diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..088b1d63531974da5c8c019fd1ff525a4f64f440 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/METADATA @@ -0,0 +1,582 @@ +Metadata-Version: 2.4 +Name: torchmetrics +Version: 1.9.0 +Summary: PyTorch native Metrics +Home-page: https://github.com/Lightning-AI/torchmetrics +Download-URL: https://github.com/Lightning-AI/torchmetrics/archive/master.zip +Author: Lightning-AI et al. +Author-email: name@pytorchlightning.ai +License: Apache-2.0 +Project-URL: Bug Tracker, https://github.com/Lightning-AI/torchmetrics/issues +Project-URL: Documentation, https://torchmetrics.rtfd.io/en/latest/ +Project-URL: Source Code, https://github.com/Lightning-AI/torchmetrics +Keywords: deep learning,machine learning,pytorch,metrics,AI +Classifier: Environment :: Console +Classifier: Natural Language :: English +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Scientific/Engineering :: Image Recognition +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy>1.20.0 +Requires-Dist: packaging>17.1 +Requires-Dist: torch>=2.0.0 +Requires-Dist: lightning-utilities>=0.15.3 +Provides-Extra: audio +Requires-Dist: requests>=2.22.0; extra == "audio" +Requires-Dist: onnxruntime>=1.12.0; extra == "audio" +Requires-Dist: gammatone>=1.0.0; extra == "audio" +Requires-Dist: pesq>=0.0.4; extra == "audio" +Requires-Dist: pystoi>=0.4.0; extra == "audio" +Requires-Dist: librosa>=0.10.0; extra == "audio" +Requires-Dist: torchaudio>=2.0.1; extra == "audio" +Provides-Extra: clustering +Requires-Dist: torch_linear_assignment>=0.0.2; extra == "clustering" +Provides-Extra: debug +Provides-Extra: detection +Requires-Dist: pycocotools>2.0.0; extra == "detection" +Requires-Dist: torchvision>=0.15.1; extra == "detection" +Provides-Extra: image +Requires-Dist: torch-fidelity<=0.4.0; extra == "image" +Requires-Dist: torchvision>=0.15.1; extra == "image" +Requires-Dist: scipy>1.0.0; extra == "image" +Provides-Extra: integrate +Provides-Extra: multimodal +Requires-Dist: timm>=0.9.0; extra == "multimodal" +Requires-Dist: transformers>=4.43.0; extra == "multimodal" +Requires-Dist: einops>=0.7.0; extra == "multimodal" +Requires-Dist: piq<=0.8.0; extra == "multimodal" +Provides-Extra: text +Requires-Dist: tqdm<4.68.0; extra == "text" +Requires-Dist: nltk>3.8.1; extra == "text" +Requires-Dist: ipadic>=1.0.0; extra == "text" +Requires-Dist: mecab-python3>=1.0.6; extra == "text" +Requires-Dist: transformers>=4.43.0; extra == "text" +Requires-Dist: regex>=2021.9.24; extra == "text" +Requires-Dist: sentencepiece>=0.2.0; extra == "text" +Provides-Extra: typing +Requires-Dist: types-six; extra == "typing" +Requires-Dist: mypy==1.17.1; extra == "typing" +Requires-Dist: types-requests; extra == "typing" +Requires-Dist: types-tabulate; extra == "typing" +Requires-Dist: types-setuptools; extra == "typing" +Requires-Dist: types-emoji; extra == "typing" +Requires-Dist: torch==2.8.0; extra == "typing" +Requires-Dist: types-PyYAML; extra == "typing" +Requires-Dist: types-protobuf; extra == "typing" +Provides-Extra: video +Requires-Dist: vmaf-torch>=1.1.0; extra == "video" +Requires-Dist: einops>=0.7.0; extra == "video" +Provides-Extra: visual +Requires-Dist: matplotlib>=3.6.0; extra == "visual" +Requires-Dist: SciencePlots>=2.0.0; extra == "visual" +Provides-Extra: all +Requires-Dist: requests>=2.22.0; extra == "all" +Requires-Dist: onnxruntime>=1.12.0; extra == "all" +Requires-Dist: gammatone>=1.0.0; extra == "all" +Requires-Dist: pesq>=0.0.4; extra == "all" +Requires-Dist: pystoi>=0.4.0; extra == "all" +Requires-Dist: librosa>=0.10.0; extra == "all" +Requires-Dist: torchaudio>=2.0.1; extra == "all" +Requires-Dist: torch_linear_assignment>=0.0.2; extra == "all" +Requires-Dist: pycocotools>2.0.0; extra == "all" +Requires-Dist: torchvision>=0.15.1; extra == "all" +Requires-Dist: torch-fidelity<=0.4.0; extra == "all" +Requires-Dist: torchvision>=0.15.1; extra == "all" +Requires-Dist: scipy>1.0.0; extra == "all" +Requires-Dist: timm>=0.9.0; extra == "all" +Requires-Dist: transformers>=4.43.0; extra == "all" +Requires-Dist: einops>=0.7.0; extra == "all" +Requires-Dist: piq<=0.8.0; extra == "all" +Requires-Dist: tqdm<4.68.0; extra == "all" +Requires-Dist: nltk>3.8.1; extra == "all" +Requires-Dist: ipadic>=1.0.0; extra == "all" +Requires-Dist: mecab-python3>=1.0.6; extra == "all" +Requires-Dist: transformers>=4.43.0; extra == "all" +Requires-Dist: regex>=2021.9.24; extra == "all" +Requires-Dist: sentencepiece>=0.2.0; extra == "all" +Requires-Dist: types-six; extra == "all" +Requires-Dist: mypy==1.17.1; extra == "all" +Requires-Dist: types-requests; extra == "all" +Requires-Dist: types-tabulate; extra == "all" +Requires-Dist: types-setuptools; extra == "all" +Requires-Dist: types-emoji; extra == "all" +Requires-Dist: torch==2.8.0; extra == "all" +Requires-Dist: types-PyYAML; extra == "all" +Requires-Dist: types-protobuf; extra == "all" +Requires-Dist: vmaf-torch>=1.1.0; extra == "all" +Requires-Dist: einops>=0.7.0; extra == "all" +Requires-Dist: matplotlib>=3.6.0; extra == "all" +Requires-Dist: SciencePlots>=2.0.0; extra == "all" +Provides-Extra: dev +Requires-Dist: requests>=2.22.0; extra == "dev" +Requires-Dist: onnxruntime>=1.12.0; extra == "dev" +Requires-Dist: gammatone>=1.0.0; extra == "dev" +Requires-Dist: pesq>=0.0.4; extra == "dev" +Requires-Dist: pystoi>=0.4.0; extra == "dev" +Requires-Dist: librosa>=0.10.0; extra == "dev" +Requires-Dist: torchaudio>=2.0.1; extra == "dev" +Requires-Dist: torch_linear_assignment>=0.0.2; extra == "dev" +Requires-Dist: pycocotools>2.0.0; extra == "dev" +Requires-Dist: torchvision>=0.15.1; extra == "dev" +Requires-Dist: torch-fidelity<=0.4.0; extra == "dev" +Requires-Dist: torchvision>=0.15.1; extra == "dev" +Requires-Dist: scipy>1.0.0; extra == "dev" +Requires-Dist: timm>=0.9.0; extra == "dev" +Requires-Dist: transformers>=4.43.0; extra == "dev" +Requires-Dist: einops>=0.7.0; extra == "dev" +Requires-Dist: piq<=0.8.0; extra == "dev" +Requires-Dist: tqdm<4.68.0; extra == "dev" +Requires-Dist: nltk>3.8.1; extra == "dev" +Requires-Dist: ipadic>=1.0.0; extra == "dev" +Requires-Dist: mecab-python3>=1.0.6; extra == "dev" +Requires-Dist: transformers>=4.43.0; extra == "dev" +Requires-Dist: regex>=2021.9.24; extra == "dev" +Requires-Dist: sentencepiece>=0.2.0; extra == "dev" +Requires-Dist: types-six; extra == "dev" +Requires-Dist: mypy==1.17.1; extra == "dev" +Requires-Dist: types-requests; extra == "dev" +Requires-Dist: types-tabulate; extra == "dev" +Requires-Dist: types-setuptools; extra == "dev" +Requires-Dist: types-emoji; extra == "dev" +Requires-Dist: torch==2.8.0; extra == "dev" +Requires-Dist: types-PyYAML; extra == "dev" +Requires-Dist: types-protobuf; extra == "dev" +Requires-Dist: vmaf-torch>=1.1.0; extra == "dev" +Requires-Dist: einops>=0.7.0; extra == "dev" +Requires-Dist: matplotlib>=3.6.0; extra == "dev" +Requires-Dist: SciencePlots>=2.0.0; extra == "dev" +Requires-Dist: pytorch-msssim==1.0.0; extra == "dev" +Requires-Dist: sewar>=0.4.4; extra == "dev" +Requires-Dist: setuptools<82.0.0; extra == "dev" +Requires-Dist: scikit-image>=0.19.0; extra == "dev" +Requires-Dist: dists-pytorch==0.1; extra == "dev" +Requires-Dist: rouge-score>0.1.0; extra == "dev" +Requires-Dist: netcal>1.0.0; extra == "dev" +Requires-Dist: pandas>1.4.0; extra == "dev" +Requires-Dist: numpy<2.4.0; extra == "dev" +Requires-Dist: torch_complex<0.5.0; extra == "dev" +Requires-Dist: permetrics==2.0.0; extra == "dev" +Requires-Dist: jiwer>=2.3.0; extra == "dev" +Requires-Dist: aeon>=1.0.0; python_version > "3.10" and extra == "dev" +Requires-Dist: mir-eval>=0.6; extra == "dev" +Requires-Dist: huggingface-hub<0.35; extra == "dev" +Requires-Dist: faster-coco-eval>=1.6.3; extra == "dev" +Requires-Dist: mecab-ko-dic>=1.0.0; python_version < "3.12" and extra == "dev" +Requires-Dist: monai==1.4.0; extra == "dev" +Requires-Dist: mecab-ko<1.1.0,>=1.0.0; python_version < "3.12" and extra == "dev" +Requires-Dist: bert_score==0.3.13; extra == "dev" +Requires-Dist: sacrebleu>=2.3.0; extra == "dev" +Requires-Dist: scipy>1.0.0; extra == "dev" +Requires-Dist: lpips<=0.1.4; extra == "dev" +Requires-Dist: dython==0.7.9; extra == "dev" +Requires-Dist: properscoring==0.1; extra == "dev" +Requires-Dist: fast-bss-eval>=0.1.0; extra == "dev" +Requires-Dist: PyTDC==0.4.1; (platform_system == "Windows" and python_version < "3.12") and extra == "dev" +Requires-Dist: fairlearn; extra == "dev" +Requires-Dist: kornia>=0.6.7; extra == "dev" +Requires-Dist: statsmodels>0.13.5; extra == "dev" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: download-url +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +
+ + + +**Machine learning metrics for distributed, scalable PyTorch applications.** + +______________________________________________________________________ + +

+ What is Torchmetrics • + Implementing a metric • + Built-in metrics • + Docs • + Community • + License +

+ +______________________________________________________________________ + +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/torchmetrics)](https://pypi.org/project/torchmetrics/) +[![PyPI Status](https://badge.fury.io/py/torchmetrics.svg)](https://badge.fury.io/py/torchmetrics) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/torchmetrics) +](https://pepy.tech/project/torchmetrics) +[![Conda](https://img.shields.io/conda/v/conda-forge/torchmetrics?label=conda&color=success)](https://anaconda.org/conda-forge/torchmetrics) +[![license](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/Lightning-AI/torchmetrics/blob/master/LICENSE) + +[![CI testing | CPU](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml/badge.svg?event=push)](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml) +[![Build Status](https://dev.azure.com/Lightning-AI/Metrics/_apis/build/status%2FTM.unittests?branchName=refs%2Ftags%2Fv1.9.0)](https://dev.azure.com/Lightning-AI/Metrics/_build/latest?definitionId=2&branchName=refs%2Ftags%2Fv1.9.0) +[![codecov](https://codecov.io/gh/Lightning-AI/torchmetrics/release/v1.9.0/graph/badge.svg?token=NER6LPI3HS)](https://codecov.io/gh/Lightning-AI/torchmetrics) +[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/Lightning-AI/torchmetrics/master.svg)](https://results.pre-commit.ci/latest/github/Lightning-AI/torchmetrics/master) + +[![Documentation Status](https://readthedocs.org/projects/torchmetrics/badge/?version=latest)](https://torchmetrics.readthedocs.io/en/latest/?badge=latest) +[![Discord](https://img.shields.io/discord/1077906959069626439?style=plastic)](https://discord.gg/VptPCZkGNa) +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5844769.svg)](https://doi.org/10.5281/zenodo.5844769) +[![JOSS status](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43/status.svg)](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43) + +______________________________________________________________________ + +
+ +# Looking for GPUs? + +Over 340,000 developers use [Lightning Cloud](https://lightning.ai/?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme) - purpose-built for PyTorch and PyTorch Lightning. + +- [GPUs](https://lightning.ai/pricing?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme) from $0.19. +- [Clusters](https://lightning.ai/clusters?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): frontier-grade training/inference clusters. +- [AI Studio (vibe train)](https://lightning.ai/studios?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): workspaces where AI helps you debug, tune and vibe train. +- [AI Studio (vibe deploy)](https://lightning.ai/studios?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): workspaces where AI helps you optimize, and deploy models. +- [Notebooks](https://lightning.ai/notebooks?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): Persistent GPU workspaces where AI helps you code and analyze. +- [Inference](https://lightning.ai/deploy?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): Deploy models as inference APIs. + +# Installation + +Simple installation from PyPI + +```bash +pip install torchmetrics +``` + +
+ Other installations + +Install using conda + +```bash +conda install -c conda-forge torchmetrics +``` + +Install using uv + +```bash +uv add torchmetrics +``` + +Pip from source + +```bash +# with git +pip install git+https://github.com/Lightning-AI/torchmetrics.git@release/stable +``` + +Pip from archive + +```bash +pip install https://github.com/Lightning-AI/torchmetrics/archive/refs/heads/release/stable.zip +``` + +Extra dependencies for specialized metrics: + +```bash +pip install torchmetrics[audio] +pip install torchmetrics[image] +pip install torchmetrics[text] +pip install torchmetrics[all] # install all of the above +``` + +Install latest developer version + +```bash +pip install https://github.com/Lightning-AI/torchmetrics/archive/master.zip +``` + +
+ +______________________________________________________________________ + +# What is TorchMetrics + +TorchMetrics is a collection of 100+ PyTorch metrics implementations and an easy-to-use API to create custom metrics. It offers: + +- A standardized interface to increase reproducibility +- Reduces boilerplate +- Automatic accumulation over batches +- Metrics optimized for distributed-training +- Automatic synchronization between multiple devices + +You can use TorchMetrics with any PyTorch model or with [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/) to enjoy additional features such as: + +- Module metrics are automatically placed on the correct device. +- Native support for logging metrics in Lightning to reduce even more boilerplate. + +# Using TorchMetrics + +### Module metrics + +The [module-based metrics](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) contain internal metric states (similar to the parameters of the PyTorch module) that automate accumulation and synchronization across devices! + +- Automatic accumulation over multiple batches +- Automatic synchronization between multiple devices +- Metric arithmetic + +**This can be run on CPU, single GPU or multi-GPUs!** + +For the single GPU/CPU case: + +```python +import torch + +# import our library +import torchmetrics + +# initialize metric +metric = torchmetrics.classification.Accuracy(task="multiclass", num_classes=5) + +# move the metric to device you want computations to take place +device = "cuda" if torch.cuda.is_available() else "cpu" +metric.to(device) + +n_batches = 10 +for i in range(n_batches): + # simulate a classification problem + preds = torch.randn(10, 5).softmax(dim=-1).to(device) + target = torch.randint(5, (10,)).to(device) + + # metric on current batch + acc = metric(preds, target) + print(f"Accuracy on batch {i}: {acc}") + +# metric on all batches using custom accumulation +acc = metric.compute() +print(f"Accuracy on all data: {acc}") +``` + +Module metric usage remains the same when using multiple GPUs or multiple nodes. + +
+ Example using DDP + + + +```python +import os +import torch +import torch.distributed as dist +import torch.multiprocessing as mp +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +import torchmetrics + + +def metric_ddp(rank, world_size): + os.environ["MASTER_ADDR"] = "localhost" + os.environ["MASTER_PORT"] = "12355" + + # create default process group + dist.init_process_group("gloo", rank=rank, world_size=world_size) + + # initialize model + metric = torchmetrics.classification.Accuracy(task="multiclass", num_classes=5) + + # define a model and append your metric to it + # this allows metric states to be placed on correct accelerators when + # .to(device) is called on the model + model = nn.Linear(10, 10) + model.metric = metric + model = model.to(rank) + + # initialize DDP + model = DDP(model, device_ids=[rank]) + + n_epochs = 5 + # this shows iteration over multiple training epochs + for n in range(n_epochs): + # this will be replaced by a DataLoader with a DistributedSampler + n_batches = 10 + for i in range(n_batches): + # simulate a classification problem + preds = torch.randn(10, 5).softmax(dim=-1) + target = torch.randint(5, (10,)) + + # metric on current batch + acc = metric(preds, target) + if rank == 0: # print only for rank 0 + print(f"Accuracy on batch {i}: {acc}") + + # metric on all batches and all accelerators using custom accumulation + # accuracy is same across both accelerators + acc = metric.compute() + print(f"Accuracy on all data: {acc}, accelerator rank: {rank}") + + # Resetting internal state such that metric ready for new data + metric.reset() + + # cleanup + dist.destroy_process_group() + + +if __name__ == "__main__": + world_size = 2 # number of gpus to parallelize over + mp.spawn(metric_ddp, args=(world_size,), nprocs=world_size, join=True) +``` + +
+ +### Implementing your own Module metric + +Implementing your own metric is as easy as subclassing an [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). Simply, subclass `torchmetrics.Metric` +and just implement the `update` and `compute` methods: + +```python +import torch +from torchmetrics import Metric + + +class MyAccuracy(Metric): + def __init__(self): + # remember to call super + super().__init__() + # call `self.add_state`for every internal state that is needed for the metrics computations + # dist_reduce_fx indicates the function that should be used to reduce + # state from multiple processes + self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum") + self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") + + def update(self, preds: torch.Tensor, target: torch.Tensor) -> None: + # extract predicted class index for computing accuracy + preds = preds.argmax(dim=-1) + assert preds.shape == target.shape + # update metric states + self.correct += torch.sum(preds == target) + self.total += target.numel() + + def compute(self) -> torch.Tensor: + # compute final result + return self.correct.float() / self.total + + +my_metric = MyAccuracy() +preds = torch.randn(10, 5).softmax(dim=-1) +target = torch.randint(5, (10,)) + +print(my_metric(preds, target)) +``` + +### Functional metrics + +Similar to [`torch.nn`](https://pytorch.org/docs/stable/nn.html), most metrics have both a [module-based](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) and functional version. +The functional versions are simple python functions that as input take [torch.tensors](https://pytorch.org/docs/stable/tensors.html) and return the corresponding metric as a [torch.tensor](https://pytorch.org/docs/stable/tensors.html). + +```python +import torch + +# import our library +import torchmetrics + +# simulate a classification problem +preds = torch.randn(10, 5).softmax(dim=-1) +target = torch.randint(5, (10,)) + +acc = torchmetrics.functional.classification.multiclass_accuracy( + preds, target, num_classes=5 +) +``` + +### Covered domains and example metrics + +In total TorchMetrics contains [100+ metrics](https://lightning.ai/docs/torchmetrics/stable/all-metrics.html), which +covers the following domains: + +- Audio +- Classification +- Detection +- Information Retrieval +- Image +- Multimodal (Image-Text-3D Talking Heads) +- Nominal +- Regression +- Segmentation +- Text + +Each domain may require some additional dependencies which can be installed with `pip install torchmetrics[audio]`, +`pip install torchmetrics['image']` etc. + +### Additional features + +#### Plotting + +Visualization of metrics can be important to help understand what is going on with your machine learning algorithms. +Torchmetrics have built-in plotting support (install dependencies with `pip install torchmetrics[visual]`) for nearly +all modular metrics through the `.plot` method. Simply call the method to get a simple visualization of any metric! + +```python +import torch +from torchmetrics.classification import MulticlassAccuracy, MulticlassConfusionMatrix + +num_classes = 3 + +# this will generate two distributions that comes more similar as iterations increase +w = torch.randn(num_classes) +target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True) +preds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True) + +acc = MulticlassAccuracy(num_classes=num_classes, average="micro") +acc_per_class = MulticlassAccuracy(num_classes=num_classes, average=None) +confmat = MulticlassConfusionMatrix(num_classes=num_classes) + +# plot single value +for i in range(5): + acc_per_class.update(preds(i), target(i)) + confmat.update(preds(i), target(i)) +fig1, ax1 = acc_per_class.plot() +fig2, ax2 = confmat.plot() + +# plot multiple values +values = [] +for i in range(10): + values.append(acc(preds(i), target(i))) +fig3, ax3 = acc.plot(values) +``` + +

+ +

+ +For examples of plotting different metrics try running [this example file](_samples/plotting.py). + +# Contribute! + +The lightning + TorchMetrics team is hard at work adding even more metrics. +But we're looking for incredible contributors like you to submit new metrics +and improve existing ones! + +Join our [Discord](https://discord.com/invite/tfXFetEZxv) to get help with becoming a contributor! + +# Community + +For help or questions, join our huge community on [Discord](https://discord.com/invite/tfXFetEZxv)! + +# Citation + +We’re excited to continue the strong legacy of open source software and have been inspired +over the years by Caffe, Theano, Keras, PyTorch, torchbearer, ignite, sklearn and fast.ai. + +If you want to cite this framework feel free to use GitHub's built-in citation option to generate a bibtex or APA-Style citation based on [this file](https://github.com/Lightning-AI/torchmetrics/blob/master/CITATION.cff) (but only if you loved it 😊). + +# License + +Please observe the Apache 2.0 license that is listed in this repository. +In addition, the Lightning framework is Patent Pending. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d28003d16abe9929b5abb51b9943f0dda5a2db31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/RECORD @@ -0,0 +1,709 @@ +torchmetrics-1.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +torchmetrics-1.9.0.dist-info/METADATA,sha256=6aaxD25cq-5RUK_DDtcP3RTlVrG4VpeaM0HSy6Ibqt0,23134 +torchmetrics-1.9.0.dist-info/RECORD,, +torchmetrics-1.9.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +torchmetrics-1.9.0.dist-info/licenses/LICENSE,sha256=-jH0M_W0vB-3MPucZ4-QGC2Tv3a22Yuk0A9ARUrIuDI,11352 +torchmetrics-1.9.0.dist-info/top_level.txt,sha256=wUt7Alce9yBXuCXPU2Mcfh3_6ZjoYejoj2silrPGA_Q,13 +torchmetrics/__about__.py,sha256=D5zucYwCJrFMOc_8wbvI8p-r8XRT-j6kVaOvw_dNfnU,1239 +torchmetrics/__init__.py,sha256=NinAv0FcLhc4rO-8cH_FXB-0cEqvI38uZL0v6sYk6Ls,9490 +torchmetrics/__pycache__/__about__.cpython-310.pyc,, +torchmetrics/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/__pycache__/aggregation.cpython-310.pyc,, +torchmetrics/__pycache__/collections.cpython-310.pyc,, +torchmetrics/__pycache__/metric.cpython-310.pyc,, +torchmetrics/aggregation.py,sha256=0b56QtlPggVi4YC0oPeLlYvFOD1Q7IWKhRtKIBLRqII,28384 +torchmetrics/audio/__init__.py,sha256=yRvq2xMGIOveZSWYGqhRF01oLpvWej_iyc4vn6UQqew,2536 +torchmetrics/audio/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/audio/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/audio/__pycache__/dnsmos.cpython-310.pyc,, +torchmetrics/audio/__pycache__/nisqa.cpython-310.pyc,, +torchmetrics/audio/__pycache__/pesq.cpython-310.pyc,, +torchmetrics/audio/__pycache__/pit.cpython-310.pyc,, +torchmetrics/audio/__pycache__/sdr.cpython-310.pyc,, +torchmetrics/audio/__pycache__/snr.cpython-310.pyc,, +torchmetrics/audio/__pycache__/srmr.cpython-310.pyc,, +torchmetrics/audio/__pycache__/stoi.cpython-310.pyc,, +torchmetrics/audio/_deprecated.py,sha256=-_Q_my6O20Itu7ISoyKqZz3NmN6xMk4uTH8s48BV4Ag,4065 +torchmetrics/audio/dnsmos.py,sha256=DVBuN07qox7KNNDCZ3my0PjL2hZtkIYfqux5prjZgI4,8057 +torchmetrics/audio/nisqa.py,sha256=_m9EeZQfEd0MNwlwZACOOQAuSScpgoERrtieFuyzAdk,6027 +torchmetrics/audio/pesq.py,sha256=l5Y0ClQhqnWiKkmBD0W9fwt80qE6QsO62USvZhPn1is,7348 +torchmetrics/audio/pit.py,sha256=TxGn-jDkK3yVavjnRTxCKMWVovQzoijiZKNSkIfQpbo,6914 +torchmetrics/audio/sdr.py,sha256=aQzlxGiONWBfNWxzAgLLmkrL9vjDh--2an2-SdETbYg,15295 +torchmetrics/audio/snr.py,sha256=FJQKwuHUoB8Q--mlrDKL3sH6kdpZTlkupP60UpQsvQU,12701 +torchmetrics/audio/srmr.py,sha256=HxYPY1sh8b26iZw5jc1BnHwa_LRD5el58Ogec0HjY9U,7378 +torchmetrics/audio/stoi.py,sha256=ZtaXNTieNiDuhfntrPP_1Mu1TxEBr9hAxC0vz1RyJ34,6428 +torchmetrics/classification/__init__.py,sha256=DWUA3NXdeh20ZyFuLGQ6QKcoGM1aZfT6XKPqwhhkW9Q,7467 +torchmetrics/classification/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/classification/__pycache__/accuracy.cpython-310.pyc,, +torchmetrics/classification/__pycache__/auroc.cpython-310.pyc,, +torchmetrics/classification/__pycache__/average_precision.cpython-310.pyc,, +torchmetrics/classification/__pycache__/base.cpython-310.pyc,, +torchmetrics/classification/__pycache__/calibration_error.cpython-310.pyc,, +torchmetrics/classification/__pycache__/cohen_kappa.cpython-310.pyc,, +torchmetrics/classification/__pycache__/confusion_matrix.cpython-310.pyc,, +torchmetrics/classification/__pycache__/eer.cpython-310.pyc,, +torchmetrics/classification/__pycache__/exact_match.cpython-310.pyc,, +torchmetrics/classification/__pycache__/f_beta.cpython-310.pyc,, +torchmetrics/classification/__pycache__/group_fairness.cpython-310.pyc,, +torchmetrics/classification/__pycache__/hamming.cpython-310.pyc,, +torchmetrics/classification/__pycache__/hinge.cpython-310.pyc,, +torchmetrics/classification/__pycache__/jaccard.cpython-310.pyc,, +torchmetrics/classification/__pycache__/logauc.cpython-310.pyc,, +torchmetrics/classification/__pycache__/matthews_corrcoef.cpython-310.pyc,, +torchmetrics/classification/__pycache__/negative_predictive_value.cpython-310.pyc,, +torchmetrics/classification/__pycache__/precision_fixed_recall.cpython-310.pyc,, +torchmetrics/classification/__pycache__/precision_recall.cpython-310.pyc,, +torchmetrics/classification/__pycache__/precision_recall_curve.cpython-310.pyc,, +torchmetrics/classification/__pycache__/ranking.cpython-310.pyc,, +torchmetrics/classification/__pycache__/recall_fixed_precision.cpython-310.pyc,, +torchmetrics/classification/__pycache__/roc.cpython-310.pyc,, +torchmetrics/classification/__pycache__/sensitivity_specificity.cpython-310.pyc,, +torchmetrics/classification/__pycache__/specificity.cpython-310.pyc,, +torchmetrics/classification/__pycache__/specificity_sensitivity.cpython-310.pyc,, +torchmetrics/classification/__pycache__/stat_scores.cpython-310.pyc,, +torchmetrics/classification/accuracy.py,sha256=li5d2sLrZMU11EOJxwbf0k5CVf4EbzykR1qhEOqK44Q,23408 +torchmetrics/classification/auroc.py,sha256=SAb3TdBVCWpoZ2ki2ftiL2rqK5S08Fntej2Tc1lTrG0,25595 +torchmetrics/classification/average_precision.py,sha256=OxolA2NDz6K3C_LuL5_cexeVvOU_5pYJgBhpqYF3dQ0,25457 +torchmetrics/classification/base.py,sha256=V5wu8vUqgJ23upaI4alsL7019gkL9H3k4A1-oXG4FXY,1234 +torchmetrics/classification/calibration_error.py,sha256=ZJgJcbtCMPgE2jgwrV6Kl-vlyG78JJfTMa49rhO9tLE,17288 +torchmetrics/classification/cohen_kappa.py,sha256=UVTRv8x9_s4-Ixnxl7qf8yWzRZGKyK5JctcHTz5LuT0,13717 +torchmetrics/classification/confusion_matrix.py,sha256=ulifUwFRmr45Gw-K-grd_nliQYUwKtJrx2Dt-e9oowg,23841 +torchmetrics/classification/eer.py,sha256=c_BFrYkbdRu2cuJftio_r4NP2u4CR187vp1k4cWTG-A,21210 +torchmetrics/classification/exact_match.py,sha256=i1WQDaRYUYzxaiBeJEAtcXSJVEPjr8rELrDtEcMhKI4,20293 +torchmetrics/classification/f_beta.py,sha256=1YxmohjAAwMXybbf2p7tncdseJthu9XRbCrQMkWsjss,54228 +torchmetrics/classification/group_fairness.py,sha256=gaTZRXdEdpFwwOpvbpSo4zr0nm-S1nd2CiYWZoZrs1I,13784 +torchmetrics/classification/hamming.py,sha256=LNEJxKWB_jr4QCkACseoY42mnFlrYSNidHsMMuCCrpA,24081 +torchmetrics/classification/hinge.py,sha256=djewxadp9uubjuXIX-zpuHgLmcettQUwHM3k9eG0UEo,15828 +torchmetrics/classification/jaccard.py,sha256=KoQZwZ6plXFqtrdGl3gTpJNv19g2Wo471tMA1x3aexg,20552 +torchmetrics/classification/logauc.py,sha256=syZ1mL2VEWanxVEGQx4bj5kCprZjFLzXLVRhpxFl8KY,23446 +torchmetrics/classification/matthews_corrcoef.py,sha256=SucLKvwnTJIQCbBhV8lTrUWTowzxfNCz-QOrK-GVA1U,17086 +torchmetrics/classification/negative_predictive_value.py,sha256=HA6enJuGNAtlFLnDug9pOUgjGXLGbuwcD4mq8VxNDSo,24587 +torchmetrics/classification/precision_fixed_recall.py,sha256=pRTECzSJbsoDTHkPAY8YICc9wM2pw7RMmNEC0sw9kqo,25300 +torchmetrics/classification/precision_recall.py,sha256=gbPlpSJTiV9v4pCeGoFnZ1Xaj1oJneGfiVGcDC1nMRs,48258 +torchmetrics/classification/precision_recall_curve.py,sha256=uDIdQqBLI4TRPb0kd-rE2bTUDwqpzxKj7FgJVcMOtEE,35413 +torchmetrics/classification/ranking.py,sha256=KHs7A1VZvDIZmZWMzpAW34yi9DStNTzU77iuOpo3cCo,18332 +torchmetrics/classification/recall_fixed_precision.py,sha256=gahv-ypAqMrkUY60uAL1OSEtqQimWctLievklKJLJqY,25272 +torchmetrics/classification/roc.py,sha256=tN3bZ56NdyhyyvVLki1fdMzAZRf1W3_dUwH1V8IgAB8,30543 +torchmetrics/classification/sensitivity_specificity.py,sha256=ml2-satmeUB6uKpy_meXeaHHIIZAEnlJ8erR8S9i-AI,18702 +torchmetrics/classification/specificity.py,sha256=KvZwwWhaL3h1ZR5lSnJ748ChLno-uq_kbT8x-M9vMtM,23645 +torchmetrics/classification/specificity_sensitivity.py,sha256=qc59pDyFIXxPNMZIy_6ikOLmsCovyYDCxIkxR8mro8s,18811 +torchmetrics/classification/stat_scores.py,sha256=MOVEwrA6kt0SaSMKrx9DOsg-6-0lL-25lu-aIhYY-2Q,26230 +torchmetrics/clustering/__init__.py,sha256=7i2WpseBvmmLmBboB6CSCZiU_WebDOaM1KGUMLT0PEY,1794 +torchmetrics/clustering/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/adjusted_mutual_info_score.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/adjusted_rand_score.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/calinski_harabasz_score.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/cluster_accuracy.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/davies_bouldin_score.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/dunn_index.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/fowlkes_mallows_index.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/homogeneity_completeness_v_measure.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/mutual_info_score.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/normalized_mutual_info_score.cpython-310.pyc,, +torchmetrics/clustering/__pycache__/rand_score.cpython-310.pyc,, +torchmetrics/clustering/adjusted_mutual_info_score.py,sha256=0vi2mjpjSrEFrfoxmZXX0Cf89BD_N7V60CdgZDc6yac,5389 +torchmetrics/clustering/adjusted_rand_score.py,sha256=vtA9yYIaoeStHN6qgn2omjElVvvwK9GEGCRnOqoqHEs,5191 +torchmetrics/clustering/calinski_harabasz_score.py,sha256=tu358N-itZQqrlTT0nA1t0Yu7LXiii9HJRCJ3rgghno,5357 +torchmetrics/clustering/cluster_accuracy.py,sha256=D7_Qr8feZ7AD75lOESldMuC79e5SV8yDxpAVrV1x7p0,6034 +torchmetrics/clustering/davies_bouldin_score.py,sha256=4-S5yAgbH4g2Q6id4SkB6BkaJok49DKg2kRp_k9SZJ4,5478 +torchmetrics/clustering/dunn_index.py,sha256=dfGpxsESjwFErInYSac345XE_aWj9rzfhehZq6xpFcI,5014 +torchmetrics/clustering/fowlkes_mallows_index.py,sha256=Yl5qiFxoH3_Nf5XjGipRLKeUR81NCZk1oQifc2Ppyhw,4619 +torchmetrics/clustering/homogeneity_completeness_v_measure.py,sha256=j2JlfxjUPdVvy01lELlyvwZ0ri4OqyoXw4yN15S_J08,12969 +torchmetrics/clustering/mutual_info_score.py,sha256=VyZqKcF4qMGZwLPX-_UmGW0ZFE8OpLj9wJU520aaoVw,5044 +torchmetrics/clustering/normalized_mutual_info_score.py,sha256=Xt0NuydOkm0dZ6wGnm-oHxU8tjTe16Opsuf9tnThNJE,5282 +torchmetrics/clustering/rand_score.py,sha256=kFZzSBMXtSex74q4XFNwdFFNRrfp5hbuV4GEqSjKdhY,4886 +torchmetrics/collections.py,sha256=swVhMCOmaRfV55Y56SrZw1ENzMBD6lQXYW_EhhLz24g,33319 +torchmetrics/detection/__init__.py,sha256=52oQOnyWr0b4Pa5do22VYW2kcdK1wxc1ct-LqnCHLC0,1398 +torchmetrics/detection/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/detection/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/detection/__pycache__/_mean_ap.cpython-310.pyc,, +torchmetrics/detection/__pycache__/ciou.cpython-310.pyc,, +torchmetrics/detection/__pycache__/diou.cpython-310.pyc,, +torchmetrics/detection/__pycache__/giou.cpython-310.pyc,, +torchmetrics/detection/__pycache__/helpers.cpython-310.pyc,, +torchmetrics/detection/__pycache__/iou.cpython-310.pyc,, +torchmetrics/detection/__pycache__/mean_ap.cpython-310.pyc,, +torchmetrics/detection/__pycache__/panoptic_qualities.cpython-310.pyc,, +torchmetrics/detection/_deprecated.py,sha256=SSLnxdFWx8BAFTd5Rd8salDvHP0TUCwjQxV2vEpu14g,2359 +torchmetrics/detection/_mean_ap.py,sha256=FH-1pw2HFUIqYpM6fJn5i8YRHABxJpPhO7nEMSg5-4Q,43130 +torchmetrics/detection/ciou.py,sha256=S0D_1Nh8-IvI5jpeI71I7TdZttAFwDRo03wJaaYxKp4,8176 +torchmetrics/detection/diou.py,sha256=PjjWFXu8Vfxpf4NYVVOo5fAUBFHuQo1RiN0cFVk3z48,8133 +torchmetrics/detection/giou.py,sha256=_0SaXFbtLcQUZAfzakl8AIZAR3uDeC2EO_PC41m97eA,7899 +torchmetrics/detection/helpers.py,sha256=Q6UpNZ00BC2RMRsTYV-NOj7X6HQFDdOXTfq8kmdHC3s,36145 +torchmetrics/detection/iou.py,sha256=swTsOn1r768KYd6lpEhsRinBBDmHlmopBuNfYtg3nPU,13195 +torchmetrics/detection/mean_ap.py,sha256=tDxJHsFaCf2uihU8QOPL7yIZcDbbg8ujMKCuWFhVBbk,33109 +torchmetrics/detection/panoptic_qualities.py,sha256=gVOdRYu9wcrmj-NCfSJbbQOfsR-vMpNzmKa075Qmkbg,22057 +torchmetrics/functional/__init__.py,sha256=8_bsjdxoMayi-o2VvkSrHc34-lHyrlDKpForqSsS4SM,9825 +torchmetrics/functional/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/audio/__init__.py,sha256=Wm3T4Yg21V1PQz8K_oviNepH26pLxipN_dcoXDwp_1w,2744 +torchmetrics/functional/audio/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/dnsmos.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/nisqa.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/pesq.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/pit.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/sdr.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/snr.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/srmr.cpython-310.pyc,, +torchmetrics/functional/audio/__pycache__/stoi.cpython-310.pyc,, +torchmetrics/functional/audio/_deprecated.py,sha256=Nsfcx04pVCRoFOHP7QSGOYiNNpEBrNViYr9k0uBxdzY,4431 +torchmetrics/functional/audio/dnsmos.py,sha256=h4zYSzUd7i0YDYRsaOG2BuUk8wiwvm4FG0C4mTQVOyY,11843 +torchmetrics/functional/audio/nisqa.py,sha256=XH6yDuY06sHESP3tSKZrr5CLx2qedO8uOGHe7bxkP9E,16465 +torchmetrics/functional/audio/pesq.py,sha256=Da09vsLFJngu4hGibzHLF2Jnpfu-FnlMf8BDLfbBH18,5029 +torchmetrics/functional/audio/pit.py,sha256=Ju7x4uL4PTJE0tdKQFaSqrPMxQnfBxAokaPDxRbwO3I,9834 +torchmetrics/functional/audio/sdr.py,sha256=PC5NwI7Py-CmrirHCebelerStEhRRfJ_43fJXiLBEk8,11910 +torchmetrics/functional/audio/snr.py,sha256=jrr7-_oSTXw_qHUgGUTaaQ063OJDw2UpGuaxVFP9LOg,5002 +torchmetrics/functional/audio/srmr.py,sha256=ktp7whxQrKm3kU6XP9yvdvn0x1d5jjaYfLdt7azPTsA,14170 +torchmetrics/functional/audio/stoi.py,sha256=g6rfViTkjy9zA-_Iit6VMTYDRPO3kVg-OekrVtESzRA,4217 +torchmetrics/functional/classification/__init__.py,sha256=fywVnR_Hdh9zW7DHuqMx2COZqPjN2UaKSqAqM-VZKgk,8295 +torchmetrics/functional/classification/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/accuracy.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/auroc.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/average_precision.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/calibration_error.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/cohen_kappa.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/confusion_matrix.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/eer.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/exact_match.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/f_beta.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/group_fairness.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/hamming.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/hinge.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/jaccard.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/logauc.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/matthews_corrcoef.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/negative_predictive_value.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/precision_fixed_recall.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/precision_recall.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/precision_recall_curve.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/ranking.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/recall_fixed_precision.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/roc.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/sensitivity_specificity.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/specificity.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/specificity_sensitivity.cpython-310.pyc,, +torchmetrics/functional/classification/__pycache__/stat_scores.cpython-310.pyc,, +torchmetrics/functional/classification/accuracy.py,sha256=oN2_8ExcHx0E9TcDevuyicC2O2ScMRzUJmtnMluk-oI,20039 +torchmetrics/functional/classification/auroc.py,sha256=s5PhrMKJjoCO6FOOuMFJ0zMp7W6-_JjWnvaFx2WK5bU,23714 +torchmetrics/functional/classification/average_precision.py,sha256=8JLUguxEVel5K6HEQ5xF0FaXnTB9H4NUMEeMv_QYzYw,23577 +torchmetrics/functional/classification/calibration_error.py,sha256=HRg8c73p3uvTykykPx0gPM7UlX-IHgzPBT037z5Quac,16976 +torchmetrics/functional/classification/cohen_kappa.py,sha256=GhLGVkiU6oX6Av99uGNbAiywPE8UF8eoapRMFkVhlIM,11633 +torchmetrics/functional/classification/confusion_matrix.py,sha256=IZtK8pY36posNW7FUEAqViQdGS9amO3r01iXUE23qAw,27785 +torchmetrics/functional/classification/eer.py,sha256=92hHrYFpaJ9AjafQXjkiS2OVXzTvZDXPA4W-Xl6KOCE,13176 +torchmetrics/functional/classification/exact_match.py,sha256=bvJUNWa0VnHNeGC7sQBQZ0RUD3O--ml8gk-YxqlYeg8,11963 +torchmetrics/functional/classification/f_beta.py,sha256=d03WGgnIcF6TBW6XbDELlaqzqxKJL-zTGcQo4LU4hhw,37936 +torchmetrics/functional/classification/group_fairness.py,sha256=IPgJgQsoWuzv5fgst5O4dkYu-1L5kYh8MAifz3kUpqs,16872 +torchmetrics/functional/classification/hamming.py,sha256=AWxWwllptTn0GpNOmewLvatwLKuFgBNr0hDdR64Ujyc,20726 +torchmetrics/functional/classification/hinge.py,sha256=T_cFHhhZKlAkII5Jx5HMAr27IwV0cv9bMzctWuqa7Ks,12404 +torchmetrics/functional/classification/jaccard.py,sha256=upbjIwzZ_ggVezBVNZNWKqltQSiviv4B-N0P5u0y71s,17235 +torchmetrics/functional/classification/logauc.py,sha256=o5P1iu538mLtGDo1n0Rv1as6_HxXDgq3cmhm1hK0g5Q,17864 +torchmetrics/functional/classification/matthews_corrcoef.py,sha256=JJIQigQt7xGoElLHjzEAU2CF5Yqonl_IUzCO3BpF-tY,12855 +torchmetrics/functional/classification/negative_predictive_value.py,sha256=9vO9brzv2Ubmp_LFkKztfcjv0YdapkZm2Ata7DFT-8Q,20655 +torchmetrics/functional/classification/precision_fixed_recall.py,sha256=NMo_KziOn0iJfsLx4suWy0YXAGklpW5ZCy9fqrZdoEQ,18024 +torchmetrics/functional/classification/precision_recall.py,sha256=IWYoKEPs3HUf1Mqf3U9aVMSK0CzjXO74V2iEJ5wS-fs,36816 +torchmetrics/functional/classification/precision_recall_curve.py,sha256=ne1lHINYQVdzmIilMgiNO7_x83v7nB-Pn9bOT4rSBq4,47564 +torchmetrics/functional/classification/ranking.py,sha256=ndKaQlMPDW36EJ6r-2jZZZX7Kr6TGlr4rGrC2Br9z8Q,11377 +torchmetrics/functional/classification/recall_fixed_precision.py,sha256=SjMaETyWPwrZJaV9TX5qFMT50SopeCGwpUVERcKBCXs,21870 +torchmetrics/functional/classification/roc.py,sha256=-3nASnhSc0JKQWJBirp5Oo811bD46tblXyjZxshS-T8,28559 +torchmetrics/functional/classification/sensitivity_specificity.py,sha256=EIVTPmnhASlHBiXSMq4CfqEbdB4FFlctSvqZYhq1ZWQ,22197 +torchmetrics/functional/classification/specificity.py,sha256=U5JhctBhJk7OCgDmnUkfj5fLRBTj9WNuKFdEJ9ci4bg,18562 +torchmetrics/functional/classification/specificity_sensitivity.py,sha256=MBfj89U5MFhdxC_i6T63hjnaq7LxdDZOKmrjJdakSR4,23556 +torchmetrics/functional/classification/stat_scores.py,sha256=cH8JMBweBeFQQ3xDx0ZLuYmfHMw-2bl3y67A5So-MvY,41365 +torchmetrics/functional/clustering/__init__.py,sha256=AD1Is3Bd41C4Ux8pEr3vqbbXKoADPYggpP5Cy2W8Irs,1961 +torchmetrics/functional/clustering/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/adjusted_mutual_info_score.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/adjusted_rand_score.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/calinski_harabasz_score.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/cluster_accuracy.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/davies_bouldin_score.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/dunn_index.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/fowlkes_mallows_index.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/homogeneity_completeness_v_measure.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/mutual_info_score.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/normalized_mutual_info_score.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/rand_score.cpython-310.pyc,, +torchmetrics/functional/clustering/__pycache__/utils.cpython-310.pyc,, +torchmetrics/functional/clustering/adjusted_mutual_info_score.py,sha256=u8Bu-7oXp9SFnuhJw_Ni2Q3T_4UvJQAX6aym71bcFjw,4470 +torchmetrics/functional/clustering/adjusted_rand_score.py,sha256=S63-9ipbJ2xwdzDzkjpjKoU5AK18ajumXqJXhFIF-uU,2422 +torchmetrics/functional/clustering/calinski_harabasz_score.py,sha256=A0KO1NQQOjXKNIK0o33dr0IKfMI1-t59W7aDIAOs9SY,2432 +torchmetrics/functional/clustering/cluster_accuracy.py,sha256=CABBa3QK11i_OZG6eoDRI6fA-n1PMM0Jhmy9fofgI6g,2538 +torchmetrics/functional/clustering/davies_bouldin_score.py,sha256=kocPnHdOgG-fUB7GcAeUzqAOjkzXCT8LFf4SZQtVJCQ,2595 +torchmetrics/functional/clustering/dunn_index.py,sha256=tNmaPqi-3ageHHruNbz0f5hJ8VgkS55KG6irCGPKKls,2764 +torchmetrics/functional/clustering/fowlkes_mallows_index.py,sha256=fvY5b869WfAyEcoAnNKH6uYhNBgBcIbWBKI-AOIeaWI,2477 +torchmetrics/functional/clustering/homogeneity_completeness_v_measure.py,sha256=gQFqVNpPyef8RtVxkd4snud8Ku8fTzQWlGlYYXb8w6Q,4374 +torchmetrics/functional/clustering/mutual_info_score.py,sha256=DOAZhmgC-Qj3-gtaR1XahDr6CsjLKf_bLo5OBiofmFY,2616 +torchmetrics/functional/clustering/normalized_mutual_info_score.py,sha256=QUqPGhyJqckNjzMo1_2xgbmvTkCV-e-bw78vlsyKIDg,2104 +torchmetrics/functional/clustering/rand_score.py,sha256=wpZODfoQXhG_nstuB0bmieB4aHpdMZksxWlJNtBv40g,2602 +torchmetrics/functional/clustering/utils.py,sha256=5XXzlUNdMKZj7kEpvGjjBYEjnljHudiy_RAu7QYIKaU,10090 +torchmetrics/functional/detection/__init__.py,sha256=Xo65qcNkcJbQTpex3Ym8JTIlOXkNt66G1ae7wpeVbYQ,1510 +torchmetrics/functional/detection/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/_panoptic_quality_common.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/ciou.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/diou.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/giou.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/iou.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/map.cpython-310.pyc,, +torchmetrics/functional/detection/__pycache__/panoptic_qualities.cpython-310.pyc,, +torchmetrics/functional/detection/_deprecated.py,sha256=QOLkrR_L5cYascVaOz58mm32DTe-gjFGDqTKcB56sro,2308 +torchmetrics/functional/detection/_panoptic_quality_common.py,sha256=A7LctJ-pmMMJpB4qCXhNRhpH5A4-60FcJRv3IPIMIss,20147 +torchmetrics/functional/detection/ciou.py,sha256=GDPVS1z0tLlGpZqSvJHHhK0R-aIKeq1nt84Jar3S0hY,4912 +torchmetrics/functional/detection/diou.py,sha256=D9-UygjNRESR6ft__AG0pFgBGn0q6F_gZlwfUd5yiFA,4914 +torchmetrics/functional/detection/giou.py,sha256=TYCYK6-2U2UPhnrrmsgePc8T9yfxKiXRFmhsR9_O3fs,4918 +torchmetrics/functional/detection/iou.py,sha256=k-pVlsypkbaPPDRtPJJMyR8tjUBLxes-VM8efgK32oU,4833 +torchmetrics/functional/detection/map.py,sha256=TXMFJC8hoPVkkzYA2omYwzM42XYOPhnYqWAh3K6UCmM,9732 +torchmetrics/functional/detection/panoptic_qualities.py,sha256=rR3_bXo4hS8e1KZ9NRzIIwzu9FCZSoZP9I-st0Ev4Zk,11547 +torchmetrics/functional/image/__init__.py,sha256=n4FQ3CJqqtODHOHpWmT3DQlg1e6f7YpXgoHqDuctBts,2890 +torchmetrics/functional/image/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/arniqa.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/d_lambda.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/d_s.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/dists.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/ergas.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/gradients.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/lpips.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/perceptual_path_length.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/psnr.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/psnrb.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/qnr.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/rase.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/rmse_sw.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/sam.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/scc.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/ssim.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/tv.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/uqi.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/utils.cpython-310.pyc,, +torchmetrics/functional/image/__pycache__/vif.cpython-310.pyc,, +torchmetrics/functional/image/_deprecated.py,sha256=5UaCvIG8KZPdhwHV4tZKwIFCiHCQngWa9oju0isVFx8,8940 +torchmetrics/functional/image/arniqa.py,sha256=DL71C6UqeMBiLv_CQ4psGQZ6BSSY0wfb0r_DoDcOyv8,12220 +torchmetrics/functional/image/d_lambda.py,sha256=rivTjYLrmJhdZSPcNtIHGrdVcAMTnxqIPQPlZ_0UMvE,5623 +torchmetrics/functional/image/d_s.py,sha256=dElq0cbZcSc00f9JQRhxSn3Qas-rzVOjRuvr1rdQDPc,11095 +torchmetrics/functional/image/dists.py,sha256=V3-TWDXgaPhC_2gp7gMlls_X46b4eWdJFG6SifsKG94,8930 +torchmetrics/functional/image/dists_models/weights.pt,sha256=9eZcliMLf2yplWkWR9SCI35Mq4pQxcSleE8hnvB0ghg,12288 +torchmetrics/functional/image/ergas.py,sha256=S0nZ6EHupd9e5yu9XRFyf-Pngwisv5TX_65niiKbXko,4167 +torchmetrics/functional/image/gradients.py,sha256=GiniMRsV22SoyGWxs087in4G9itrWt_wNHftxC4oKA4,2886 +torchmetrics/functional/image/lpips.py,sha256=tkftKrTUZiKJMczXD6HvUd5h3Zt8_DCOvbKOPUutqIo,17630 +torchmetrics/functional/image/lpips_models/alex.pth,sha256=33MoXjWyI1Wi34fNtrcLNDcTtmft29pz4Zd-DIYINcA,6009 +torchmetrics/functional/image/lpips_models/squeeze.pth,sha256=SlNQ8jYAy3mSPOZbsHy_V9ykYTKYlBU-BaE0a9Uxz3Y,10811 +torchmetrics/functional/image/lpips_models/vgg.pth,sha256=p4kooK8eXw_LHzuej4w6Klo94kTYMK1cH-3cebhDKGg,7289 +torchmetrics/functional/image/perceptual_path_length.py,sha256=Xh_Em1YMdxm7z3hQcKQ6qcU0h9PoA6PJXbBDHCYWohA,13741 +torchmetrics/functional/image/psnr.py,sha256=fbM3yUNPLyR-oh7qgIHB81pkFCQzXeiheLzAtWdf4OI,5560 +torchmetrics/functional/image/psnrb.py,sha256=jcyB5f7jSUtM5swlYZRRlDydF8zAj4dfUr70Zp8mpQ8,4858 +torchmetrics/functional/image/qnr.py,sha256=Y91qy2uOjRFeqQQEJtKibyhHAYwfF61azcnJ26tPfb4,3201 +torchmetrics/functional/image/rase.py,sha256=AeIk9mkg18dIUor6QD472wINP41MuB3Trm0C_-a1p6U,3980 +torchmetrics/functional/image/rmse_sw.py,sha256=QsHOEd7csxo8TNaAmD5Umkjb4ArFEH0QOOAyg_3-J0U,5546 +torchmetrics/functional/image/sam.py,sha256=nMIZS7cVLPPUIBOmK_IHWGjNqRKPq2ZLvCrq9U8s5hI,4198 +torchmetrics/functional/image/scc.py,sha256=V8PdnvMxGfZr3cWs3p_gV47V_pnZHUSWHDpCtN4f4OM,8610 +torchmetrics/functional/image/ssim.py,sha256=upztfW16SDf8NKHKYQSodPOHxMKc7Y6mYo_NU34O7OA,21771 +torchmetrics/functional/image/tv.py,sha256=bQmlbCqN4Mt_gRtPrABhe3Qq3LiTOGpOQRl-Vu8A78c,2799 +torchmetrics/functional/image/uqi.py,sha256=Vu5myFN9iwfeW-SWNxeheG5I-6QLmAe4CFArmd9p538,6566 +torchmetrics/functional/image/utils.py,sha256=Suy8BfPBTakcEd01IauLTdfGCfNZgOVKcgmVePrGByc,6013 +torchmetrics/functional/image/vif.py,sha256=9b6VpqMk9DmHdxXBuka0lkAj37yCJCdleUu5nRfN5nY,6419 +torchmetrics/functional/multimodal/__init__.py,sha256=MwecONDNOv7y6xnyDNUt2_c3jIaNFYjU70CBNgAoDx0,1019 +torchmetrics/functional/multimodal/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/multimodal/__pycache__/clip_iqa.cpython-310.pyc,, +torchmetrics/functional/multimodal/__pycache__/clip_score.cpython-310.pyc,, +torchmetrics/functional/multimodal/__pycache__/lve.cpython-310.pyc,, +torchmetrics/functional/multimodal/clip_iqa.py,sha256=jbyyAUOBnw8e_EcABnJ3l1gUfnHcel3FWFJQfJfD__I,15942 +torchmetrics/functional/multimodal/clip_score.py,sha256=Tx38ulxuK4nc9vS4L6u4OivCVafVytwl4MWOGDv_BX4,15186 +torchmetrics/functional/multimodal/lve.py,sha256=6KKx7TtTPdaoxdEi9hbpLh3yb8i2hrxHPHGc9BUnX90,4398 +torchmetrics/functional/nominal/__init__.py,sha256=JDtSc1P4crHRJSQb6PXymlWykb4-eGed-kLHVzNHpI0,1285 +torchmetrics/functional/nominal/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/nominal/__pycache__/cramers.cpython-310.pyc,, +torchmetrics/functional/nominal/__pycache__/fleiss_kappa.cpython-310.pyc,, +torchmetrics/functional/nominal/__pycache__/pearson.cpython-310.pyc,, +torchmetrics/functional/nominal/__pycache__/theils_u.cpython-310.pyc,, +torchmetrics/functional/nominal/__pycache__/tschuprows.cpython-310.pyc,, +torchmetrics/functional/nominal/__pycache__/utils.cpython-310.pyc,, +torchmetrics/functional/nominal/cramers.py,sha256=Ot_7UFSz_Pv-73eNoUFdzUywPwdPw__de9wDiCOBN_Q,7340 +torchmetrics/functional/nominal/fleiss_kappa.py,sha256=3vjLTQ8Qs5wTWosHjJ4-7RFaBnAivrA3EedNMa2xYzg,4226 +torchmetrics/functional/nominal/pearson.py,sha256=7SZeWnwTzvgxHD7_8oBHsQKoGJtUiRsO5OJ1TZkqf9g,6875 +torchmetrics/functional/nominal/theils_u.py,sha256=APxXfi7RFrrdPhfmBQ2ux1pWjOZ1ALN9dICMf6SQafA,7107 +torchmetrics/functional/nominal/tschuprows.py,sha256=6la3UCp8aPIzfTxT80bvmS9qpI5CmS8FxQAlShFCz1k,7639 +torchmetrics/functional/nominal/utils.py,sha256=8S75LS3YDDKBlSny5rgurDQUi9_yU9IGwr8c0rtGTfM,5745 +torchmetrics/functional/pairwise/__init__.py,sha256=f1NY4J7hgdcrpKk2yLHXF9yojm8qbGOmB8G4h9jrVRk,1173 +torchmetrics/functional/pairwise/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/pairwise/__pycache__/cosine.cpython-310.pyc,, +torchmetrics/functional/pairwise/__pycache__/euclidean.cpython-310.pyc,, +torchmetrics/functional/pairwise/__pycache__/helpers.cpython-310.pyc,, +torchmetrics/functional/pairwise/__pycache__/linear.cpython-310.pyc,, +torchmetrics/functional/pairwise/__pycache__/manhattan.cpython-310.pyc,, +torchmetrics/functional/pairwise/__pycache__/minkowski.cpython-310.pyc,, +torchmetrics/functional/pairwise/cosine.py,sha256=CPg8_Q4hLUe6YymgbZiCir1FtSWmnYROnXZpv5LYnyw,3499 +torchmetrics/functional/pairwise/euclidean.py,sha256=p9WZz6TBwQS25cZKDcU-6_tnDwF5OOTtkTIUBE2whq0,3449 +torchmetrics/functional/pairwise/helpers.py,sha256=8gZxrpBBUuRJdUnx49JUloeAlwgH3gM8-Ul8VBilKzs,2246 +torchmetrics/functional/pairwise/linear.py,sha256=OLOP2usOlbPOzD05vXlnWLlHkGgS68x94lP7UmRdkJU,3176 +torchmetrics/functional/pairwise/manhattan.py,sha256=zXQBFhxpmYzVtXSclM7sIPHXWXea-1tSmszU4CrjUng,3196 +torchmetrics/functional/pairwise/minkowski.py,sha256=jkms9LhEdX5yE9aezLKZXk3KeLi3EfLsPjUfxTlwCTQ,3999 +torchmetrics/functional/regression/__init__.py,sha256=NhakHreDD8TvYs7wk0aFEJ72pHeCC6I_rIJFHy_rRgw,3045 +torchmetrics/functional/regression/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/concordance.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/cosine_similarity.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/crps.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/csi.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/explained_variance.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/js_divergence.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/kendall.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/kl_divergence.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/log_cosh.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/log_mse.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/mae.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/mape.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/minkowski.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/mse.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/nrmse.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/pearson.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/r2.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/rse.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/spearman.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/symmetric_mape.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/tweedie_deviance.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/utils.cpython-310.pyc,, +torchmetrics/functional/regression/__pycache__/wmape.cpython-310.pyc,, +torchmetrics/functional/regression/concordance.py,sha256=PKw3PFNytnMbVY1DLdVcYJPoeymqCxzm3JFW1yY2F9I,3340 +torchmetrics/functional/regression/cosine_similarity.py,sha256=OGlqnXQZe6I-JSTmbhRQDhip9UQi_OWfEZ1xgjGU_0s,3628 +torchmetrics/functional/regression/crps.py,sha256=md5MRhhKUlJhMyzkXBIg4W58VMiWj9Cn1kRw5V7Wphs,3767 +torchmetrics/functional/regression/csi.py,sha256=0pURdVheU2yk5neMLcdbv8KTmLIn3z8t5QYs-Col92c,4855 +torchmetrics/functional/regression/explained_variance.py,sha256=ul817GvdESRyAI8e9veAiv1RJQWw2HnOigA5YKzQT9o,5492 +torchmetrics/functional/regression/js_divergence.py,sha256=l6WIe1R6AGKCwdmxBoaO06IPV4oGvWNc-MI8BQA7MBU,4237 +torchmetrics/functional/regression/kendall.py,sha256=AG4AzLnwP-o3QawCaXlaSpsndBhkaYtmTRUf2I4kpPc,15816 +torchmetrics/functional/regression/kl_divergence.py,sha256=6C7eQPvQgoH-jDFzRU3txjv_RedCyfTcNouQlFrOu3Q,4392 +torchmetrics/functional/regression/log_cosh.py,sha256=-xCnETLaQ6e5o2N7jiORi7wtsv9dhIIiccFrKZxZ6Ck,3500 +torchmetrics/functional/regression/log_mse.py,sha256=HjJy6qvVFo4MsmFPT6KkMVQs1n4iCaH_t6Ucw2xpi08,2598 +torchmetrics/functional/regression/mae.py,sha256=Vysyes-BPJ2xk42x07eEuiJ3bg7GJ-W-hj5m80ci-NA,2855 +torchmetrics/functional/regression/mape.py,sha256=1UHopkH9KN-KYB9qOSGklkUqFqN1KAS-WkPAmVVDNZE,3023 +torchmetrics/functional/regression/minkowski.py,sha256=sQYgJm2edpTZhTDIVAyGGZjJ9EAzgoeF8cB-j64GMMU,3010 +torchmetrics/functional/regression/mse.py,sha256=pNg7uuCSvTqjQrG2XiYbsZKn5CZIrndzP3ZGFCduMcE,2893 +torchmetrics/functional/regression/nrmse.py,sha256=07f9JsO9PYf8P4UlsuMISnK7eORJPsuwE5DVS6Oi1bk,4376 +torchmetrics/functional/regression/pearson.py,sha256=u2S2HXDzHD55V7XhHtfukpROXiqtDFniJnnmcKr7UVg,7368 +torchmetrics/functional/regression/r2.py,sha256=M6NC_RAOHNtldiUENV7R1L2pvsnVoo5WpxzAdnVE__M,6613 +torchmetrics/functional/regression/rse.py,sha256=o8AFBRGSS2Evcux83H6IEn6PuywjpJZC6fg9e9Y3y6A,2945 +torchmetrics/functional/regression/spearman.py,sha256=G1hn6br1BpSDMEZ8HJS_axHPNNHyxkflW107ZhK9k2s,4723 +torchmetrics/functional/regression/symmetric_mape.py,sha256=Kt2Y3v6sTEdLCA0M5YOBgoLPtJC6Jff5utmbdDSZMeI,3298 +torchmetrics/functional/regression/tweedie_deviance.py,sha256=3Z-kVkKUDvUUxDtjiyqAUot2KOrzHPDJ_lVH9mSwRJw,6071 +torchmetrics/functional/regression/utils.py,sha256=J5w3uY5qnyeoibifzsIwxE7cAm7ooFEVW--k4qDGFkU,1805 +torchmetrics/functional/regression/wmape.py,sha256=z8SRSBAg_lTAJemBpfuat-B_kU_fl5Y1sLv0cj9Qf8c,2615 +torchmetrics/functional/retrieval/__init__.py,sha256=hQRnCa7zEI8V_VhJSCWwJL3VDjWz1blooSUiq98gvJ8,1688 +torchmetrics/functional/retrieval/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/auroc.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/average_precision.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/fall_out.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/hit_rate.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/ndcg.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/precision.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/precision_recall_curve.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/r_precision.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/recall.cpython-310.pyc,, +torchmetrics/functional/retrieval/__pycache__/reciprocal_rank.cpython-310.pyc,, +torchmetrics/functional/retrieval/_deprecated.py,sha256=N-MbyyAnk_u6zeaf83wK-TMv-E1aVu39JYXayStaH7g,5410 +torchmetrics/functional/retrieval/auroc.py,sha256=1pqKdtd8kektGa03au4NKvtedoIoD8FydMY5tZ9U3Zo,2663 +torchmetrics/functional/retrieval/average_precision.py,sha256=5MDU0IJiHv5CWaPqY2-8Li9XuibiAxZjvz-kUTgYivE,2676 +torchmetrics/functional/retrieval/fall_out.py,sha256=Q2M7qmf57NyWYRdWAvNUbyQEbY_nWVWFA_Ftahluybs,2671 +torchmetrics/functional/retrieval/hit_rate.py,sha256=CpkO2zLnBxreNCQVvF7neJD7m9lVmUc72fhTi0KrWQk,2409 +torchmetrics/functional/retrieval/ndcg.py,sha256=tZky3qj7gmM8wZeqZHAFLn7spAIkpGpm0i_NPWLwjII,4328 +torchmetrics/functional/retrieval/precision.py,sha256=Wf1NpSk2WUgwmjXnBGNltH-qqHwCcBzcz1JpDPTa5H8,2847 +torchmetrics/functional/retrieval/precision_recall_curve.py,sha256=uiCXPAtjOekAuhxHQoV5yDQmBfKcJbQNHMbLz0rXP_g,4037 +torchmetrics/functional/retrieval/r_precision.py,sha256=DpxPzInI5c5Fdz1-JLLi99P32Z6iJfGltFAk7l4bkfM,2121 +torchmetrics/functional/retrieval/recall.py,sha256=HGhXI7BRjNGkSNk-z4xEN_yNMfpMRdv0o6GGXz2RuYQ,2593 +torchmetrics/functional/retrieval/reciprocal_rank.py,sha256=XtA4BSXu5Keuy5tDVXVRNkcvPG0KqQdFAp660yYN6UE,2518 +torchmetrics/functional/segmentation/__init__.py,sha256=i0DFQxUagC0C0AHT30H9i-32lzwtMu6Ev1kG_v5LfGc,972 +torchmetrics/functional/segmentation/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/segmentation/__pycache__/dice.cpython-310.pyc,, +torchmetrics/functional/segmentation/__pycache__/generalized_dice.cpython-310.pyc,, +torchmetrics/functional/segmentation/__pycache__/hausdorff_distance.cpython-310.pyc,, +torchmetrics/functional/segmentation/__pycache__/mean_iou.cpython-310.pyc,, +torchmetrics/functional/segmentation/__pycache__/utils.cpython-310.pyc,, +torchmetrics/functional/segmentation/dice.py,sha256=hxZpHtPh1Lo6km2Kg3aIzWoEfENlEvGS5k3AqE0bgEc,8807 +torchmetrics/functional/segmentation/generalized_dice.py,sha256=0MVbNWf1RD6pOGPPAY663inK_QS0ZYA1HhV_aMhtyvQ,6838 +torchmetrics/functional/segmentation/hausdorff_distance.py,sha256=ahBDXnaNrdAY_xxPAA79UdUmrA75Ejl1S6HBXaYVXuA,4940 +torchmetrics/functional/segmentation/mean_iou.py,sha256=fB5ex8V5ibeRTmSfPZ4xQ7XeTl_Giisj3w3J6OMU1lo,6786 +torchmetrics/functional/segmentation/utils.py,sha256=d4M7lahG2YDouysZ_rSojoFXTSYats9gHLR9wUyTLSk,50136 +torchmetrics/functional/shape/__init__.py,sha256=FxPrVkJAILigFAzOdvGI98m-dVSrwwn6Nw_Wr_8wWzo,688 +torchmetrics/functional/shape/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/shape/__pycache__/procrustes.cpython-310.pyc,, +torchmetrics/functional/shape/procrustes.py,sha256=nDlQc3WczwcIGISPEWtjOrn-i2p7uLQfsgfpigHtl50,2728 +torchmetrics/functional/text/__init__.py,sha256=kEA3cUZAlO9SLXyUNgb71p_ZX9CNlxwxhfLhyIYJYIU,2067 +torchmetrics/functional/text/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/bert.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/bleu.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/cer.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/chrf.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/edit.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/eed.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/helper.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/helper_embedding_metric.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/infolm.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/mer.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/perplexity.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/rouge.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/sacre_bleu.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/squad.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/ter.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/wer.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/wil.cpython-310.pyc,, +torchmetrics/functional/text/__pycache__/wip.cpython-310.pyc,, +torchmetrics/functional/text/_deprecated.py,sha256=1332p3ojAoUPQabLW3u2aEwA0ymH-RwT9XuizxW4Fk0,13963 +torchmetrics/functional/text/bert.py,sha256=BS9sruyRl96OgwAKH0Qo7TriKFK9i6iy2XrsXQeF758,26746 +torchmetrics/functional/text/bleu.py,sha256=P2F2FZN-dVz7GHTbXTTTgprhcwWddZ7uc5jSHpsYFl8,7598 +torchmetrics/functional/text/cer.py,sha256=QPsm_kUS_FKnjVOcxF6SORQyF1TuBhTLsXuZ87yWfGM,2970 +torchmetrics/functional/text/chrf.py,sha256=L5CMw4D5h3gB9wnvsAVytcyupYmBrzM-G0JS1M7Rpbo,25904 +torchmetrics/functional/text/edit.py,sha256=MqHGLvmkM4NkXbfKUpcHlOu1hfnVknR92gGOlL0x_Hg,4806 +torchmetrics/functional/text/eed.py,sha256=HyNCFszmsatkGhGyFS6hoDVtyqjyNB3wJWV7n_ZXME4,17569 +torchmetrics/functional/text/helper.py,sha256=2AUG95KbGxyAfDgzdJt8V_uvfttPGgFAlfsN5fFFjtI,17004 +torchmetrics/functional/text/helper_embedding_metric.py,sha256=PQId2tnXovGDNrbGIf-My7fCNb3i9om8UIUu18XcwWo,12021 +torchmetrics/functional/text/infolm.py,sha256=yKowb2NjeDvYM1GoBxQJLxbMB88Ayixcqg_O8AE4Zps,28027 +torchmetrics/functional/text/mer.py,sha256=roRGGKGcfpeId3yA2X7pwehlD9wF0CBi3wv4TocA5TE,3018 +torchmetrics/functional/text/perplexity.py,sha256=AaKgl3u-bb7IOpIKBAIVjyswga6ys5gH5clt2kEYAYI,5304 +torchmetrics/functional/text/rouge.py,sha256=hMB_kehukr2s49xrWxG5A8BmuHkUyCixhHjkeFeR7Q8,20727 +torchmetrics/functional/text/sacre_bleu.py,sha256=jGBFcdKPLPPRHBYVbfZiU_Wut6G3EhJlI9pNkzvSDbE,20151 +torchmetrics/functional/text/squad.py,sha256=yu_vNl5X5HX_um5TN1wVsvbc0ta5i7TxexyTy9CcdC0,9869 +torchmetrics/functional/text/ter.py,sha256=Gqesb980zS2Rvw0n9dTtL3kZ2nuQvubRjb_q96fuyPs,23280 +torchmetrics/functional/text/wer.py,sha256=Qpwg0IRR5oTPK1G3XMqUbaJHZW-5mHVuwBOz3Pvfl-8,2961 +torchmetrics/functional/text/wil.py,sha256=IhJ8FOiuzaFc7agGszacKzbIjLqVqLEWfuebMylrNAk,3496 +torchmetrics/functional/text/wip.py,sha256=jJHXGA1Df-VkFU3JmN1NMZrGGTydgVsBk-AoehmAJAY,3500 +torchmetrics/functional/video/__init__.py,sha256=Fve47SWsGruroKBLzyymNUhLL8mBMKlW2LFpsESL-bM,829 +torchmetrics/functional/video/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/functional/video/__pycache__/vmaf.cpython-310.pyc,, +torchmetrics/functional/video/vmaf.py,sha256=n_Vdt684JgukFyoByDXMpiS324UnpSvSGfZrkESa2p4,6979 +torchmetrics/image/__init__.py,sha256=AFPaVQ3iZqacAYCBUaGZFQQImrLd1yI1PagSvf8dv0c,3038 +torchmetrics/image/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/image/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/image/__pycache__/arniqa.cpython-310.pyc,, +torchmetrics/image/__pycache__/d_lambda.cpython-310.pyc,, +torchmetrics/image/__pycache__/d_s.cpython-310.pyc,, +torchmetrics/image/__pycache__/dists.cpython-310.pyc,, +torchmetrics/image/__pycache__/ergas.cpython-310.pyc,, +torchmetrics/image/__pycache__/fid.cpython-310.pyc,, +torchmetrics/image/__pycache__/inception.cpython-310.pyc,, +torchmetrics/image/__pycache__/kid.cpython-310.pyc,, +torchmetrics/image/__pycache__/lpip.cpython-310.pyc,, +torchmetrics/image/__pycache__/mifid.cpython-310.pyc,, +torchmetrics/image/__pycache__/perceptual_path_length.cpython-310.pyc,, +torchmetrics/image/__pycache__/psnr.cpython-310.pyc,, +torchmetrics/image/__pycache__/psnrb.cpython-310.pyc,, +torchmetrics/image/__pycache__/qnr.cpython-310.pyc,, +torchmetrics/image/__pycache__/rase.cpython-310.pyc,, +torchmetrics/image/__pycache__/rmse_sw.cpython-310.pyc,, +torchmetrics/image/__pycache__/sam.cpython-310.pyc,, +torchmetrics/image/__pycache__/scc.cpython-310.pyc,, +torchmetrics/image/__pycache__/ssim.cpython-310.pyc,, +torchmetrics/image/__pycache__/tv.cpython-310.pyc,, +torchmetrics/image/__pycache__/uqi.cpython-310.pyc,, +torchmetrics/image/__pycache__/vif.cpython-310.pyc,, +torchmetrics/image/_deprecated.py,sha256=V2udahUjZqO7FBoodf9FlfxbFmRHT2XymEMC2W-UGhk,8504 +torchmetrics/image/arniqa.py,sha256=gGjqflHrL9jgsp8oa2_r-MNY2zuBOlTVo6eotLLx3aM,9242 +torchmetrics/image/d_lambda.py,sha256=xJsrJdC83iTEAfVsd8kSmKnObu68ccZ08j0-XFGXV_4,6006 +torchmetrics/image/d_s.py,sha256=l8MuZnTsNxHjizN_NsV97aPi-0D4ghQe5QKxtBz2J_4,9464 +torchmetrics/image/dists.py,sha256=jvoJwZXC0Tbbht99VMXOkP_u4PgQDczY6eaDyefLqOk,5725 +torchmetrics/image/ergas.py,sha256=NydrHyzRsjcv9D93D71JBXsezj7ZVuDXPPvYV3Hd1eA,6240 +torchmetrics/image/fid.py,sha256=C3E2rkub7mE5nmKlnRSOC3E-GfmXv4Q8SKJL49OMLMo,22297 +torchmetrics/image/inception.py,sha256=f_EXhcRKqjgOe14WW5b6mDZ3S3RxK_D0LNl3xr-XRgM,9235 +torchmetrics/image/kid.py,sha256=gVbHNlh_eEnigxP5n1IT9E2tHTpfgKfMIHg7rtsfQpQ,15628 +torchmetrics/image/lpip.py,sha256=ezWAjFgGOYJjg1KZJP6dGPeXsCumLqVwfOWx0Z2QRCk,8460 +torchmetrics/image/mifid.py,sha256=Li_gYCsImp_DModIUFWhyYLnPXWhM87IE1mKv-ILd9o,13101 +torchmetrics/image/perceptual_path_length.py,sha256=cCWEf1DcoiryWgV8M6G2lCuQmeSsW5fHlEi3daED0ks,8523 +torchmetrics/image/psnr.py,sha256=eN5RmFgOpNkhKO4I-7TW_-GGfDygwm1jB0nMFLgqP7w,8512 +torchmetrics/image/psnrb.py,sha256=QQ1mjTw8QdZy5ck6-b3Q8Gh2TcxKRPug_YszyZKlNvg,6181 +torchmetrics/image/qnr.py,sha256=KNJSmtKPmQFoSj8SAacN9eAF-OiXA8n04B_wpfyXke4,9626 +torchmetrics/image/rase.py,sha256=N9Ra1-978iHGldbXEXL2WhqQv2hGlGQBXW2njaPfc8Q,4945 +torchmetrics/image/rmse_sw.py,sha256=joX_z3tlN14IS_wzWOcXzNqAM5Am0tsI09apbCxWtAk,5429 +torchmetrics/image/sam.py,sha256=O33sxzXo7I20d4uPppTUecQU4lwIOM4XTo_747smoTg,6626 +torchmetrics/image/scc.py,sha256=vBh-6K-TFCUnsWxoH-n5l1M363cpA57dYIu_BVA2WrI,3256 +torchmetrics/image/ssim.py,sha256=v23wARQUV9gLQVClRKoynS7oGqn-BnCbAbIkdyU-yFY,19532 +torchmetrics/image/tv.py,sha256=kh38dodRJ63HcImc5Svg5QrVoWFNDaJBbYBwRLnueZQ,5306 +torchmetrics/image/uqi.py,sha256=d75vZMDVnu7DVoBayMT6BjVtf35qKjf0NsDScD_4Y2Y,6843 +torchmetrics/image/vif.py,sha256=_yVSXc0I4OjDqjvs5ljlc0nRzYH16VIRHAaIPF-l6Js,4206 +torchmetrics/metric.py,sha256=jcUIo3QWFG6Dkv3BEBitjIm0GL52VfmiAG4MSBlzoPo,57049 +torchmetrics/multimodal/__init__.py,sha256=GFq8rL-QwcrP4Z4jGc0rIdoSzSMUF6O7a1Ee9hca854,974 +torchmetrics/multimodal/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/multimodal/__pycache__/clip_iqa.cpython-310.pyc,, +torchmetrics/multimodal/__pycache__/clip_score.cpython-310.pyc,, +torchmetrics/multimodal/__pycache__/lve.cpython-310.pyc,, +torchmetrics/multimodal/clip_iqa.py,sha256=ELuh7dqrvhp3D1wZHv86RKTIzVJUoDGJjwvJL8cOkLU,11924 +torchmetrics/multimodal/clip_score.py,sha256=PmslChrtknb-Qo1kfa5g6Wv4GVQE7bE_CmKB6ryf0vs,10941 +torchmetrics/multimodal/lve.py,sha256=RSZGmjtLUTvKgB19-diBROqsABYJlGrvHJuIItk3IWo,8358 +torchmetrics/nominal/__init__.py,sha256=-AbpLuTpceUjVMJz2AQLMY_nnXJJsry75B0hXk2Zkbo,987 +torchmetrics/nominal/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/nominal/__pycache__/cramers.cpython-310.pyc,, +torchmetrics/nominal/__pycache__/fleiss_kappa.cpython-310.pyc,, +torchmetrics/nominal/__pycache__/pearson.cpython-310.pyc,, +torchmetrics/nominal/__pycache__/theils_u.cpython-310.pyc,, +torchmetrics/nominal/__pycache__/tschuprows.cpython-310.pyc,, +torchmetrics/nominal/cramers.py,sha256=tuSme3YICwkOLBHQfYizF_lls5w8WqN7E5spBhTFPjA,6272 +torchmetrics/nominal/fleiss_kappa.py,sha256=x7v-mzB5bOLLnTdfoQBkjZTeq4g6Bsonc2o-cJ_J7IA,5664 +torchmetrics/nominal/pearson.py,sha256=gocfEjREFXEJCnZu53cht2IV-n7XNmfrITvsKhsxIcI,6567 +torchmetrics/nominal/theils_u.py,sha256=XjSIcRZwjexE8gZYlYd1GQSCshEstGHgNSUx61qUn_U,5798 +torchmetrics/nominal/tschuprows.py,sha256=H0O-m-Zec_dX3ld4JAHzyaNdww93Rg6LXsSKPMEkQIY,6337 +torchmetrics/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchmetrics/regression/__init__.py,sha256=SmayrB6S4UstfYTY7HHgaxA2nwMJwMeF-7PvFdyXb2Y,2675 +torchmetrics/regression/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/regression/__pycache__/concordance.cpython-310.pyc,, +torchmetrics/regression/__pycache__/cosine_similarity.cpython-310.pyc,, +torchmetrics/regression/__pycache__/crps.cpython-310.pyc,, +torchmetrics/regression/__pycache__/csi.cpython-310.pyc,, +torchmetrics/regression/__pycache__/explained_variance.cpython-310.pyc,, +torchmetrics/regression/__pycache__/js_divergence.cpython-310.pyc,, +torchmetrics/regression/__pycache__/kendall.cpython-310.pyc,, +torchmetrics/regression/__pycache__/kl_divergence.cpython-310.pyc,, +torchmetrics/regression/__pycache__/log_cosh.cpython-310.pyc,, +torchmetrics/regression/__pycache__/log_mse.cpython-310.pyc,, +torchmetrics/regression/__pycache__/mae.cpython-310.pyc,, +torchmetrics/regression/__pycache__/mape.cpython-310.pyc,, +torchmetrics/regression/__pycache__/minkowski.cpython-310.pyc,, +torchmetrics/regression/__pycache__/mse.cpython-310.pyc,, +torchmetrics/regression/__pycache__/nrmse.cpython-310.pyc,, +torchmetrics/regression/__pycache__/pearson.cpython-310.pyc,, +torchmetrics/regression/__pycache__/r2.cpython-310.pyc,, +torchmetrics/regression/__pycache__/rse.cpython-310.pyc,, +torchmetrics/regression/__pycache__/spearman.cpython-310.pyc,, +torchmetrics/regression/__pycache__/symmetric_mape.cpython-310.pyc,, +torchmetrics/regression/__pycache__/tweedie_deviance.cpython-310.pyc,, +torchmetrics/regression/__pycache__/wmape.cpython-310.pyc,, +torchmetrics/regression/concordance.py,sha256=OQBtHYgFxY_qxGxd_lK_WHqK81eszaogMy1INRzVEBY,5841 +torchmetrics/regression/cosine_similarity.py,sha256=a0BEQP0iZY4Qu4CjEW9DqSq4S5_Xuw9Z929SumUltPI,5235 +torchmetrics/regression/crps.py,sha256=Hfhe4_xqmOLFdwJpgChdQohyOqNHUHj5k0VUAqlmrnM,5096 +torchmetrics/regression/csi.py,sha256=RJuh0_bSRyI7cuY4atVuuO7YdDbdEFOshdjdRGpfFRI,4792 +torchmetrics/regression/explained_variance.py,sha256=A5ml_rvQpHUuDcA8wXoMqy2EIi2IvKPE_lkpnEO2J98,6948 +torchmetrics/regression/js_divergence.py,sha256=T36I89jXCsSHYN8SetF0BzqQ5BvV6EnviWgWl8pZkT8,6775 +torchmetrics/regression/kendall.py,sha256=afAcigwQwfuXoGIJoDqMU05Cmwx51wVTy4PIQUvz1Yc,8278 +torchmetrics/regression/kl_divergence.py,sha256=a9_KYNLcMX01gpY4z8Entt1pkuGdFAvnFsbwelzX5Xc,6672 +torchmetrics/regression/log_cosh.py,sha256=5vkae4AqkJtEz_6W4BvtA8tLgHCu3nbvY-Fovxm44wE,5440 +torchmetrics/regression/log_mse.py,sha256=AEyNbkwNrDUQ6ZEAQ7tTbGn5k6asvWR4H3i1NiMEp4c,4720 +torchmetrics/regression/mae.py,sha256=a3tDZxZu_JrIo5-d7SxGlyXsXrIE4reE4fH-Z7flAe0,5307 +torchmetrics/regression/mape.py,sha256=SgekTYO9jJzNDSBJQVOIaROM7DJ8ROFoSm26kkVg2_w,5094 +torchmetrics/regression/minkowski.py,sha256=KnzYJ8jTSwtlPjyNgbYqaBnI4tU7-fTS7G1cGugGgPE,4603 +torchmetrics/regression/mse.py,sha256=wpuUpCfpvnL2-dl0kXHlYzlj8Xz7bNG3VGjsYXHuJUk,5609 +torchmetrics/regression/nrmse.py,sha256=bH7UWG0yJyRNTE2wI9SCrjzCnL8Y5CTX-FRBstTzXoc,10852 +torchmetrics/regression/pearson.py,sha256=u0zeqKtdkoeDaJzyzrKOSd48PvfRBL0b6Ds4AMlHrkI,9769 +torchmetrics/regression/r2.py,sha256=LXCqIE7IAgX3-ScpBYb4ZteQz3nXshZPqnMX83-KCSo,7741 +torchmetrics/regression/rse.py,sha256=EMH0_8wCvULpo1lazBrYZ3BZ3rZA-OVbtGjV9bhA8Ig,5470 +torchmetrics/regression/spearman.py,sha256=dKA9h1qRzp02jtcyFDp-QoeF2FDmfHlCaWswytUwr2E,5810 +torchmetrics/regression/symmetric_mape.py,sha256=Uh_3hQfzGsK6C_feQHeKM718sEKj9paxj-a6K1aEoDg,4855 +torchmetrics/regression/tweedie_deviance.py,sha256=IVHg6nVBEc5j6NuRd9IZlVp5yyxM4ndV3eIlCvdafZ0,5919 +torchmetrics/regression/wmape.py,sha256=205orI6kavTLXE9mdqPuX1bjVtFVazIIhELu8p0g8k0,4848 +torchmetrics/retrieval/__init__.py,sha256=j8ra86FDGJa_lcZDt6VBn45-iQ_Ew3fFVAnYrsedWHY,1566 +torchmetrics/retrieval/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/auroc.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/average_precision.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/base.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/fall_out.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/hit_rate.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/ndcg.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/precision.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/precision_recall_curve.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/r_precision.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/recall.cpython-310.pyc,, +torchmetrics/retrieval/__pycache__/reciprocal_rank.cpython-310.pyc,, +torchmetrics/retrieval/_deprecated.py,sha256=nFRag3cnGTSOfEuk5NhIgIzG0vBIosxCMqJdBxf4yCY,9222 +torchmetrics/retrieval/auroc.py,sha256=r_37wzE7NYsMcW-82UQiDKeHt5Q0bgr52xiqeDBfwqg,7001 +torchmetrics/retrieval/average_precision.py,sha256=JOieRB7hh-oP0Isnazc_UoIbBlKfsK6ixyWjYWJDTqc,6567 +torchmetrics/retrieval/base.py,sha256=Wh5U6kXi0-qSfZyZfWQBt6MKw6OYufZ8-IsRED28FY0,8043 +torchmetrics/retrieval/fall_out.py,sha256=NNbBuhc-nSOxIKfdcoTTr3ABiDI2f2ZaDLA0872c6vE,8186 +torchmetrics/retrieval/hit_rate.py,sha256=yMXY_aMuaTCsnMJADls1rQt6YgjFE56-QeXYnXHGd40,6538 +torchmetrics/retrieval/ndcg.py,sha256=TeT1vWlZ-pdv4PKYEWgff7eqFvOVF3ljfYhgegSdKSM,6664 +torchmetrics/retrieval/precision.py,sha256=E1wFVBNMX4BcYYf0iUxA2Ld3SvnE9WJGPu4Wt4DSoLg,6919 +torchmetrics/retrieval/precision_recall_curve.py,sha256=6z6SMA6SOsox_0gdMwGcp-Kb3uJU7lPgglg4o147TAQ,17893 +torchmetrics/retrieval/r_precision.py,sha256=OV6Q6vyLVjY3nhbyksRD_damTr-a1ljXZq2VlrtkBoU,5627 +torchmetrics/retrieval/recall.py,sha256=-8Xsyxto8e0m8cYuL531PUgjTtwN5U500owDcI5YsBk,6516 +torchmetrics/retrieval/reciprocal_rank.py,sha256=vjee2uUpUXeRt68MsGW8WfwRlO6-bUFM6Ee06LEUMWs,6557 +torchmetrics/segmentation/__init__.py,sha256=3Xht3JWQYpfc3hR8wp-EbxVdTTtm1P9aG6LRz_UoA8c,918 +torchmetrics/segmentation/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/segmentation/__pycache__/dice.cpython-310.pyc,, +torchmetrics/segmentation/__pycache__/generalized_dice.cpython-310.pyc,, +torchmetrics/segmentation/__pycache__/hausdorff_distance.cpython-310.pyc,, +torchmetrics/segmentation/__pycache__/mean_iou.cpython-310.pyc,, +torchmetrics/segmentation/dice.py,sha256=d_OWYTGajcooqjP7da1hd__Lo-o12ehEU_LEUTlLccM,9079 +torchmetrics/segmentation/generalized_dice.py,sha256=WoKTcjdGyJNhkhvZxSxzKchyDDkyc31jHT3-hyM_Xtc,8423 +torchmetrics/segmentation/hausdorff_distance.py,sha256=PGTJlIcd5lkqI34sZL4nZOeIQGOEHIUM14SY4Gbpwlo,6989 +torchmetrics/segmentation/mean_iou.py,sha256=SbB2u8VCBDLJc-vDpymYQawrjFbi02IjwMGUrtJKTT4,10539 +torchmetrics/shape/__init__.py,sha256=geZDESOmNmoZ_5IZZofbTJlOorwgBqh6liklsX1Q-0k,675 +torchmetrics/shape/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/shape/__pycache__/procrustes.cpython-310.pyc,, +torchmetrics/shape/procrustes.py,sha256=vO6at_AV6d2GV1hrsqyxQ4O5-NcLDJ0HTiQmmJBl9MI,5734 +torchmetrics/text/__init__.py,sha256=5VeA0U0_AF-00-kP-G-PyVDOjnxnsTkgjZu4FI_oBUk,1819 +torchmetrics/text/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/text/__pycache__/_deprecated.cpython-310.pyc,, +torchmetrics/text/__pycache__/bert.cpython-310.pyc,, +torchmetrics/text/__pycache__/bleu.cpython-310.pyc,, +torchmetrics/text/__pycache__/cer.cpython-310.pyc,, +torchmetrics/text/__pycache__/chrf.cpython-310.pyc,, +torchmetrics/text/__pycache__/edit.cpython-310.pyc,, +torchmetrics/text/__pycache__/eed.cpython-310.pyc,, +torchmetrics/text/__pycache__/infolm.cpython-310.pyc,, +torchmetrics/text/__pycache__/mer.cpython-310.pyc,, +torchmetrics/text/__pycache__/perplexity.cpython-310.pyc,, +torchmetrics/text/__pycache__/rouge.cpython-310.pyc,, +torchmetrics/text/__pycache__/sacre_bleu.cpython-310.pyc,, +torchmetrics/text/__pycache__/squad.cpython-310.pyc,, +torchmetrics/text/__pycache__/ter.cpython-310.pyc,, +torchmetrics/text/__pycache__/wer.cpython-310.pyc,, +torchmetrics/text/__pycache__/wil.cpython-310.pyc,, +torchmetrics/text/__pycache__/wip.cpython-310.pyc,, +torchmetrics/text/_deprecated.py,sha256=HGgPtmnq5_2Zqxi3EqfnXvTXXGi6JA3CZntym2xL0ow,8229 +torchmetrics/text/bert.py,sha256=Y4miLqw_I4YmOrKOWjmSq0ssMuO1K_1AUuz0GEgx8tQ,16684 +torchmetrics/text/bleu.py,sha256=WwkBFYVZ6jjoLltbR-djdy9kPFcgB7gC6qIyy-osY4k,5884 +torchmetrics/text/cer.py,sha256=TWRmAvOz6WqqvPgfFKPVPvM7emBoGhpPnBT03XX6O_k,5307 +torchmetrics/text/chrf.py,sha256=C80Jg4l7lhB3eYTe3FDbny62duohgN10sLZSVHLMzbU,10490 +torchmetrics/text/edit.py,sha256=j1fk-57mcP577vj7H23UfHF7HqW4Rhxj1JsGPFsBnrk,7369 +torchmetrics/text/eed.py,sha256=BRIWrDKYgexoZkd-97nmrTrBiekN4ZQpV_DBPMjbbvQ,6381 +torchmetrics/text/infolm.py,sha256=4HzPIahF7sWJ_Bj8WYME18QRD-xEBTc6gKP1qkitF1E,10949 +torchmetrics/text/mer.py,sha256=Rzq6kea3q2K6Te8TxrE6nj-I4I3pp7uI1yagSHS5JX8,5250 +torchmetrics/text/perplexity.py,sha256=RXaUg75kbwGDUIYeicAx7W49deTT1BJbivdGzXCXnwo,5019 +torchmetrics/text/rouge.py,sha256=H_HHPe-ZQ3PyaDgiBbLYCNy_Di-N_8hw6HxXwAxIzI8,9412 +torchmetrics/text/sacre_bleu.py,sha256=PqGRvq9iGexmipUG9hbIVGBYjmPrwJOdublR7dViA2c,7188 +torchmetrics/text/squad.py,sha256=ebACHcgDciqKlJiJuU6NXAFdVmNaUt9n6YR33OX46PQ,6066 +torchmetrics/text/ter.py,sha256=yLpNLa5F-wW5cExjMtocfg48Md9Qw88_aoxeKAEH0fM,6765 +torchmetrics/text/wer.py,sha256=F_54E-BL68GZw0Ni2cMkfyTqX5_56xj7f23Gab0rhes,5232 +torchmetrics/text/wil.py,sha256=zf0xuWcHt5Vsfw8_sUW-THMviRCesyRGTetBtFfj9rM,5359 +torchmetrics/text/wip.py,sha256=dPR8YiszbJesfti30G8JuyZD0yYeW8t7DbEM-cPEW7o,5380 +torchmetrics/utilities/__init__.py,sha256=NM33fJ7MrGne7df6F4OYY9x59IeIWirkdMU5K9Q2Js4,1205 +torchmetrics/utilities/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/checks.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/compute.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/data.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/distributed.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/enums.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/exceptions.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/imports.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/plot.cpython-310.pyc,, +torchmetrics/utilities/__pycache__/prints.cpython-310.pyc,, +torchmetrics/utilities/checks.py,sha256=qbrocKIIILEQN7pmy9jWbKcMbdKBBsyL1Sy1qRHGtLc,12885 +torchmetrics/utilities/compute.py,sha256=bv33DfL4Bn3jsv999p0gvSJThhTXnWFzE0I6E2vi-jg,8319 +torchmetrics/utilities/data.py,sha256=p461ppdb5Jxcdc4bHPx4zf1XqMZxh_xsp9zRh-pi6k4,9071 +torchmetrics/utilities/distributed.py,sha256=88GtCrH_xIqg_odhI7_6vz4O3-El9INdvJjHmY3O7yQ,6146 +torchmetrics/utilities/enums.py,sha256=8i7ivcvC5kh8wB10IJZd5q5KkROodKhcYK0c2lIf2aU,3688 +torchmetrics/utilities/exceptions.py,sha256=VMl06AQRg-CjJnkKfWw_XXe11ajlm2I0XiXCi0knZTM,830 +torchmetrics/utilities/imports.py,sha256=59iPLS8g5oh9xc3Alz5UAznFnQ7j8Bnu1IoJ-jmVlpc,3412 +torchmetrics/utilities/plot.py,sha256=AjWBQlXbxDOIpbVZZ0BdXw--OhgUsptGBNpwtRjsKFk,14461 +torchmetrics/utilities/prints.py,sha256=H0kAnHRILObNdOEglHsFS8G6MCJ4uaumyrdzKhpGVKo,2368 +torchmetrics/video/__init__.py,sha256=t6gSl7eQk8zyIFuwxnx01AtxihVMajDK4cSp-71c-Vg,810 +torchmetrics/video/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/video/__pycache__/vmaf.cpython-310.pyc,, +torchmetrics/video/vmaf.py,sha256=U8dR_b9jUhgsUIcGnXlQ3D_7437M0RT7WLN_-QpHz80,10016 +torchmetrics/wrappers/__init__.py,sha256=_9AfQDwrHrnm3itZIy7xlw6NB9t6aVLgnIgaGwq4CgQ,1462 +torchmetrics/wrappers/__pycache__/__init__.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/abstract.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/bootstrapping.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/classwise.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/feature_share.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/minmax.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/multioutput.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/multitask.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/running.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/tracker.cpython-310.pyc,, +torchmetrics/wrappers/__pycache__/transformations.cpython-310.pyc,, +torchmetrics/wrappers/abstract.py,sha256=W74Qd23mi2qbOaQ6AvfyiZXi3AzEpsFPR5WZOxj_MX4,1855 +torchmetrics/wrappers/bootstrapping.py,sha256=C0ztxgGH2P0k09AzILAgqwx3t0H4lNLbE6zkuB4yDnA,9075 +torchmetrics/wrappers/classwise.py,sha256=saeaD2ZehxWcJH4RATRJ-Ei_soas0Z3oqqAxwyhKt2Q,10520 +torchmetrics/wrappers/feature_share.py,sha256=yVEC15r3qDdT9__5LgQuQe7PCjJcJNd7htXvRU6PJwA,6593 +torchmetrics/wrappers/minmax.py,sha256=D_1EsMeHMZUcfu4qYjzu2PBHj_kAKVFivNymWl38YsU,6262 +torchmetrics/wrappers/multioutput.py,sha256=Z2nUuk8NoYEUDrXxqa4MlESB54Zjl6mW6B-ab3ROogY,9584 +torchmetrics/wrappers/multitask.py,sha256=xIt_8z8LlxdRbhV2EJeacuG8gjuMipeqI7Ekc2qyjTg,18398 +torchmetrics/wrappers/running.py,sha256=K9ZU0eIkOW_fa8YCHiNMK2H_uN91DcTxpM3Gu-OGYZI,8362 +torchmetrics/wrappers/tracker.py,sha256=-OalxU2YI0aXNykoCaK42rAizCQQae0ttPjSC0HVOIY,18135 +torchmetrics/wrappers/transformations.py,sha256=y5THlNsdC1kpfrN9CcxyOd5tNhCc9xBm2ur4qxr1yGE,7083 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/licenses/LICENSE b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1c4044c766e386dab2ed09b97aad8d736d41c567 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020-2022 Lightning-AI team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..122b223a99f75fa6662f5a532d7f634d01ed0219 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/top_level.txt @@ -0,0 +1 @@ +torchmetrics diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/sam.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/sam.py new file mode 100644 index 0000000000000000000000000000000000000000..af5edb5f41ed8a843908e2a77988abcf28c70a62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/sam.py @@ -0,0 +1,121 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.distributed import reduce + + +def _sam_update(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute Spectral Angle Mapper. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + if preds.dtype != target.dtype: + raise TypeError( + "Expected `preds` and `target` to have the same data type." + f" Got preds: {preds.dtype} and target: {target.dtype}." + ) + _check_same_shape(preds, target) + if len(preds.shape) != 4: + raise ValueError( + f"Expected `preds` and `target` to have BxCxHxW shape. Got preds: {preds.shape} and target: {target.shape}." + ) + if (preds.shape[1] <= 1) or (target.shape[1] <= 1): + raise ValueError( + "Expected channel dimension of `preds` and `target` to be larger than 1." + f" Got preds: {preds.shape[1]} and target: {target.shape[1]}." + ) + return preds, target + + +def _sam_compute( + preds: Tensor, + target: Tensor, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", +) -> Tensor: + """Compute Spectral Angle Mapper. + + Args: + preds: estimated image + target: ground truth image + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + Example: + >>> from torch import rand + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> preds, target = _sam_update(preds, target) + >>> _sam_compute(preds, target) + tensor(0.5914) + + """ + dot_product = (preds * target).sum(dim=1) + preds_norm = preds.norm(dim=1) + target_norm = target.norm(dim=1) + sam_score = torch.clamp(dot_product / (preds_norm * target_norm), -1, 1).acos() + return reduce(sam_score, reduction) + + +def spectral_angle_mapper( + preds: Tensor, + target: Tensor, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", +) -> Tensor: + """Universal Spectral Angle Mapper. + + Args: + preds: estimated image + target: ground truth image + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + Return: + Tensor with Spectral Angle Mapper score + + Raises: + TypeError: + If ``preds`` and ``target`` don't have the same data type. + ValueError: + If ``preds`` and ``target`` don't have ``BxCxHxW shape``. + + Example: + >>> from torch import rand + >>> from torchmetrics.functional.image import spectral_angle_mapper + >>> preds = rand([16, 3, 16, 16],) + >>> target = rand([16, 3, 16, 16]) + >>> spectral_angle_mapper(preds, target) + tensor(0.5914) + + References: + [1] Roberta H. Yuhas, Alexander F. H. Goetz and Joe W. Boardman, "Discrimination among semi-arid + landscape endmembers using the Spectral Angle Mapper (SAM) algorithm" in PL, Summaries of the Third Annual JPL + Airborne Geoscience Workshop, vol. 1, June 1, 1992. + + """ + preds, target = _sam_update(preds, target) + return _sam_compute(preds, target, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/scc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/scc.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa6b31fd627056b9e038b2380e508adc44613d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/scc.py @@ -0,0 +1,220 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math +from typing import Optional, Union + +import torch +from torch import Tensor, tensor +from torch.nn.functional import conv2d, pad +from typing_extensions import Literal + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.distributed import reduce + + +def _scc_update(preds: Tensor, target: Tensor, hp_filter: Tensor, window_size: int) -> tuple[Tensor, Tensor, Tensor]: + """Update and returns variables required to compute Spatial Correlation Coefficient. + + Args: + preds: Predicted tensor + target: Ground truth tensor + hp_filter: High-pass filter tensor + window_size: Local window size integer + + Return: + Tuple of (preds, target, hp_filter) tensors + + Raises: + ValueError: + If ``preds`` and ``target`` have different number of channels + If ``preds`` and ``target`` have different shapes + If ``preds`` and ``target`` have invalid shapes + If ``window_size`` is not a positive integer + If ``window_size`` is greater than the size of the image + + """ + if preds.dtype != target.dtype: + target = target.to(preds.dtype) + _check_same_shape(preds, target) + if preds.ndim not in (3, 4): + raise ValueError( + "Expected `preds` and `target` to have batch of colored images with BxCxHxW shape" + " or batch of grayscale images of BxHxW shape." + f" Got preds: {preds.shape} and target: {target.shape}." + ) + + if len(preds.shape) == 3: + preds = preds.unsqueeze(1) + target = target.unsqueeze(1) + + if not window_size > 0: + raise ValueError(f"Expected `window_size` to be a positive integer. Got {window_size}.") + + if window_size > preds.size(2) or window_size > preds.size(3): + raise ValueError( + f"Expected `window_size` to be less than or equal to the size of the image." + f" Got window_size: {window_size} and image size: {preds.size(2)}x{preds.size(3)}." + ) + + preds = preds.to(torch.float32) + target = target.to(torch.float32) + hp_filter = hp_filter[None, None, :].to(dtype=preds.dtype, device=preds.device) + return preds, target, hp_filter + + +def _symmetric_reflect_pad_2d(input_img: Tensor, pad: Union[int, tuple[int, ...]]) -> Tensor: + """Applies symmetric padding to the 2D image tensor input using ``reflect`` mode (d c b a | a b c d | d c b a).""" + if isinstance(pad, int): + pad = (pad, pad, pad, pad) + if len(pad) != 4: + raise ValueError(f"Expected padding to have length 4, but got {len(pad)}") + + left_pad = input_img[:, :, :, 0 : pad[0]].flip(dims=[3]) + right_pad = input_img[:, :, :, -pad[1] :].flip(dims=[3]) + padded = torch.cat([left_pad, input_img, right_pad], dim=3) + + top_pad = padded[:, :, 0 : pad[2], :].flip(dims=[2]) + bottom_pad = padded[:, :, -pad[3] :, :].flip(dims=[2]) + return torch.cat([top_pad, padded, bottom_pad], dim=2) + + +def _signal_convolve_2d(input_img: Tensor, kernel: Tensor) -> Tensor: + """Applies 2D signal convolution to the input tensor with the given kernel.""" + left_padding = math.floor((kernel.size(3) - 1) / 2) + right_padding = math.ceil((kernel.size(3) - 1) / 2) + top_padding = math.floor((kernel.size(2) - 1) / 2) + bottom_padding = math.ceil((kernel.size(2) - 1) / 2) + + padded = _symmetric_reflect_pad_2d(input_img, pad=(left_padding, right_padding, top_padding, bottom_padding)) + kernel = kernel.flip([2, 3]) + return conv2d(padded, kernel, stride=1, padding=0) + + +def _hp_2d_laplacian(input_img: Tensor, kernel: Tensor) -> Tensor: + """Applies 2-D Laplace filter to the input tensor with the given high pass filter.""" + return _signal_convolve_2d(input_img, kernel) * 2.0 + + +def _local_variance_covariance(preds: Tensor, target: Tensor, window: Tensor) -> tuple[Tensor, Tensor, Tensor]: + """Computes local variance and covariance of the input tensors.""" + # This code is inspired by + # https://github.com/andrewekhalel/sewar/blob/master/sewar/full_ref.py#L187. + + left_padding = math.ceil((window.size(3) - 1) / 2) + right_padding = math.floor((window.size(3) - 1) / 2) + + preds = pad(preds, (left_padding, right_padding, left_padding, right_padding)) + target = pad(target, (left_padding, right_padding, left_padding, right_padding)) + + preds_mean = conv2d(preds, window, stride=1, padding=0) + target_mean = conv2d(target, window, stride=1, padding=0) + + preds_var = conv2d(preds**2, window, stride=1, padding=0) - preds_mean**2 + target_var = conv2d(target**2, window, stride=1, padding=0) - target_mean**2 + target_preds_cov = conv2d(target * preds, window, stride=1, padding=0) - target_mean * preds_mean + + return preds_var, target_var, target_preds_cov + + +def _scc_per_channel_compute(preds: Tensor, target: Tensor, hp_filter: Tensor, window_size: int) -> Tensor: + """Computes per channel Spatial Correlation Coefficient. + + Args: + preds: estimated image of Bx1xHxW shape. + target: ground truth image of Bx1xHxW shape. + hp_filter: 2D high-pass filter. + window_size: size of window for local mean calculation. + + Return: + Tensor with Spatial Correlation Coefficient score + + """ + dtype = preds.dtype + device = preds.device + + # This code is inspired by + # https://github.com/andrewekhalel/sewar/blob/master/sewar/full_ref.py#L187. + + window = torch.ones(size=(1, 1, window_size, window_size), dtype=dtype, device=device) / (window_size**2) + + preds_hp = _hp_2d_laplacian(preds, hp_filter) + target_hp = _hp_2d_laplacian(target, hp_filter) + + preds_var, target_var, target_preds_cov = _local_variance_covariance(preds_hp, target_hp, window) + + preds_var[preds_var < 0] = 0 + target_var[target_var < 0] = 0 + + den = torch.sqrt(target_var) * torch.sqrt(preds_var) + idx = den == 0 + den[den == 0] = 1 + scc = target_preds_cov / den + scc[idx] = 0 + return scc + + +def spatial_correlation_coefficient( + preds: Tensor, + target: Tensor, + hp_filter: Optional[Tensor] = None, + window_size: int = 8, + reduction: Optional[Literal["mean", "none", None]] = "mean", +) -> Tensor: + """Compute Spatial Correlation Coefficient (SCC_). + + Args: + preds: predicted images of shape ``(N,C,H,W)`` or ``(N,H,W)``. + target: ground truth images of shape ``(N,C,H,W)`` or ``(N,H,W)``. + hp_filter: High-pass filter tensor. default: tensor([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]) + window_size: Local window size integer. default: 8, + reduction: Reduction method for output tensor. If ``None`` or ``"none"``, + returns a tensor with the per sample results. default: ``"mean"``. + + Return: + Tensor with scc score + + Example: + >>> from torch import randn + >>> from torchmetrics.functional.image import spatial_correlation_coefficient as scc + >>> x = randn(5, 3, 16, 16) + >>> scc(x, x) + tensor(1.) + >>> x = randn(5, 16, 16) + >>> scc(x, x) + tensor(1.) + >>> x = randn(5, 3, 16, 16) + >>> y = randn(5, 3, 16, 16) + >>> scc(x, y, reduction="none") + tensor([0.0223, 0.0256, 0.0616, 0.0159, 0.0170]) + + """ + if hp_filter is None: + hp_filter = tensor([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]) + if reduction is None: + reduction = "none" + if reduction not in ("mean", "none"): + raise ValueError(f"Expected reduction to be 'mean' or 'none', but got {reduction}") + preds, target, hp_filter = _scc_update(preds, target, hp_filter, window_size) + + per_channel = [ + _scc_per_channel_compute( + preds[:, i, :, :].unsqueeze(1), target[:, i, :, :].unsqueeze(1), hp_filter, window_size + ) + for i in range(preds.size(1)) + ] + if reduction == "none": + return torch.mean(torch.cat(per_channel, dim=1), dim=[1, 2, 3]) + if reduction == "mean": + return reduce(torch.cat(per_channel, dim=1), reduction="elementwise_mean") + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/ssim.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/ssim.py new file mode 100644 index 0000000000000000000000000000000000000000..ccaafe660657e5b7bc3dda9b5e3cb323294a56cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/ssim.py @@ -0,0 +1,529 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import List, Optional, Union + +import torch +from torch import Tensor +from torch.nn import functional as F # noqa: N812 +from typing_extensions import Literal + +from torchmetrics.functional.image.utils import _gaussian_kernel_2d, _gaussian_kernel_3d, _reflection_pad_3d +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.distributed import reduce + + +def _ssim_check_inputs(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute Structural Similarity Index Measure. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + if preds.dtype != target.dtype: + target = target.to(preds.dtype) + _check_same_shape(preds, target) + if len(preds.shape) not in (4, 5): + raise ValueError( + "Expected `preds` and `target` to have BxCxHxW or BxCxDxHxW shape." + f" Got preds: {preds.shape} and target: {target.shape}." + ) + return preds, target + + +def _ssim_update( + preds: Tensor, + target: Tensor, + gaussian_kernel: bool = True, + sigma: Union[float, Sequence[float]] = 1.5, + kernel_size: Union[int, Sequence[int]] = 11, + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + return_full_image: bool = False, + return_contrast_sensitivity: bool = False, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Compute Structural Similarity Index Measure. + + Args: + preds: estimated image + target: ground truth image + gaussian_kernel: If true (default), a gaussian kernel is used, if false a uniform kernel is used + sigma: Standard deviation of the gaussian kernel, anisotropic kernels are possible. + Ignored if a uniform kernel is used + kernel_size: the size of the uniform kernel, anisotropic kernels are possible. + Ignored if a Gaussian kernel is used + data_range: Range of the image. If ``None``, it is determined from the image (max - min) + k1: Parameter of SSIM. + k2: Parameter of SSIM. + return_full_image: If true, the full ``ssim`` image is returned as a second argument. + Mutually exclusive with ``return_contrast_sensitivity`` + return_contrast_sensitivity: If true, the contrast term is returned as a second argument. + The luminance term can be obtained with luminance=ssim/contrast + Mutually exclusive with ``return_full_image`` + + """ + is_3d = preds.ndim == 5 + + if not isinstance(kernel_size, Sequence): + kernel_size = 3 * [kernel_size] if is_3d else 2 * [kernel_size] + if not isinstance(sigma, Sequence): + sigma = 3 * [sigma] if is_3d else 2 * [sigma] + + if len(kernel_size) != len(target.shape) - 2: + raise ValueError( + f"`kernel_size` has dimension {len(kernel_size)}, but expected to be two less that target dimensionality," + f" which is: {len(target.shape)}" + ) + if len(kernel_size) not in (2, 3): + raise ValueError( + f"Expected `kernel_size` dimension to be 2 or 3. `kernel_size` dimensionality: {len(kernel_size)}" + ) + if len(sigma) != len(target.shape) - 2: + raise ValueError( + f"`kernel_size` has dimension {len(kernel_size)}, but expected to be two less that target dimensionality," + f" which is: {len(target.shape)}" + ) + if len(sigma) not in (2, 3): + raise ValueError( + f"Expected `kernel_size` dimension to be 2 or 3. `kernel_size` dimensionality: {len(kernel_size)}" + ) + + if return_full_image and return_contrast_sensitivity: + raise ValueError("Arguments `return_full_image` and `return_contrast_sensitivity` are mutually exclusive.") + + if any(x % 2 == 0 or x <= 0 for x in kernel_size): + raise ValueError(f"Expected `kernel_size` to have odd positive number. Got {kernel_size}.") + + if any(y <= 0 for y in sigma): + raise ValueError(f"Expected `sigma` to have positive number. Got {sigma}.") + + if data_range is None: + data_range = max(preds.max() - preds.min(), target.max() - target.min()) # type: ignore[call-overload] + elif isinstance(data_range, tuple): + preds = torch.clamp(preds, min=data_range[0], max=data_range[1]) + target = torch.clamp(target, min=data_range[0], max=data_range[1]) + data_range = data_range[1] - data_range[0] + + c1 = pow(k1 * data_range, 2) # type: ignore[operator] + c2 = pow(k2 * data_range, 2) # type: ignore[operator] + device = preds.device + + channel = preds.size(1) + dtype = preds.dtype + gauss_kernel_size = [int(3.5 * s + 0.5) * 2 + 1 for s in sigma] + + if gaussian_kernel: + pad_h = (gauss_kernel_size[0] - 1) // 2 + pad_w = (gauss_kernel_size[1] - 1) // 2 + else: + pad_h = (kernel_size[0] - 1) // 2 + pad_w = (kernel_size[1] - 1) // 2 + + if is_3d: + pad_d = (kernel_size[2] - 1) // 2 + preds = _reflection_pad_3d(preds, pad_d, pad_w, pad_h) + target = _reflection_pad_3d(target, pad_d, pad_w, pad_h) + if gaussian_kernel: + kernel = _gaussian_kernel_3d(channel, gauss_kernel_size, sigma, dtype, device) + else: + preds = F.pad(preds, (pad_w, pad_w, pad_h, pad_h), mode="reflect") + target = F.pad(target, (pad_w, pad_w, pad_h, pad_h), mode="reflect") + if gaussian_kernel: + kernel = _gaussian_kernel_2d(channel, gauss_kernel_size, sigma, dtype, device) + + if not gaussian_kernel: + kernel = torch.ones((channel, 1, *kernel_size), dtype=dtype, device=device) / torch.prod( + torch.tensor(kernel_size, dtype=dtype, device=device) + ) + + input_list = torch.cat((preds, target, preds * preds, target * target, preds * target)) # (5 * B, C, H, W) + + outputs = F.conv3d(input_list, kernel, groups=channel) if is_3d else F.conv2d(input_list, kernel, groups=channel) + + output_list = outputs.split(preds.shape[0]) + + mu_pred_sq = output_list[0].pow(2) + mu_target_sq = output_list[1].pow(2) + mu_pred_target = output_list[0] * output_list[1] + + # Calculate the variance of the predicted and target images, should be non-negative + sigma_pred_sq = torch.clamp(output_list[2] - mu_pred_sq, min=0.0) + sigma_target_sq = torch.clamp(output_list[3] - mu_target_sq, min=0.0) + sigma_pred_target = output_list[4] - mu_pred_target + + upper = 2 * sigma_pred_target.to(dtype) + c2 + lower = (sigma_pred_sq + sigma_target_sq).to(dtype) + c2 + + ssim_idx_full_image = ((2 * mu_pred_target + c1) * upper) / ((mu_pred_sq + mu_target_sq + c1) * lower) + + if return_contrast_sensitivity: + contrast_sensitivity = upper / lower + if is_3d: + contrast_sensitivity = contrast_sensitivity[..., pad_h:-pad_h, pad_w:-pad_w, pad_d:-pad_d] + else: + contrast_sensitivity = contrast_sensitivity[..., pad_h:-pad_h, pad_w:-pad_w] + + return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1), contrast_sensitivity.reshape( + contrast_sensitivity.shape[0], -1 + ).mean(-1) + + if return_full_image: + return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1), ssim_idx_full_image + + return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1) + + +def _ssim_compute( + similarities: Tensor, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", +) -> Tensor: + """Apply the specified reduction to pre-computed structural similarity. + + Args: + similarities: per image similarities for a batch of images. + reduction: a method to reduce metric score over individual batch scores + + - ``'elementwise_mean'``: takes the mean + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + Returns: + The reduced SSIM score + + """ + return reduce(similarities, reduction) + + +def structural_similarity_index_measure( + preds: Tensor, + target: Tensor, + gaussian_kernel: bool = True, + sigma: Union[float, Sequence[float]] = 1.5, + kernel_size: Union[int, Sequence[int]] = 11, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + return_full_image: bool = False, + return_contrast_sensitivity: bool = False, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Compute Structural Similarity Index Measure. + + Args: + preds: estimated image + target: ground truth image + gaussian_kernel: If true (default), a gaussian kernel is used, if false a uniform kernel is used + sigma: Standard deviation of the gaussian kernel, anisotropic kernels are possible. + Ignored if a uniform kernel is used + kernel_size: the size of the uniform kernel, anisotropic kernels are possible. + Ignored if a Gaussian kernel is used + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + data_range: + the range of the data. If None, it is determined from the data (max - min). If a tuple is provided then + the range is calculated as the difference and input is clamped between the values. + k1: Parameter of SSIM. + k2: Parameter of SSIM. + return_full_image: If true, the full ``ssim`` image is returned as a second argument. + Mutually exclusive with ``return_contrast_sensitivity`` + return_contrast_sensitivity: If true, the constant term is returned as a second argument. + The luminance term can be obtained with luminance=ssim/contrast + Mutually exclusive with ``return_full_image`` + + Return: + Tensor with SSIM score + + Raises: + TypeError: + If ``preds`` and ``target`` don't have the same data type. + ValueError: + If ``preds`` and ``target`` don't have ``BxCxHxW shape``. + ValueError: + If the length of ``kernel_size`` or ``sigma`` is not ``2``. + ValueError: + If one of the elements of ``kernel_size`` is not an ``odd positive number``. + ValueError: + If one of the elements of ``sigma`` is not a ``positive number``. + + Example: + >>> from torchmetrics.functional.image import structural_similarity_index_measure + >>> preds = torch.rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> structural_similarity_index_measure(preds, target) + tensor(0.9219) + + """ + preds, target = _ssim_check_inputs(preds, target) + similarity_pack = _ssim_update( + preds, + target, + gaussian_kernel, + sigma, + kernel_size, + data_range, + k1, + k2, + return_full_image, + return_contrast_sensitivity, + ) + + if isinstance(similarity_pack, tuple): + similarity, image = similarity_pack + return _ssim_compute(similarity, reduction), image + + similarity = similarity_pack + return _ssim_compute(similarity, reduction) + + +def _get_normalized_sim_and_cs( + preds: Tensor, + target: Tensor, + gaussian_kernel: bool = True, + sigma: Union[float, Sequence[float]] = 1.5, + kernel_size: Union[int, Sequence[int]] = 11, + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + normalize: Optional[Literal["relu", "simple"]] = None, +) -> tuple[Tensor, Tensor]: + sim, contrast_sensitivity = _ssim_update( + preds, + target, + gaussian_kernel, + sigma, + kernel_size, + data_range, + k1, + k2, + return_contrast_sensitivity=True, + ) + if normalize == "relu": + sim = torch.relu(sim) + contrast_sensitivity = torch.relu(contrast_sensitivity) + return sim, contrast_sensitivity + + +def _multiscale_ssim_update( + preds: Tensor, + target: Tensor, + gaussian_kernel: bool = True, + sigma: Union[float, Sequence[float]] = 1.5, + kernel_size: Union[int, Sequence[int]] = 11, + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + betas: Union[tuple[float, float, float, float, float], tuple[float, ...]] = ( + 0.0448, + 0.2856, + 0.3001, + 0.2363, + 0.1333, + ), + normalize: Optional[Literal["relu", "simple"]] = None, +) -> Tensor: + """Compute Multi-Scale Structural Similarity Index Measure. + + Adapted from: https://github.com/jorge-pessoa/pytorch-msssim/blob/master/pytorch_msssim/__init__.py. + + Args: + preds: estimated image + target: ground truth image + gaussian_kernel: If true, a gaussian kernel is used, if false a uniform kernel is used + sigma: Standard deviation of the gaussian kernel + kernel_size: size of the gaussian kernel + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + data_range: Range of the image. If ``None``, it is determined from the image (max - min) + k1: Parameter of structural similarity index measure. + k2: Parameter of structural similarity index measure. + betas: Exponent parameters for individual similarities and contrastive sensitives returned by different image + resolutions. + normalize: When MultiScaleSSIM loss is used for training, it is desirable to use normalizes to improve the + training stability. This `normalize` argument is out of scope of the original implementation [1], and it is + adapted from https://github.com/jorge-pessoa/pytorch-msssim instead. + + Raises: + ValueError: + If the image height or width is smaller then ``2 ** len(betas)``. + ValueError: + If the image height is smaller than ``(kernel_size[0] - 1) * max(1, (len(betas) - 1)) ** 2``. + ValueError: + If the image width is smaller than ``(kernel_size[0] - 1) * max(1, (len(betas) - 1)) ** 2``. + + """ + mcs_list: List[Tensor] = [] + + is_3d = preds.ndim == 5 + + if not isinstance(kernel_size, Sequence): + kernel_size = 3 * [kernel_size] if is_3d else 2 * [kernel_size] + if not isinstance(sigma, Sequence): + sigma = 3 * [sigma] if is_3d else 2 * [sigma] + + if preds.size()[-1] < 2 ** len(betas) or preds.size()[-2] < 2 ** len(betas): + raise ValueError( + f"For a given number of `betas` parameters {len(betas)}, the image height and width dimensions must be" + f" larger than or equal to {2 ** len(betas)}." + ) + + _betas_div = max(1, (len(betas) - 1)) ** 2 + if preds.size()[-2] // _betas_div <= kernel_size[0] - 1: + raise ValueError( + f"For a given number of `betas` parameters {len(betas)} and kernel size {kernel_size[0]}," + f" the image height must be larger than {(kernel_size[0] - 1) * _betas_div}." + ) + if preds.size()[-1] // _betas_div <= kernel_size[1] - 1: + raise ValueError( + f"For a given number of `betas` parameters {len(betas)} and kernel size {kernel_size[1]}," + f" the image width must be larger than {(kernel_size[1] - 1) * _betas_div}." + ) + + for _ in range(len(betas)): + sim, contrast_sensitivity = _get_normalized_sim_and_cs( + preds, target, gaussian_kernel, sigma, kernel_size, data_range, k1, k2, normalize=normalize + ) + mcs_list.append(contrast_sensitivity) + + if len(kernel_size) == 2: + preds = F.avg_pool2d(preds, (2, 2)) + target = F.avg_pool2d(target, (2, 2)) + elif len(kernel_size) == 3: + preds = F.avg_pool3d(preds, (2, 2, 2)) + target = F.avg_pool3d(target, (2, 2, 2)) + else: + raise ValueError("length of kernel_size is neither 2 nor 3") + + mcs_list[-1] = sim + mcs_stack = torch.stack(mcs_list) + + if normalize == "simple": + mcs_stack = (mcs_stack + 1) / 2 + + betas = torch.tensor(betas, device=mcs_stack.device).view(-1, 1) + mcs_weighted = mcs_stack**betas + return torch.prod(mcs_weighted, axis=0) # type: ignore[call-overload] + + +def _multiscale_ssim_compute( + mcs_per_image: Tensor, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", +) -> Tensor: + """Apply the specified reduction to pre-computed multi-scale structural similarity. + + Args: + mcs_per_image: per image similarities for a batch of images. + reduction: a method to reduce metric score over individual batch scores + + - ``'elementwise_mean'``: takes the mean + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + Returns: + The reduced multi-scale structural similarity + + """ + return reduce(mcs_per_image, reduction) + + +def multiscale_structural_similarity_index_measure( + preds: Tensor, + target: Tensor, + gaussian_kernel: bool = True, + sigma: Union[float, Sequence[float]] = 1.5, + kernel_size: Union[int, Sequence[int]] = 11, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + betas: tuple[float, ...] = (0.0448, 0.2856, 0.3001, 0.2363, 0.1333), + normalize: Optional[Literal["relu", "simple"]] = "relu", +) -> Tensor: + """Compute `MultiScaleSSIM`_, Multi-scale Structural Similarity Index Measure. + + This metric is a generalization of Structural Similarity Index Measure by incorporating image details at different + resolution scores. + + Args: + preds: Predictions from model of shape ``[N, C, H, W]`` + target: Ground truth values of shape ``[N, C, H, W]`` + gaussian_kernel: If true, a gaussian kernel is used, if false a uniform kernel is used + sigma: Standard deviation of the gaussian kernel + kernel_size: size of the gaussian kernel + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + data_range: + the range of the data. If None, it is determined from the data (max - min). If a tuple is provided then + the range is calculated as the difference and input is clamped between the values. + k1: Parameter of structural similarity index measure. + k2: Parameter of structural similarity index measure. + betas: Exponent parameters for individual similarities and contrastive sensitivities returned by different image + resolutions. + normalize: When MultiScaleSSIM loss is used for training, it is desirable to use normalizes to improve the + training stability. This `normalize` argument is out of scope of the original implementation [1], and it is + adapted from https://github.com/jorge-pessoa/pytorch-msssim instead. + + Return: + Tensor with Multi-Scale SSIM score + + Raises: + TypeError: + If ``preds`` and ``target`` don't have the same data type. + ValueError: + If ``preds`` and ``target`` don't have ``BxCxHxW shape``. + ValueError: + If the length of ``kernel_size`` or ``sigma`` is not ``2``. + ValueError: + If one of the elements of ``kernel_size`` is not an ``odd positive number``. + ValueError: + If one of the elements of ``sigma`` is not a ``positive number``. + + Example: + >>> from torch import rand + >>> from torchmetrics.functional.image import multiscale_structural_similarity_index_measure + >>> preds = rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> multiscale_structural_similarity_index_measure(preds, target, data_range=1.0) + tensor(0.9628) + + References: + [1] Multi-Scale Structural Similarity For Image Quality Assessment by Zhou Wang, Eero P. Simoncelli and Alan C. + Bovik `MultiScaleSSIM`_ + + """ + if not isinstance(betas, tuple): + raise ValueError("Argument `betas` is expected to be of a type tuple.") + if isinstance(betas, tuple) and not all(isinstance(beta, float) for beta in betas): + raise ValueError("Argument `betas` is expected to be a tuple of floats.") + if normalize and normalize not in ("relu", "simple"): + raise ValueError("Argument `normalize` to be expected either `None` or one of 'relu' or 'simple'") + + preds, target = _ssim_check_inputs(preds, target) + mcs_per_image = _multiscale_ssim_update( + preds, target, gaussian_kernel, sigma, kernel_size, data_range, k1, k2, betas, normalize + ) + return _multiscale_ssim_compute(mcs_per_image, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/tv.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/tv.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f310d498d0fa4480b00adcb6ffb54ab5566a36 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/tv.py @@ -0,0 +1,77 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional, Union + +from torch import Tensor +from typing_extensions import Literal + + +def _total_variation_update(img: Tensor) -> tuple[Tensor, int]: + """Compute total variation statistics on current batch.""" + if img.ndim != 4: + raise RuntimeError(f"Expected input `img` to be an 4D tensor, but got {img.shape}") + diff1 = img[..., 1:, :] - img[..., :-1, :] + diff2 = img[..., :, 1:] - img[..., :, :-1] + + res1 = diff1.abs().sum([1, 2, 3]) + res2 = diff2.abs().sum([1, 2, 3]) + score = res1 + res2 + return score, img.shape[0] + + +def _total_variation_compute( + score: Tensor, num_elements: Union[int, Tensor], reduction: Optional[Literal["mean", "sum", "none"]] +) -> Tensor: + """Compute final total variation score.""" + if reduction == "mean": + return score.sum() / num_elements + if reduction == "sum": + return score.sum() + if reduction is None or reduction == "none": + return score + raise ValueError("Expected argument `reduction` to either be 'sum', 'mean', 'none' or None") + + +def total_variation(img: Tensor, reduction: Optional[Literal["mean", "sum", "none"]] = "sum") -> Tensor: + """Compute total variation loss. + + Args: + img: A `Tensor` of shape `(N, C, H, W)` consisting of images + reduction: a method to reduce metric score over samples. + + - ``'mean'``: takes the mean over samples + - ``'sum'``: takes the sum over samples + - ``None`` or ``'none'``: return the score per sample + + Returns: + A loss scalar value containing the total variation + + Raises: + ValueError: + If ``reduction`` is not one of ``'sum'``, ``'mean'``, ``'none'`` or ``None`` + RuntimeError: + If ``img`` is not 4D tensor + + Example: + >>> from torch import rand + >>> from torchmetrics.functional.image import total_variation + >>> img = rand(5, 3, 28, 28) + >>> total_variation(img) + tensor(7546.8018) + + """ + # code adapted from: + # from kornia.losses import total_variation as kornia_total_variation + score, num_elements = _total_variation_update(img) + return _total_variation_compute(score, num_elements, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/uqi.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/uqi.py new file mode 100644 index 0000000000000000000000000000000000000000..2b8d6f3cfa77ac62d38592b23f30fbf72d62c5bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/uqi.py @@ -0,0 +1,171 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Optional + +import torch +from torch import Tensor, nn +from typing_extensions import Literal + +from torchmetrics.functional.image.utils import _gaussian_kernel_2d +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.distributed import reduce + + +def _uqi_update(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute Universal Image Quality Index. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + if preds.dtype != target.dtype: + raise TypeError( + "Expected `preds` and `target` to have the same data type." + f" Got preds: {preds.dtype} and target: {target.dtype}." + ) + _check_same_shape(preds, target) + if len(preds.shape) != 4: + raise ValueError( + f"Expected `preds` and `target` to have BxCxHxW shape. Got preds: {preds.shape} and target: {target.shape}." + ) + return preds, target + + +def _uqi_compute( + preds: Tensor, + target: Tensor, + kernel_size: Sequence[int] = (11, 11), + sigma: Sequence[float] = (1.5, 1.5), + reduction: Optional[Literal["elementwise_mean", "sum", "none"]] = "elementwise_mean", +) -> Tensor: + """Compute Universal Image Quality Index. + + Args: + preds: estimated image + target: ground truth image + kernel_size: size of the gaussian kernel + sigma: Standard deviation of the gaussian kernel + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + Example: + >>> preds = torch.rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> preds, target = _uqi_update(preds, target) + >>> _uqi_compute(preds, target) + tensor(0.9216) + + """ + if len(kernel_size) != 2 or len(sigma) != 2: + raise ValueError( + "Expected `kernel_size` and `sigma` to have the length of two." + f" Got kernel_size: {len(kernel_size)} and sigma: {len(sigma)}." + ) + + if any(x % 2 == 0 or x <= 0 for x in kernel_size): + raise ValueError(f"Expected `kernel_size` to have odd positive number. Got {kernel_size}.") + + if any(y <= 0 for y in sigma): + raise ValueError(f"Expected `sigma` to have positive number. Got {sigma}.") + + device = preds.device + channel = preds.size(1) + dtype = preds.dtype + kernel = _gaussian_kernel_2d(channel, kernel_size, sigma, dtype, device) + pad_h = (kernel_size[0] - 1) // 2 + pad_w = (kernel_size[1] - 1) // 2 + + preds = nn.functional.pad(preds, (pad_h, pad_h, pad_w, pad_w), mode="reflect") + target = nn.functional.pad(target, (pad_h, pad_h, pad_w, pad_w), mode="reflect") + + input_list = torch.cat((preds, target, preds * preds, target * target, preds * target)) # (5 * B, C, H, W) + outputs = nn.functional.conv2d(input_list, kernel, groups=channel) + output_list = outputs.split(preds.shape[0]) + + mu_pred_sq = output_list[0].pow(2) + mu_target_sq = output_list[1].pow(2) + mu_pred_target = output_list[0] * output_list[1] + + # Calculate the variance of the predicted and target images, should be non-negative + sigma_pred_sq = torch.clamp(output_list[2] - mu_pred_sq, min=0.0) + sigma_target_sq = torch.clamp(output_list[3] - mu_target_sq, min=0.0) + sigma_pred_target = output_list[4] - mu_pred_target + + upper = 2 * sigma_pred_target + lower = sigma_pred_sq + sigma_target_sq + eps = torch.finfo(sigma_pred_sq.dtype).eps + uqi_idx = ((2 * mu_pred_target) * upper) / ((mu_pred_sq + mu_target_sq) * lower + eps) + uqi_idx = uqi_idx[..., pad_h:-pad_h, pad_w:-pad_w] + + return reduce(uqi_idx, reduction) + + +def universal_image_quality_index( + preds: Tensor, + target: Tensor, + kernel_size: Sequence[int] = (11, 11), + sigma: Sequence[float] = (1.5, 1.5), + reduction: Optional[Literal["elementwise_mean", "sum", "none"]] = "elementwise_mean", +) -> Tensor: + """Universal Image Quality Index. + + Args: + preds: estimated image + target: ground truth image + kernel_size: size of the gaussian kernel + sigma: Standard deviation of the gaussian kernel + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + Return: + Tensor with UniversalImageQualityIndex score + + Raises: + TypeError: + If ``preds`` and ``target`` don't have the same data type. + ValueError: + If ``preds`` and ``target`` don't have ``BxCxHxW shape``. + ValueError: + If the length of ``kernel_size`` or ``sigma`` is not ``2``. + ValueError: + If one of the elements of ``kernel_size`` is not an ``odd positive number``. + ValueError: + If one of the elements of ``sigma`` is not a ``positive number``. + + Example: + >>> from torchmetrics.functional.image import universal_image_quality_index + >>> preds = torch.rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> universal_image_quality_index(preds, target) + tensor(0.9216) + + References: + [1] Zhou Wang and A. C. Bovik, "A universal image quality index," in IEEE Signal Processing Letters, vol. 9, + no. 3, pp. 81-84, March 2002, doi: 10.1109/97.995823. + + [2] Zhou Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli, "Image quality assessment: from error visibility + to structural similarity," in IEEE Transactions on Image Processing, vol. 13, no. 4, pp. 600-612, April 2004, + doi: 10.1109/TIP.2003.819861. + + """ + preds, target = _uqi_update(preds, target) + return _uqi_compute(preds, target, kernel_size, sigma, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..24ed9cd0de83faf02b17aa05c733d12a3049ef8d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/utils.py @@ -0,0 +1,173 @@ +from collections.abc import Sequence +from typing import Union + +import torch +from torch import Tensor +from torch.nn import functional as F # noqa: N812 + + +def _gaussian(kernel_size: int, sigma: float, dtype: torch.dtype, device: Union[torch.device, str]) -> Tensor: + """Compute 1D gaussian kernel. + + Args: + kernel_size: size of the gaussian kernel + sigma: Standard deviation of the gaussian kernel + dtype: data type of the output tensor + device: device of the output tensor + + Example: + >>> _gaussian(3, 1, torch.float, 'cpu') + tensor([[0.2741, 0.4519, 0.2741]]) + + """ + dist = torch.arange(start=(1 - kernel_size) / 2, end=(1 + kernel_size) / 2, step=1, dtype=dtype, device=device) + gauss = torch.exp(-torch.pow(dist / sigma, 2) / 2) + return (gauss / gauss.sum()).unsqueeze(dim=0) # (1, kernel_size) + + +def _gaussian_kernel_2d( + channel: int, + kernel_size: Sequence[int], + sigma: Sequence[float], + dtype: torch.dtype, + device: Union[torch.device, str], +) -> Tensor: + """Compute 2D gaussian kernel. + + Args: + channel: number of channels in the image + kernel_size: size of the gaussian kernel as a tuple (h, w) + sigma: Standard deviation of the gaussian kernel + dtype: data type of the output tensor + device: device of the output tensor + + Example: + >>> _gaussian_kernel_2d(1, (5,5), (1,1), torch.float, "cpu") + tensor([[[[0.0030, 0.0133, 0.0219, 0.0133, 0.0030], + [0.0133, 0.0596, 0.0983, 0.0596, 0.0133], + [0.0219, 0.0983, 0.1621, 0.0983, 0.0219], + [0.0133, 0.0596, 0.0983, 0.0596, 0.0133], + [0.0030, 0.0133, 0.0219, 0.0133, 0.0030]]]]) + + """ + gaussian_kernel_x = _gaussian(kernel_size[0], sigma[0], dtype, device) + gaussian_kernel_y = _gaussian(kernel_size[1], sigma[1], dtype, device) + kernel = torch.matmul(gaussian_kernel_x.t(), gaussian_kernel_y) # (kernel_size, 1) * (1, kernel_size) + + return kernel.expand(channel, 1, kernel_size[0], kernel_size[1]) + + +def _uniform_weight_bias_conv2d(inputs: Tensor, window_size: int) -> tuple[Tensor, Tensor]: + """Construct uniform weight and bias for a 2d convolution. + + Args: + inputs: Input image + window_size: size of convolutional kernel + + Return: + The weight and bias for 2d convolution + + """ + kernel_weight = torch.ones(1, 1, window_size, window_size, dtype=inputs.dtype, device=inputs.device) + kernel_weight /= window_size**2 + kernel_bias = torch.zeros(1, dtype=inputs.dtype, device=inputs.device) + return kernel_weight, kernel_bias + + +def _single_dimension_pad(inputs: Tensor, dim: int, pad: int, outer_pad: int = 0) -> Tensor: + """Apply single-dimension reflection padding to match scipy implementation. + + Args: + inputs: Input image + dim: A dimension the image should be padded over + pad: Number of pads + outer_pad: Number of outer pads + + Return: + Image padded over a single dimension + + """ + _max = inputs.shape[dim] + x = torch.index_select(inputs, dim, torch.arange(pad - 1, -1, -1).to(inputs.device)) + y = torch.index_select(inputs, dim, torch.arange(_max - 1, _max - pad - outer_pad, -1).to(inputs.device)) + return torch.cat((x, inputs, y), dim) + + +def _reflection_pad_2d(inputs: Tensor, pad: int, outer_pad: int = 0) -> Tensor: + """Apply reflection padding to the input image. + + Args: + inputs: Input image + pad: Number of pads + outer_pad: Number of outer pads + + Return: + Padded image + + """ + for dim in [2, 3]: + inputs = _single_dimension_pad(inputs, dim, pad, outer_pad) + return inputs + + +def _uniform_filter(inputs: Tensor, window_size: int) -> Tensor: + """Apply uniform filter with a window of a given size over the input image. + + Args: + inputs: Input image + window_size: Sliding window used for rmse calculation + + Return: + Image transformed with the uniform input + + """ + inputs = _reflection_pad_2d(inputs, window_size // 2, window_size % 2) + kernel_weight, kernel_bias = _uniform_weight_bias_conv2d(inputs, window_size) + # Iterate over channels + return torch.cat( + [ + F.conv2d(inputs[:, channel].unsqueeze(1), kernel_weight, kernel_bias, padding=0) + for channel in range(inputs.shape[1]) + ], + dim=1, + ) + + +def _gaussian_kernel_3d( + channel: int, kernel_size: Sequence[int], sigma: Sequence[float], dtype: torch.dtype, device: torch.device +) -> Tensor: + """Compute 3D gaussian kernel. + + Args: + channel: number of channels in the image + kernel_size: size of the gaussian kernel as a tuple (h, w, d) + sigma: Standard deviation of the gaussian kernel + dtype: data type of the output tensor + device: device of the output tensor + + """ + gaussian_kernel_x = _gaussian(kernel_size[0], sigma[0], dtype, device) + gaussian_kernel_y = _gaussian(kernel_size[1], sigma[1], dtype, device) + gaussian_kernel_z = _gaussian(kernel_size[2], sigma[2], dtype, device) + kernel_xy = torch.matmul(gaussian_kernel_x.t(), gaussian_kernel_y) # (kernel_size, 1) * (1, kernel_size) + kernel = torch.mul( + kernel_xy.unsqueeze(-1).repeat(1, 1, kernel_size[2]), + gaussian_kernel_z.expand(kernel_size[0], kernel_size[1], kernel_size[2]), + ) + return kernel.expand(channel, 1, kernel_size[0], kernel_size[1], kernel_size[2]) + + +def _reflection_pad_3d(inputs: Tensor, pad_h: int, pad_w: int, pad_d: int) -> Tensor: + """Reflective padding of 3d input. + + Args: + inputs: tensor to pad, should be a 3D tensor of shape ``[N, C, H, W, D]`` + pad_w: amount of padding in the height dimension + pad_h: amount of padding in the width dimension + pad_d: amount of padding in the depth dimension + + Returns: + padded input tensor + + """ + return F.pad(inputs, (pad_h, pad_h, pad_w, pad_w, pad_d, pad_d), mode="reflect") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/vif.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/vif.py new file mode 100644 index 0000000000000000000000000000000000000000..cacf0616116464fd3d812b2d5f096e5f77f1227b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/vif.py @@ -0,0 +1,154 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from torch import Tensor +from torch.nn.functional import conv2d +from typing_extensions import Literal + +from torchmetrics.utilities.data import dim_zero_cat + + +def _filter(win_size: float, sigma: float, dtype: torch.dtype, device: torch.device) -> Tensor: + # This code is inspired by + # https://github.com/andrewekhalel/sewar/blob/ac76e7bc75732fde40bb0d3908f4b6863400cc27/sewar/utils.py#L45 + # https://github.com/photosynthesis-team/piq/blob/01e16b7d8c76bc8765fb6a69560d806148b8046a/piq/functional/filters.py#L38 + # Both links do the same, but the second one is cleaner + coords = torch.arange(win_size, dtype=dtype, device=device) - (win_size - 1) / 2 + g = coords**2 + g = torch.exp(-(g.unsqueeze(0) + g.unsqueeze(1)) / (2.0 * sigma**2)) + g /= torch.sum(g) + return g + + +def _vif_per_channel(preds: Tensor, target: Tensor, sigma_n_sq: float) -> Tensor: + dtype = preds.dtype + device = preds.device + + preds = preds.unsqueeze(1) # Add channel dimension + target = target.unsqueeze(1) + # Constant for numerical stability + eps = torch.tensor(1e-10, dtype=dtype, device=device) + + sigma_n_sq = torch.tensor(sigma_n_sq, dtype=dtype, device=device) + + preds_vif = torch.zeros(preds.size(0), dtype=dtype, device=device) + target_vif = torch.zeros(preds.size(0), dtype=dtype, device=device) + + for scale in range(4): + n = 2.0 ** (4 - scale) + 1 + kernel = _filter(n, n / 5, dtype=dtype, device=device)[None, None, :] + + if scale > 0: + target = conv2d(target, kernel)[:, :, ::2, ::2] + preds = conv2d(preds, kernel)[:, :, ::2, ::2] + + mu_target = conv2d(target, kernel) + mu_preds = conv2d(preds, kernel) + mu_target_sq = mu_target**2 + mu_preds_sq = mu_preds**2 + mu_target_preds = mu_target * mu_preds + + sigma_target_sq = torch.clamp(conv2d(target**2, kernel) - mu_target_sq, min=0.0) + sigma_preds_sq = torch.clamp(conv2d(preds**2, kernel) - mu_preds_sq, min=0.0) + sigma_target_preds = conv2d(target * preds, kernel) - mu_target_preds + + g = sigma_target_preds / (sigma_target_sq + eps) + sigma_v_sq = sigma_preds_sq - g * sigma_target_preds + + mask = sigma_target_sq < eps + g[mask] = 0 + sigma_v_sq[mask] = sigma_preds_sq[mask] + sigma_target_sq[mask] = 0 + + mask = sigma_preds_sq < eps + g[mask] = 0 + sigma_v_sq[mask] = 0 + + mask = g < 0 + sigma_v_sq[mask] = sigma_preds_sq[mask] + g[mask] = 0 + sigma_v_sq = torch.clamp(sigma_v_sq, min=eps) + + preds_vif += torch.sum(torch.log10(1.0 + (g**2.0) * sigma_target_sq / (sigma_v_sq + sigma_n_sq)), dim=[1, 2, 3]) + target_vif += torch.sum(torch.log10(1.0 + sigma_target_sq / sigma_n_sq), dim=[1, 2, 3]) + + return preds_vif / target_vif + + +def visual_information_fidelity( + preds: Tensor, + target: Tensor, + sigma_n_sq: float = 2.0, + reduction: Literal["mean", "none"] = "mean", +) -> Tensor: + """Compute Pixel-Based Visual Information Fidelity (VIF-P). + + VIF is a full-reference metric that measures the amount of visual information + preserved in a distorted image compared to the reference image. + + Args: + preds: Predicted images of shape (N, C, H, W). Height and width must be at least 41. + target: Ground truth images of shape (N, C, H, W). Must match preds in shape. + sigma_n_sq: Variance of the visual noise. Default: 2.0. + reduction: Method for reducing the metric across the batch. + - "mean": Return a tensor average over the batch. + - "none": Return a VIF score for each sample as a 1D tensor of shape (N,). + + Returns: + torch.Tensor: VIF score(s). The shape depends on the `reduction` argument: + - If ``reduction="mean"``, returns a scalar tensor. + - If ``reduction="none"``, returns a tensor of shape ``(N,)``. + + Raises: + ValueError: If input dimensions are smaller than ``41x41``. + ValueError: If ``preds`` and ``target`` shapes don't match. + ValueError: If ``reduction`` is not ``"mean"`` or ``"none"``. + + Example: + >>> from torchmetrics.functional.image import visual_information_fidelity + >>> preds = torch.randn(4, 3, 41, 41, generator=torch.Generator().manual_seed(42)) + >>> target = torch.randn(4, 3, 41, 41, generator=torch.Generator().manual_seed(43)) + >>> visual_information_fidelity(preds, target, reduction="none") + tensor([0.0040, 0.0049, 0.0017, 0.0039]) + + """ + # This code is inspired by + # https://github.com/photosynthesis-team/piq/blob/01e16b7d8c76bc8765fb6a69560d806148b8046a/piq/vif.py and + # https://github.com/andrewekhalel/sewar/blob/ac76e7bc75732fde40bb0d3908f4b6863400cc27/sewar/full_ref.py#L357. + + if preds.size(-1) < 41 or preds.size(-2) < 41: + raise ValueError(f"Invalid size of preds. Expected at least 41x41, but got {preds.size(-1)}x{preds.size(-2)}!") + + if target.size(-1) < 41 or target.size(-2) < 41: + raise ValueError( + f"Invalid size of target. Expected at least 41x41, but got {target.size(-1)}x{target.size(-2)}!" + ) + + if preds.shape != target.shape: + raise ValueError(f"`preds` and `target` must have the same shape, but got {preds.shape} vs {target.shape}.") + + if reduction not in ("mean", "none"): + raise ValueError(f"Argument `reduction` must be 'mean' or 'none', but got {reduction}") + + per_channel_scores = [ + _vif_per_channel(preds[:, i, :, :], target[:, i, :, :], sigma_n_sq) for i in range(preds.size(1)) + ] + + vif_per_sample = dim_zero_cat( + torch.stack(per_channel_scores, dim=0).mean(0) if preds.size(1) > 1 else per_channel_scores[0] + ) + + if reduction == "mean": + return vif_per_sample.mean() + return vif_per_sample diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9f5e199a4d2da86ab619c0e9ae8db4d2b44eef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/__init__.py @@ -0,0 +1,23 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.functional.multimodal.lve import lip_vertex_error +from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_10 + +__all__ = ["lip_vertex_error"] + +if _TRANSFORMERS_GREATER_EQUAL_4_10: + from torchmetrics.functional.multimodal.clip_iqa import clip_image_quality_assessment + from torchmetrics.functional.multimodal.clip_score import clip_score + + __all__ += ["clip_image_quality_assessment", "clip_score"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_iqa.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_iqa.py new file mode 100644 index 0000000000000000000000000000000000000000..44b097ac8e2f5919c4cb092b1d9495d2eaf85404 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_iqa.py @@ -0,0 +1,350 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import TYPE_CHECKING, Literal, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.multimodal.clip_score import _get_clip_model_and_processor +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.imports import _PIQ_GREATER_EQUAL_0_8, _TRANSFORMERS_GREATER_EQUAL_4_10 + +if TYPE_CHECKING: + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + +if _SKIP_SLOW_DOCTEST and _TRANSFORMERS_GREATER_EQUAL_4_10: + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + + def _download_clip_for_iqa_metric() -> None: + _CLIPModel.from_pretrained("openai/clip-vit-base-patch16", resume_download=True) + _CLIPProcessor.from_pretrained("openai/clip-vit-base-patch16", resume_download=True) + + if not _try_proceed_with_timeout(_download_clip_for_iqa_metric): + __doctest_skip__ = ["clip_image_quality_assessment"] +else: + __doctest_skip__ = ["clip_image_quality_assessment"] + +if not _PIQ_GREATER_EQUAL_0_8: + __doctest_skip__ = ["clip_image_quality_assessment"] + +_PROMPTS: dict[str, tuple[str, str]] = { + "quality": ("Good photo.", "Bad photo."), + "brightness": ("Bright photo.", "Dark photo."), + "noisiness": ("Clean photo.", "Noisy photo."), + "colorfullness": ("Colorful photo.", "Dull photo."), + "sharpness": ("Sharp photo.", "Blurry photo."), + "contrast": ("High contrast photo.", "Low contrast photo."), + "complexity": ("Complex photo.", "Simple photo."), + "natural": ("Natural photo.", "Synthetic photo."), + "happy": ("Happy photo.", "Sad photo."), + "scary": ("Scary photo.", "Peaceful photo."), + "new": ("New photo.", "Old photo."), + "warm": ("Warm photo.", "Cold photo."), + "real": ("Real photo.", "Abstract photo."), + "beautiful": ("Beautiful photo.", "Ugly photo."), + "lonely": ("Lonely photo.", "Sociable photo."), + "relaxing": ("Relaxing photo.", "Stressful photo."), +} + + +def _get_clip_iqa_model_and_processor( + model_name_or_path: Literal[ + "clip_iqa", + "openai/clip-vit-base-patch16", + "openai/clip-vit-base-patch32", + "openai/clip-vit-large-patch14-336", + "openai/clip-vit-large-patch14", + ], +) -> tuple["_CLIPModel", "_CLIPProcessor"]: + """Extract the CLIP model and processor from the model name or path.""" + from transformers import CLIPProcessor as _CLIPProcessor + + if model_name_or_path == "clip_iqa": + if not _PIQ_GREATER_EQUAL_0_8: + raise ValueError( + "For metric `clip_iqa` to work with argument `model_name_or_path` set to default value `'clip_iqa'`" + ", package `piq` version v0.8.0 or later must be installed. Either install with `pip install piq` or" + "`pip install torchmetrics[multimodal]`" + ) + + import piq + + model = piq.clip_iqa.clip.load().eval() + # any model checkpoint can be used here because the tokenizer is the same for all + processor = _CLIPProcessor.from_pretrained("openai/clip-vit-base-patch16") + return model, processor + return _get_clip_model_and_processor(model_name_or_path) + + +def _clip_iqa_format_prompts( + prompts: tuple[Union[str, tuple[str, str]], ...] = ("quality",), +) -> tuple[list[str], list[str]]: + """Converts the provided keywords into a list of prompts for the model to calculate the anchor vectors. + + Args: + prompts: A string, tuple of strings or nested tuple of strings. If a single string is provided, it must be one + of the available prompts (see above). Else the input is expected to be a tuple, where each element can + be one of two things: either a string or a tuple of strings. If a string is provided, it must be one of the + available prompts (see above). If tuple is provided, it must be of length 2 and the first string must be a + positive prompt and the second string must be a negative prompt. + + Returns: + Tuple containing a list of prompts and a list of the names of the prompts. The first list is double the length + of the second list. + + Examples:: + + >>> # single prompt + >>> _clip_iqa_format_prompts(("quality",)) + (['Good photo.', 'Bad photo.'], ['quality']) + >>> # multiple prompts + >>> _clip_iqa_format_prompts(("quality", "brightness")) + (['Good photo.', 'Bad photo.', 'Bright photo.', 'Dark photo.'], ['quality', 'brightness']) + >>> # Custom prompts + >>> _clip_iqa_format_prompts(("quality", ("Super good photo.", "Super bad photo."))) + (['Good photo.', 'Bad photo.', 'Super good photo.', 'Super bad photo.'], ['quality', 'user_defined_0']) + + """ + if not isinstance(prompts, tuple): + raise ValueError("Argument `prompts` must be a tuple containing strings or tuples of strings") + + prompts_names: list[str] = [] + prompts_list: list[str] = [] + count = 0 + for p in prompts: + if not isinstance(p, (str, tuple)): + raise ValueError("Argument `prompts` must be a tuple containing strings or tuples of strings") + if isinstance(p, str): + if p not in _PROMPTS: + raise ValueError( + f"All elements of `prompts` must be one of {_PROMPTS.keys()} if not custom tuple prompts, got {p}." + ) + prompts_names.append(p) + prompts_list.extend(_PROMPTS[p]) + if isinstance(p, tuple) and len(p) != 2: + raise ValueError("If a tuple is provided in argument `prompts`, it must be of length 2") + if isinstance(p, tuple): + prompts_names.append(f"user_defined_{count}") + prompts_list.extend(p) + count += 1 + + return prompts_list, prompts_names + + +def _clip_iqa_get_anchor_vectors( + model_name_or_path: str, + model: "_CLIPModel", + processor: "_CLIPProcessor", + prompts_list: list[str], + device: Union[str, torch.device], +) -> Tensor: + """Calculates the anchor vectors for the CLIP IQA metric. + + Args: + model_name_or_path: string indicating the version of the CLIP model to use. + model: The CLIP model + processor: The CLIP processor + prompts_list: A list of prompts + device: The device to use for the calculation + + """ + if model_name_or_path == "clip_iqa": + text_processed = processor(text=prompts_list) + anchors_text = torch.zeros( + len(prompts_list), processor.tokenizer.model_max_length, dtype=torch.long, device=device + ) + for i, tp in enumerate(text_processed["input_ids"]): + anchors_text[i, : len(tp)] = torch.tensor(tp, dtype=torch.long, device=device) + + anchors = model.encode_text(anchors_text).float() + else: + text_processed = processor(text=prompts_list, return_tensors="pt", padding=True) + anchors = model.get_text_features( + text_processed["input_ids"].to(device), text_processed["attention_mask"].to(device) + ) + return anchors / anchors.norm(p=2, dim=-1, keepdim=True) + + +def _clip_iqa_update( + model_name_or_path: str, + images: Tensor, + model: "_CLIPModel", + processor: "_CLIPProcessor", + data_range: float, + device: Union[str, torch.device], +) -> Tensor: + images = images / float(data_range) + """Update function for CLIP IQA.""" + if model_name_or_path == "clip_iqa": + # default mean and std from clip paper, see: + # https://github.com/huggingface/transformers/blob/main/src/transformers/utils/constants.py + default_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073], device=device).view(1, 3, 1, 1) + default_std = torch.tensor([0.26862954, 0.26130258, 0.27577711], device=device).view(1, 3, 1, 1) + images = (images - default_mean) / default_std + img_features = model.encode_image(images.float(), pos_embedding=False).float() + else: + processed_input = processor(images=[i.cpu() for i in images], return_tensors="pt", padding=True) + img_features = model.get_image_features(processed_input["pixel_values"].to(device)) + return img_features / img_features.norm(p=2, dim=-1, keepdim=True) + + +def _clip_iqa_compute( + img_features: Tensor, + anchors: Tensor, + prompts_names: list[str], + format_as_dict: bool = True, +) -> Union[Tensor, dict[str, Tensor]]: + """Final computation of CLIP IQA.""" + logits_per_image = 100 * img_features @ anchors.t() + probs = logits_per_image.reshape(logits_per_image.shape[0], -1, 2).softmax(-1)[:, :, 0] + if len(prompts_names) == 1: + return probs.squeeze() + if format_as_dict: + return {p: probs[:, i] for i, p in enumerate(prompts_names)} + return probs + + +def clip_image_quality_assessment( + images: Tensor, + model_name_or_path: Literal[ + "clip_iqa", + "openai/clip-vit-base-patch16", + "openai/clip-vit-base-patch32", + "openai/clip-vit-large-patch14-336", + "openai/clip-vit-large-patch14", + ] = "clip_iqa", + data_range: float = 1.0, + prompts: tuple[Union[str, tuple[str, str]], ...] = ("quality",), +) -> Union[Tensor, dict[str, Tensor]]: + """Calculates `CLIP-IQA`_, that can be used to measure the visual content of images. + + The metric is based on the `CLIP`_ model, which is a neural network trained on a variety of (image, text) pairs to + be able to generate a vector representation of the image and the text that is similar if the image and text are + semantically similar. + + The metric works by calculating the cosine similarity between user provided images and pre-defined prompts. The + prompts always come in pairs of "positive" and "negative" such as "Good photo." and "Bad photo.". By calculating + the similartity between image embeddings and both the "positive" and "negative" prompt, the metric can determine + which prompt the image is more similar to. The metric then returns the probability that the image is more similar + to the first prompt than the second prompt. + + Build in prompts are: + * quality: "Good photo." vs "Bad photo." + * brightness: "Bright photo." vs "Dark photo." + * noisiness: "Clean photo." vs "Noisy photo." + * colorfullness: "Colorful photo." vs "Dull photo." + * sharpness: "Sharp photo." vs "Blurry photo." + * contrast: "High contrast photo." vs "Low contrast photo." + * complexity: "Complex photo." vs "Simple photo." + * natural: "Natural photo." vs "Synthetic photo." + * happy: "Happy photo." vs "Sad photo." + * scary: "Scary photo." vs "Peaceful photo." + * new: "New photo." vs "Old photo." + * warm: "Warm photo." vs "Cold photo." + * real: "Real photo." vs "Abstract photo." + * beautiful: "Beautiful photo." vs "Ugly photo." + * lonely: "Lonely photo." vs "Sociable photo." + * relaxing: "Relaxing photo." vs "Stressful photo." + + Args: + images: Either a single ``[N, C, H, W]`` tensor or a list of ``[C, H, W]`` tensors + model_name_or_path: string indicating the version of the CLIP model to use. By default this argument is set to + ``clip_iqa`` which corresponds to the model used in the original paper. Other available models are + `"openai/clip-vit-base-patch16"`, `"openai/clip-vit-base-patch32"`, `"openai/clip-vit-large-patch14-336"` + and `"openai/clip-vit-large-patch14"` + data_range: The maximum value of the input tensor. For example, if the input images are in range [0, 255], + data_range should be 255. The images are normalized by this value. + prompts: A string, tuple of strings or nested tuple of strings. If a single string is provided, it must be one + of the available prompts (see above). Else the input is expected to be a tuple, where each element can + be one of two things: either a string or a tuple of strings. If a string is provided, it must be one of the + available prompts (see above). If tuple is provided, it must be of length 2 and the first string must be a + positive prompt and the second string must be a negative prompt. + + .. hint:: + If using the default `clip_iqa` model, the package `piq` must be installed. Either install with + `pip install piq` or `pip install torchmetrics[multimodal]`. + + Returns: + A tensor of shape ``(N,)`` if a single prompts is provided. If a list of prompts is provided, a dictionary of + with the prompts as keys and tensors of shape ``(N,)`` as values. + + Raises: + ModuleNotFoundError: + If transformers package is not installed or version is lower than 4.10.0 + ValueError: + If not all images have format [C, H, W] + ValueError: + If prompts is a tuple and it is not of length 2 + ValueError: + If prompts is a string and it is not one of the available prompts + ValueError: + If prompts is a list of strings and not all strings are one of the available prompts + + Example:: + Single prompt: + + >>> from torch import randint + >>> from torchmetrics.functional.multimodal import clip_image_quality_assessment + >>> imgs = randint(255, (2, 3, 224, 224)).float() + >>> clip_image_quality_assessment(imgs, prompts=("quality",)) + tensor([0.8894, 0.8902]) + + Example:: + Multiple prompts: + + >>> from torch import randint + >>> from torchmetrics.functional.multimodal import clip_image_quality_assessment + >>> imgs = randint(255, (2, 3, 224, 224)).float() + >>> clip_image_quality_assessment(imgs, prompts=("quality", "brightness")) + {'quality': tensor([0.8693, 0.8705]), 'brightness': tensor([0.5722, 0.4762])} + + Example:: + Custom prompts. Must always be a tuple of length 2, with a positive and negative prompt. + + >>> from torch import rand + >>> from torchmetrics.functional.multimodal import clip_image_quality_assessment + >>> imgs = randint(255, (2, 3, 224, 224)).float() + >>> clip_image_quality_assessment(imgs, prompts=(("Super good photo.", "Super bad photo."), "brightness")) + {'user_defined_0': tensor([0.9578, 0.9654]), 'brightness': tensor([0.5495, 0.5764])} + + """ + prompts_list, prompts_names = _clip_iqa_format_prompts(prompts) + + model, processor = _get_clip_iqa_model_and_processor(model_name_or_path) + device = images.device + model = model.to(device) + + with torch.inference_mode(): + anchors = _clip_iqa_get_anchor_vectors(model_name_or_path, model, processor, prompts_list, device) + img_features = _clip_iqa_update(model_name_or_path, images, model, processor, data_range, device) + return _clip_iqa_compute(img_features, anchors, prompts_names) + + +if TYPE_CHECKING: + from functools import partial + from typing import Any, cast + + images = cast(Any, None) + + f = partial(clip_image_quality_assessment, images=images) + f(prompts=("colorfullness",)) + f( + prompts=("quality", "brightness", "noisiness"), + ) + f( + prompts=("quality", "brightness", "noisiness", "colorfullness"), + ) + f(prompts=(("Photo of a cat", "Photo of a dog"), "quality", ("Colorful photo", "Black and white photo"))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_score.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_score.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a8e82669a6f10c5c94ebd84df1a95238316a13 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_score.py @@ -0,0 +1,354 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import TYPE_CHECKING, Any, Callable, List, Union, cast + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_10 + +if TYPE_CHECKING and _TRANSFORMERS_GREATER_EQUAL_4_10: + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + +if _SKIP_SLOW_DOCTEST and _TRANSFORMERS_GREATER_EQUAL_4_10: + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + + def _download_clip_for_clip_score() -> None: + _CLIPModel.from_pretrained("openai/clip-vit-large-patch14", resume_download=True) + _CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14", resume_download=True) + + if not _try_proceed_with_timeout(_download_clip_for_clip_score): + __doctest_skip__ = ["clip_score"] +else: + __doctest_skip__ = ["clip_score"] + _CLIPModel = None + _CLIPProcessor = None + + +class JinaProcessorWrapper: + """Wrapper class to convert tensors to PIL images if needed for Jina CLIP model.""" + + def __init__(self, processor: _CLIPProcessor) -> None: + self.processor = processor + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + """Wrap the processor's __call__ method to convert tensors to PIL images if needed.""" + # Check if 'images' is in kwargs and convert tensors to PIL images if needed + from torchvision.transforms.functional import to_pil_image + + if "images" in kwargs: + kwargs["images"] = [ + to_pil_image(img.float().cpu()) if isinstance(img, Tensor) else img for img in kwargs["images"] + ] + return self.processor(*args, **kwargs) + + +def _detect_modality(input_data: Union[Tensor, List[Tensor], List[str], str]) -> Literal["image", "text"]: + """Automatically detect the modality of the input data. + + Args: + input_data: Input data that can be either image tensors or text strings + + Returns: + str: Either "image" or "text" + + Raises: + ValueError: If the input_data is an empty list or modality cannot be determined + + """ + if isinstance(input_data, Tensor): + return "image" + + if isinstance(input_data, list): + if len(input_data) == 0: + raise ValueError("Empty input list") + if isinstance(input_data[0], Tensor): + return "image" + if isinstance(input_data[0], str): + return "text" + + if isinstance(input_data, str): + return "text" + + raise ValueError("Could not automatically determine modality for input_data") + + +def _process_image_data(images: Union[Tensor, List[Tensor]]) -> List[Tensor]: + """Helper function to process image data.""" + images = [images] if not isinstance(images, list) and images.ndim == 3 else list(images) + if not all(i.ndim == 3 for i in images): + raise ValueError("Expected all images to be 3d but found image that has either more or less") + return images + + +def _process_text_data(texts: Union[str, List[str]]) -> List[str]: + """Helper function to process text data.""" + if not isinstance(texts, list): + texts = [texts] + return texts + + +def _get_features( + data: List[Union[Tensor, str]], + modality: str, + device: torch.device, + model: "_CLIPModel", + processor: "_CLIPProcessor", +) -> Tensor: + """Get features from the CLIP model for either images or text. + + Args: + data: List of input data (images or text) + modality: String indicating the type of input data (must be either "image" or "text") + device: Device to run the model on + model: CLIP model instance + processor: CLIP processor instance + + Returns: + Tensor of features from the CLIP model + + Raises: + ValueError: If modality is not "image" or "text" + + """ + if modality == "image": + image_data = [i for i in data if isinstance(i, Tensor)] # Add type checking for images + processed = processor(images=[i.cpu() for i in image_data], return_tensors="pt", padding=True) + return model.get_image_features(processed["pixel_values"].to(device)) + if modality == "text": + processed = processor(text=data, return_tensors="pt", padding=True) + if hasattr(model.config, "text_config") and hasattr(model.config.text_config, "max_position_embeddings"): + max_position_embeddings = model.config.text_config.max_position_embeddings + if processed["attention_mask"].shape[-1] > max_position_embeddings: + rank_zero_warn( + f"Encountered caption longer than {max_position_embeddings=}. Will truncate captions to this" + "length. If longer captions are needed, initialize argument `model_name_or_path` with a model that" + "supports longer sequences.", + UserWarning, + ) + processed["attention_mask"] = processed["attention_mask"][..., :max_position_embeddings] + processed["input_ids"] = processed["input_ids"][..., :max_position_embeddings] + return model.get_text_features(processed["input_ids"].to(device), processed["attention_mask"].to(device)) + raise ValueError(f"invalid modality {modality}") + + +def _clip_score_update( + source: Union[Tensor, List[Tensor], List[str], str], + target: Union[Tensor, List[Tensor], List[str], str], + model: _CLIPModel, + processor: _CLIPProcessor, +) -> tuple[Tensor, int]: + """Update function for CLIP Score.""" + source_modality = _detect_modality(source) + target_modality = _detect_modality(target) + + source_data = ( + _process_image_data(cast(Union[Tensor, List[Tensor]], source)) + if source_modality == "image" + else _process_text_data(cast(Union[str, List[str]], source)) + ) + target_data = ( + _process_image_data(cast(Union[Tensor, List[Tensor]], target)) + if target_modality == "image" + else _process_text_data(cast(Union[str, List[str]], target)) + ) + + if len(source_data) != len(target_data): + raise ValueError( + "Expected the number of source and target examples to be the same but got " + f"{len(source_data)} and {len(target_data)}" + ) + + device = ( + source_data[0].device + if source_modality == "image" and isinstance(source_data[0], Tensor) + else target_data[0].device + if target_modality == "image" and isinstance(target_data[0], Tensor) + else torch.device("cuda" if torch.cuda.is_available() else "cpu") + ) + model = model.to(device) + + source_features = _get_features( + cast(List[Union[Tensor, str]], source_data), source_modality, device, model, processor + ) + target_features = _get_features( + cast(List[Union[Tensor, str]], target_data), target_modality, device, model, processor + ) + source_features = source_features / source_features.norm(p=2, dim=-1, keepdim=True) + target_features = target_features / target_features.norm(p=2, dim=-1, keepdim=True) + + # Calculate cosine similarity + score = 100 * (source_features * target_features).sum(axis=-1) + score = score.cpu() if source_modality == "text" and target_modality == "text" else score + return score, len(source_data) + + +def _get_clip_model_and_processor( + model_name_or_path: Union[ + Literal[ + "openai/clip-vit-base-patch16", + "openai/clip-vit-base-patch32", + "openai/clip-vit-large-patch14-336", + "openai/clip-vit-large-patch14", + "jinaai/jina-clip-v2", + "zer0int/LongCLIP-L-Diffusers", + "zer0int/LongCLIP-GmP-ViT-L-14", + ], + Callable[[], tuple[_CLIPModel, _CLIPProcessor]], + ], +) -> tuple[_CLIPModel, _CLIPProcessor]: + if callable(model_name_or_path): + return model_name_or_path() + + if _TRANSFORMERS_GREATER_EQUAL_4_10: + from transformers import AutoModel, AutoProcessor + from transformers import CLIPConfig as _CLIPConfig + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + + if "openai" in model_name_or_path: + model = _CLIPModel.from_pretrained(model_name_or_path) + processor = _CLIPProcessor.from_pretrained(model_name_or_path) + elif "jinaai" in model_name_or_path: + model = AutoModel.from_pretrained(model_name_or_path, trust_remote_code=True) + processor = JinaProcessorWrapper( + processor=AutoProcessor.from_pretrained(model_name_or_path, trust_remote_code=True) + ) + elif "zer0int" in model_name_or_path: + config = _CLIPConfig.from_pretrained(model_name_or_path) + config.text_config.max_position_embeddings = 248 + model = _CLIPModel.from_pretrained(model_name_or_path, config=config) + processor = _CLIPProcessor.from_pretrained(model_name_or_path, padding="max_length", max_length=248) + else: + raise ValueError(f"Invalid model_name_or_path {model_name_or_path}. Not supported by `clip_score` metric.") + return model, processor + + raise ModuleNotFoundError( + "`clip_score` metric requires `transformers` package be installed." + " Either install with `pip install transformers>=4.10.0` or `pip install torchmetrics[multimodal]`." + ) + + +def clip_score( + source: Union[Tensor, List[Tensor], List[str], str], + target: Union[Tensor, List[Tensor], List[str], str], + model_name_or_path: Union[ + Literal[ + "openai/clip-vit-base-patch16", + "openai/clip-vit-base-patch32", + "openai/clip-vit-large-patch14-336", + "openai/clip-vit-large-patch14", + "jinaai/jina-clip-v2", + "zer0int/LongCLIP-L-Diffusers", + "zer0int/LongCLIP-GmP-ViT-L-14", + ], + Callable[[], tuple[_CLIPModel, _CLIPProcessor]], + ] = "openai/clip-vit-large-patch14", +) -> Tensor: + r"""Calculates `CLIP Score`_ which is a text-to-image similarity metric. + + CLIP Score is a reference free metric that can be used to evaluate the correlation between a generated caption for + an image and the actual content of the image, as well as the similarity between texts or images. It has been found + to be highly correlated with human judgement. The metric is defined as: + + .. math:: + \text{CLIPScore(I, C)} = max(100 * cos(E_I, E_C), 0) + + which corresponds to the cosine similarity between visual `CLIP`_ embedding :math:`E_i` for an image :math:`i` and + textual CLIP embedding :math:`E_C` for an caption :math:`C`. The score is bound between 0 and 100 and the closer + to 100 the better. + + Additionally, the CLIP Score can be calculated for the same modalities: + + .. math:: + \text{CLIPScore(I_1, I_2)} = max(100 * cos(E_{I_1}, E_{I_2}), 0) + + where :math:`E_{I_1}` and :math:`E_{I_2}` are the visual embeddings for images :math:`I_1` and :math:`I_2`. + + .. math:: + \text{CLIPScore(T_1, T_2)} = max(100 * cos(E_{T_1}, E_{T_2}), 0) + + where :math:`E_{T_1}` and :math:`E_{T_2}` are the textual embeddings for texts :math:`T_1` and :math:`T_2`. + + .. note:: Metric is not scriptable + + .. note:: + The default CLIP and processor used in this implementation has a maximum sequence length of 77 for text + inputs. If you need to process longer captions, you can use the `zer0int/LongCLIP-L-Diffusers` model which + has a maximum sequence length of 248. + + Args: + source: Source input. This can be: + - Images: Either a single [N, C, H, W] tensor or a list of [C, H, W] tensors. + - Text: Either a single caption or a list of captions. + target: Target input. This can be: + - Images: Either a single [N, C, H, W] tensor or a list of [C, H, W] tensors. + - Text: Either a single caption or a list of captions. + model_name_or_path: String indicating the version of the CLIP model to use. Available models are: + - `"openai/clip-vit-base-patch16"` + - `"openai/clip-vit-base-patch32"` + - `"openai/clip-vit-large-patch14-336"` + - `"openai/clip-vit-large-patch14"` + - `"jinaai/jina-clip-v2"` + - `"zer0int/LongCLIP-L-Diffusers"` + - `"zer0int/LongCLIP-GmP-ViT-L-14"` + + Alternatively, a callable function that returns a tuple of CLIP compatible model and processor instances + can be passed in. By compatible, we mean that the processors `__call__` method should accept a list of + strings and list of images and that the model should have a `get_image_features` and `get_text_features` + methods. + + Raises: + ModuleNotFoundError: + If transformers package is not installed or version is lower than 4.10.0 + ValueError: + If not all images have format [C, H, W] + ValueError: + If the number of images and captions do not match + + Example: + >>> from torchmetrics.functional.multimodal import clip_score + >>> image = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(42)) + >>> score = clip_score(image, "a photo of a cat", "openai/clip-vit-base-patch16") + >>> score.detach().round(decimals=3) + tensor(24.4260) + + Example: + >>> from torchmetrics.functional.multimodal import clip_score + >>> image1 = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(42)) + >>> image2 = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(43)) + >>> score = clip_score(image1, image2, "openai/clip-vit-base-patch16") + >>> score.detach().round(decimals=3) + tensor(99.4860) + + Example: + >>> from torchmetrics.functional.multimodal import clip_score + >>> score = clip_score( + ... "28-year-old chef found dead in San Francisco mall", + ... "A 28-year-old chef who recently moved to San Francisco was found dead.", + ... "openai/clip-vit-base-patch16" + ... ) + >>> score.detach().round(decimals=3) + tensor(91.3950) + + """ + model, processor = _get_clip_model_and_processor(model_name_or_path) + score, _ = _clip_score_update(source, target, model, processor) + score = score.mean(0) + return torch.max(score, torch.zeros_like(score)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/lve.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/lve.py new file mode 100644 index 0000000000000000000000000000000000000000..e81737c5551353d625b0d912c881934828a4f574 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/lve.py @@ -0,0 +1,93 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import List + +import torch +from torch import Tensor + + +def lip_vertex_error( + vertices_pred: Tensor, + vertices_gt: Tensor, + mouth_map: List[int], + validate_args: bool = True, +) -> Tensor: + r"""Compute Lip Vertex Error (LVE) for 3D talking head evaluation. + + The Lip Vertex Error (LVE) metric evaluates the quality of lip synchronization in 3D facial animations by measuring + the maximum Euclidean distance (L2 error) between corresponding lip vertices of the generated and ground truth + meshes for each frame. The metric is defined as: + + .. math:: + \text{LVE} = \frac{1}{N} \sum_{i=1}^{N} \max_{v \in \text{lip}} \|x_{i,v} - \hat{x}_{i,v}\|_2^2 + + where :math:`N` is the number of frames, :math:`x_{i,v}` represents the 3D coordinates of vertex :math:`v` in the + lip region of the ground truth frame :math:`i`, and :math:`\hat{x}_{i,v}` represents the corresponding vertex in + the predicted frame. The metric computes the maximum squared L2 distance between corresponding lip vertices for each + frame and averages across all frames. A lower LVE value indicates better lip synchronization quality. + + Args: + vertices_pred: Predicted vertices tensor of shape (T, V, 3) where T is number of frames, + V is number of vertices, and 3 represents XYZ coordinates + vertices_gt: Ground truth vertices tensor of shape (T', V, 3) where T' can be different from T + mouth_map: List of vertex indices corresponding to the mouth region + validate_args: bool indicating if input arguments and tensors should be validated for correctness. + Set to ``False`` for faster computations. + + Returns: + torch.Tensor: Scalar tensor containing the mean LVE value across all frames + + Raises: + ValueError: + If the number of dimensions of `vertices_pred` or `vertices_gt` is not 3. + If vertex dimensions (V) or coordinate dimensions (3) don't match + If ``mouth_map`` is empty or contains invalid indices + + Example: + >>> import torch + >>> from torchmetrics.functional.multimodal import lip_vertex_error + >>> vertices_pred = torch.randn(10, 100, 3, generator=torch.manual_seed(42)) + >>> vertices_gt = torch.randn(10, 100, 3, generator=torch.manual_seed(43)) + >>> mouth_map = [0, 1, 2, 3, 4] + >>> lip_vertex_error(vertices_pred, vertices_gt, mouth_map) + tensor(12.7688) + + """ + if validate_args: + if vertices_pred.ndim != 3 or vertices_gt.ndim != 3: + raise ValueError( + f"Expected both vertices_pred and vertices_gt to have 3 dimensions but got " + f"{vertices_pred.ndim} and {vertices_gt.ndim} dimensions respectively." + ) + if vertices_pred.shape[1:] != vertices_gt.shape[1:]: + raise ValueError( + f"Expected vertices_pred and vertices_gt to have same vertex and coordinate dimensions but got " + f"shapes {vertices_pred.shape} and {vertices_gt.shape}." + ) + if not mouth_map: + raise ValueError("mouth_map cannot be empty.") + if max(mouth_map) >= vertices_pred.shape[1]: + raise ValueError( + f"mouth_map contains invalid vertex indices. Max index {max(mouth_map)} is larger than " + f"number of vertices {vertices_pred.shape[1]}." + ) + + min_frames = min(vertices_pred.shape[0], vertices_gt.shape[0]) + vertices_pred = vertices_pred[:min_frames] + vertices_gt = vertices_gt[:min_frames] + + diff = vertices_gt[:, mouth_map, :] - vertices_pred[:, mouth_map, :] # Shape: (T, M, 3) + sq_dist = torch.sum(diff**2, dim=-1) # Shape: (T, M) + max_per_frame = torch.max(sq_dist, dim=1).values # Shape: (T,) + return torch.mean(max_per_frame) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..772cb39589595b698e44a1b6ad59e88830ac2079 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/__init__.py @@ -0,0 +1,34 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from torchmetrics.functional.nominal.cramers import cramers_v, cramers_v_matrix +from torchmetrics.functional.nominal.fleiss_kappa import fleiss_kappa +from torchmetrics.functional.nominal.pearson import ( + pearsons_contingency_coefficient, + pearsons_contingency_coefficient_matrix, +) +from torchmetrics.functional.nominal.theils_u import theils_u, theils_u_matrix +from torchmetrics.functional.nominal.tschuprows import tschuprows_t, tschuprows_t_matrix + +__all__ = [ + "cramers_v", + "cramers_v_matrix", + "fleiss_kappa", + "pearsons_contingency_coefficient", + "pearsons_contingency_coefficient_matrix", + "theils_u", + "theils_u_matrix", + "tschuprows_t", + "tschuprows_t_matrix", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/cramers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/cramers.py new file mode 100644 index 0000000000000000000000000000000000000000..33b89b92014604dddf462699aff643556276c1b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/cramers.py @@ -0,0 +1,183 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update +from torchmetrics.functional.nominal.utils import ( + _compute_bias_corrected_values, + _compute_chi_squared, + _drop_empty_rows_and_cols, + _handle_nan_in_data, + _nominal_input_validation, + _unable_to_use_bias_correction_warning, +) + + +def _cramers_v_update( + preds: Tensor, + target: Tensor, + num_classes: int, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + """Compute the bins to update the confusion matrix with for Cramer's V calculation. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data + target: 1D or 2D tensor of categorical (nominal) data + num_classes: Integer specifying the number of classes + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace``` + + Returns: + Non-reduced confusion matrix + + """ + preds = preds.argmax(1) if preds.ndim == 2 else preds + target = target.argmax(1) if target.ndim == 2 else target + preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value) + return _multiclass_confusion_matrix_update(preds, target, num_classes) + + +def _cramers_v_compute(confmat: Tensor, bias_correction: bool) -> Tensor: + """Compute Cramers' V statistic based on a pre-computed confusion matrix. + + Args: + confmat: Confusion matrix for observed data + bias_correction: Indication of whether to use bias correction. + + Returns: + Cramer's V statistic + + """ + confmat = _drop_empty_rows_and_cols(confmat) + cm_sum = confmat.sum() + chi_squared = _compute_chi_squared(confmat, bias_correction) + phi_squared = chi_squared / cm_sum + num_rows, num_cols = confmat.shape + + if bias_correction: + phi_squared_corrected, rows_corrected, cols_corrected = _compute_bias_corrected_values( + phi_squared, num_rows, num_cols, cm_sum + ) + if torch.min(rows_corrected, cols_corrected) == 1: + _unable_to_use_bias_correction_warning(metric_name="Cramer's V") + return torch.tensor(float("nan"), device=confmat.device) + cramers_v_value = torch.sqrt(phi_squared_corrected / torch.min(rows_corrected - 1, cols_corrected - 1)) + else: + cramers_v_value = torch.sqrt(phi_squared / min(num_rows - 1, num_cols - 1)) + return cramers_v_value.clamp(0.0, 1.0) + + +def cramers_v( + preds: Tensor, + target: Tensor, + bias_correction: bool = True, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Cramer's V`_ statistic measuring the association between two categorical (nominal) data series. + + .. math:: + V = \sqrt{\frac{\chi^2 / n}{\min(r - 1, k - 1)}} + + where + + .. math:: + \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}} + + where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j` + represent frequencies of values in ``preds`` and ``target``, respectively. + + Cramer's V is a symmetric coefficient, i.e. :math:`V(preds, target) = V(target, preds)`. + + The output values lies in [0, 1] with 1 meaning the perfect association. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + target: 1D or 2D tensor of categorical (nominal) data + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + bias_correction: Indication of whether to use bias correction. + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Cramer's V statistic + + Example: + >>> from torch import randint, round + >>> from torchmetrics.functional.nominal import cramers_v + >>> preds = randint(0, 4, (100,)) + >>> target = round(preds + torch.randn(100)).clamp(0, 4) + >>> cramers_v(preds, target) + tensor(0.5284) + + """ + _nominal_input_validation(nan_strategy, nan_replace_value) + num_classes = len(torch.cat([preds, target]).unique()) + confmat = _cramers_v_update(preds, target, num_classes, nan_strategy, nan_replace_value) + return _cramers_v_compute(confmat, bias_correction) + + +def cramers_v_matrix( + matrix: Tensor, + bias_correction: bool = True, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Cramer's V`_ statistic between a set of multiple variables. + + This can serve as a convenient tool to compute Cramer's V statistic for analyses of correlation between categorical + variables in your dataset. + + Args: + matrix: A tensor of categorical (nominal) data, where: + - rows represent a number of data points + - columns represent a number of categorical (nominal) features + bias_correction: Indication of whether to use bias correction. + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Cramer's V statistic for a dataset of categorical variables + + Example: + >>> from torch import randint + >>> from torchmetrics.functional.nominal import cramers_v_matrix + >>> matrix = randint(0, 4, (200, 5)) + >>> cramers_v_matrix(matrix) + tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337], + [0.0637, 1.0000, 0.0000, 0.0000, 0.0000], + [0.0000, 0.0000, 1.0000, 0.0000, 0.0649], + [0.0542, 0.0000, 0.0000, 1.0000, 0.1100], + [0.1337, 0.0000, 0.0649, 0.1100, 1.0000]]) + + """ + _nominal_input_validation(nan_strategy, nan_replace_value) + num_variables = matrix.shape[1] + cramers_v_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device) + for i, j in itertools.combinations(range(num_variables), 2): + x, y = matrix[:, i], matrix[:, j] + num_classes = len(torch.cat([x, y]).unique()) + confmat = _cramers_v_update(x, y, num_classes, nan_strategy, nan_replace_value) + cramers_v_matrix_value[i, j] = cramers_v_matrix_value[j, i] = _cramers_v_compute(confmat, bias_correction) + return cramers_v_matrix_value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/fleiss_kappa.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/fleiss_kappa.py new file mode 100644 index 0000000000000000000000000000000000000000..69990f552d80bfb2babb16bfd804b6d78f53fc7d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/fleiss_kappa.py @@ -0,0 +1,99 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from torch import Tensor +from typing_extensions import Literal + + +def _fleiss_kappa_update(ratings: Tensor, mode: Literal["counts", "probs"] = "counts") -> Tensor: + """Updates the counts for fleiss kappa metric. + + Args: + ratings: ratings matrix + mode: whether ratings are provided as counts or probabilities + + """ + if mode == "probs": + if ratings.ndim != 3 or not ratings.is_floating_point(): + raise ValueError( + "If argument ``mode`` is 'probs', ratings must have 3 dimensions with the format" + " [n_samples, n_categories, n_raters] and be floating point." + ) + ratings = ratings.argmax(dim=1) + one_hot = torch.nn.functional.one_hot(ratings, num_classes=ratings.shape[1]).permute(0, 2, 1) + ratings = one_hot.sum(dim=-1) + elif mode == "counts" and (ratings.ndim != 2 or ratings.is_floating_point()): + raise ValueError( + "If argument ``mode`` is `counts`, ratings must have 2 dimensions with the format" + " [n_samples, n_categories] and be none floating point." + ) + return ratings + + +def _fleiss_kappa_compute(counts: Tensor) -> Tensor: + """Computes fleiss kappa from counts matrix. + + Args: + counts: counts matrix of shape [n_samples, n_categories] + + """ + total = counts.shape[0] + num_raters = counts.sum(1).max() + + p_i = counts.sum(dim=0) / (total * num_raters) + p_j = ((counts**2).sum(dim=1) - num_raters) / (num_raters * (num_raters - 1)) + p_bar = p_j.mean() + pe_bar = (p_i**2).sum() + return (p_bar - pe_bar) / (1 - pe_bar + 1e-5) + + +def fleiss_kappa(ratings: Tensor, mode: Literal["counts", "probs"] = "counts") -> Tensor: + r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters. + + .. math:: + \kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}} + + where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean + agreement probability over all raters if they were randomly assigned. If the raters are in complete agreement then + the score 1 is returned, if there is no agreement among the raters (other than what would be expected by chance) + then a score smaller than 0 is returned. + + Args: + ratings: Ratings of shape [n_samples, n_categories] or [n_samples, n_categories, n_raters] depedenent on `mode`. + If `mode` is `counts`, `ratings` must be integer and contain the number of raters that chose each category. + If `mode` is `probs`, `ratings` must be floating point and contain the probability/logits that each rater + chose each category. + mode: Whether `ratings` will be provided as counts or probabilities. + + Example: + >>> # Ratings are provided as counts + >>> from torch import randint + >>> from torchmetrics.functional.nominal import fleiss_kappa + >>> ratings = randint(0, 10, size=(100, 5)).long() # 100 samples, 5 categories, 10 raters + >>> fleiss_kappa(ratings) + tensor(0.0089) + + Example: + >>> # Ratings are provided as probabilities + >>> from torch import randn + >>> from torchmetrics.functional.nominal import fleiss_kappa + >>> ratings = randn(100, 5, 10).softmax(dim=1) # 100 samples, 5 categories, 10 raters + >>> fleiss_kappa(ratings, mode='probs') + tensor(-0.0075) + + """ + if mode not in ["counts", "probs"]: + raise ValueError("Argument ``mode`` must be one of ['counts', 'probs'].") + counts = _fleiss_kappa_update(ratings, mode) + return _fleiss_kappa_compute(counts) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/pearson.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/pearson.py new file mode 100644 index 0000000000000000000000000000000000000000..55fe1681bf754654e863aff3c572ea69837212c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/pearson.py @@ -0,0 +1,174 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update +from torchmetrics.functional.nominal.utils import ( + _compute_chi_squared, + _drop_empty_rows_and_cols, + _handle_nan_in_data, + _nominal_input_validation, +) + + +def _pearsons_contingency_coefficient_update( + preds: Tensor, + target: Tensor, + num_classes: int, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + """Compute the bins to update the confusion matrix with for Pearson's Contingency Coefficient calculation. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data + target: 1D or 2D tensor of categorical (nominal) data + num_classes: Integer specifying the number of classes + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace``` + + Returns: + Non-reduced confusion matrix + + """ + preds = preds.argmax(1) if preds.ndim == 2 else preds + target = target.argmax(1) if target.ndim == 2 else target + preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value) + return _multiclass_confusion_matrix_update(preds, target, num_classes) + + +def _pearsons_contingency_coefficient_compute(confmat: Tensor) -> Tensor: + """Compute Pearson's Contingency Coefficient based on a pre-computed confusion matrix. + + Args: + confmat: Confusion matrix for observed data + + Returns: + Pearson's Contingency Coefficient + + """ + confmat = _drop_empty_rows_and_cols(confmat) + cm_sum = confmat.sum() + chi_squared = _compute_chi_squared(confmat, bias_correction=False) + phi_squared = chi_squared / cm_sum + + tschuprows_t_value = torch.sqrt(phi_squared / (1 + phi_squared)) + return tschuprows_t_value.clamp(0.0, 1.0) + + +def pearsons_contingency_coefficient( + preds: Tensor, + target: Tensor, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Pearson's Contingency Coefficient`_ for measuring the association between two categorical data series. + + .. math:: + Pearson = \sqrt{\frac{\chi^2 / n}{1 + \chi^2 / n}} + + where + + .. math:: + \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}} + + where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j` + represent frequencies of values in ``preds`` and ``target``, respectively. + + Pearson's Contingency Coefficient is a symmetric coefficient, i.e. + :math:`Pearson(preds, target) = Pearson(target, preds)`. + + The output values lies in [0, 1] with 1 meaning the perfect association. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data: + + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + + target: 1D or 2D tensor of categorical (nominal) data: + + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Pearson's Contingency Coefficient + + Example: + >>> from torch import randint, round + >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient + >>> preds = randint(0, 4, (100,)) + >>> target = round(preds + torch.randn(100)).clamp(0, 4) + >>> pearsons_contingency_coefficient(preds, target) + tensor(0.6948) + + """ + _nominal_input_validation(nan_strategy, nan_replace_value) + num_classes = len(torch.cat([preds, target]).unique()) + confmat = _pearsons_contingency_coefficient_update(preds, target, num_classes, nan_strategy, nan_replace_value) + return _pearsons_contingency_coefficient_compute(confmat) + + +def pearsons_contingency_coefficient_matrix( + matrix: Tensor, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Pearson's Contingency Coefficient`_ statistic between a set of multiple variables. + + This can serve as a convenient tool to compute Pearson's Contingency Coefficient for analyses + of correlation between categorical variables in your dataset. + + Args: + matrix: A tensor of categorical (nominal) data, where: + + - rows represent a number of data points + - columns represent a number of categorical (nominal) features + + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Pearson's Contingency Coefficient statistic for a dataset of categorical variables + + Example: + >>> from torch import randint + >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient_matrix + >>> matrix = randint(0, 4, (200, 5)) + >>> pearsons_contingency_coefficient_matrix(matrix) + tensor([[1.0000, 0.2326, 0.1959, 0.2262, 0.2989], + [0.2326, 1.0000, 0.1386, 0.1895, 0.1329], + [0.1959, 0.1386, 1.0000, 0.1840, 0.2335], + [0.2262, 0.1895, 0.1840, 1.0000, 0.2737], + [0.2989, 0.1329, 0.2335, 0.2737, 1.0000]]) + + """ + _nominal_input_validation(nan_strategy, nan_replace_value) + num_variables = matrix.shape[1] + pearsons_cont_coef_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device) + for i, j in itertools.combinations(range(num_variables), 2): + x, y = matrix[:, i], matrix[:, j] + num_classes = len(torch.cat([x, y]).unique()) + confmat = _pearsons_contingency_coefficient_update(x, y, num_classes, nan_strategy, nan_replace_value) + val = _pearsons_contingency_coefficient_compute(confmat) + pearsons_cont_coef_matrix_value[i, j] = pearsons_cont_coef_matrix_value[j, i] = val + return pearsons_cont_coef_matrix_value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/theils_u.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/theils_u.py new file mode 100644 index 0000000000000000000000000000000000000000..f356dbfd03d728a5cc69b8c4dca69162ebcdd791 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/theils_u.py @@ -0,0 +1,195 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update +from torchmetrics.functional.nominal.utils import ( + _drop_empty_rows_and_cols, + _handle_nan_in_data, + _nominal_input_validation, +) + + +def _conditional_entropy_compute(confmat: Tensor) -> Tensor: + r"""Compute Conditional Entropy Statistic based on a pre-computed confusion matrix. + + .. math:: + H(X|Y) = \sum_{x, y ~ (X, Y)} p(x, y)\frac{p(y)}{p(x, y)} + + Args: + confmat: Confusion matrix for observed data + + Returns: + Conditional Entropy Value + + """ + confmat = _drop_empty_rows_and_cols(confmat) + total_occurrences = confmat.sum() + # iterate over all i, j combinations + p_xy_m = confmat / total_occurrences + # get p_y by summing over x dim (=1) + p_y = confmat.sum(1) / total_occurrences + # repeat over rows (shape = p_xy_m.shape[1]) for tensor multiplication + p_y_m = p_y.unsqueeze(1).repeat(1, p_xy_m.shape[1]) + + # entropy calculated as p_xy * log (p_xy / p_y) + return torch.nansum(p_xy_m * torch.log(p_y_m / p_xy_m)) + + +def _theils_u_update( + preds: Tensor, + target: Tensor, + num_classes: int, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + """Compute the bins to update the confusion matrix with for Theil's U calculation. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data + target: 1D or 2D tensor of categorical (nominal) data + num_classes: Integer specifying the number of classes + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace``` + + Returns: + Non-reduced confusion matrix + + """ + preds = preds.argmax(1) if preds.ndim == 2 else preds + target = target.argmax(1) if target.ndim == 2 else target + preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value) + return _multiclass_confusion_matrix_update(preds, target, num_classes) + + +def _theils_u_compute(confmat: Tensor) -> Tensor: + """Compute Theil's U statistic based on a pre-computed confusion matrix. + + Args: + confmat: Confusion matrix for observed data + + Returns: + Theil's U statistic + + """ + confmat = _drop_empty_rows_and_cols(confmat) + + # compute conditional entropy + s_xy = _conditional_entropy_compute(confmat) + + # compute H(x) + total_occurrences = confmat.sum() + p_x = confmat.sum(0) / total_occurrences + s_x = -torch.sum(p_x * torch.log(p_x)) + + # compute u statistic + if s_x == 0: + return torch.tensor(0, device=confmat.device) + + return (s_x - s_xy) / s_x + + +def theils_u( + preds: Tensor, + target: Tensor, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Theils Uncertainty coefficient`_ statistic measuring the association between two nominal data series. + + .. math:: + U(X|Y) = \frac{H(X) - H(X|Y)}{H(X)} + + where :math:`H(X)` is entropy of variable :math:`X` while :math:`H(X|Y)` is the conditional entropy of :math:`X` + given :math:`Y`. + + Theils's U is an asymmetric coefficient, i.e. :math:`TheilsU(preds, target) \neq TheilsU(target, preds)`. + + The output values lies in [0, 1]. 0 means y has no information about x while value 1 means y has complete + information about x. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + target: 1D or 2D tensor of categorical (nominal) data + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Tensor containing Theil's U statistic + + Example: + >>> from torch import randint + >>> from torchmetrics.functional.nominal import theils_u + >>> preds = randint(10, (10,)) + >>> target = randint(10, (10,)) + >>> theils_u(preds, target) + tensor(0.8530) + + """ + num_classes = len(torch.cat([preds, target]).unique()) + confmat = _theils_u_update(preds, target, num_classes, nan_strategy, nan_replace_value) + return _theils_u_compute(confmat) + + +def theils_u_matrix( + matrix: Tensor, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Theil's U`_ statistic between a set of multiple variables. + + This can serve as a convenient tool to compute Theil's U statistic for analyses of correlation between categorical + variables in your dataset. + + Args: + matrix: A tensor of categorical (nominal) data, where: + - rows represent a number of data points + - columns represent a number of categorical (nominal) features + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Theil's U statistic for a dataset of categorical variables + + Example: + >>> from torch import randint + >>> from torchmetrics.functional.nominal import theils_u_matrix + >>> matrix = randint(0, 4, (200, 5)) + >>> theils_u_matrix(matrix) + tensor([[1.0000, 0.0202, 0.0142, 0.0196, 0.0353], + [0.0202, 1.0000, 0.0070, 0.0136, 0.0065], + [0.0143, 0.0070, 1.0000, 0.0125, 0.0206], + [0.0198, 0.0137, 0.0125, 1.0000, 0.0312], + [0.0352, 0.0065, 0.0204, 0.0308, 1.0000]]) + + """ + _nominal_input_validation(nan_strategy, nan_replace_value) + num_variables = matrix.shape[1] + theils_u_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device) + for i, j in itertools.combinations(range(num_variables), 2): + x, y = matrix[:, i], matrix[:, j] + num_classes = len(torch.cat([x, y]).unique()) + confmat = _theils_u_update(x, y, num_classes, nan_strategy, nan_replace_value) + theils_u_matrix_value[i, j] = _theils_u_compute(confmat) + theils_u_matrix_value[j, i] = _theils_u_compute(confmat.T) + return theils_u_matrix_value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/tschuprows.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/tschuprows.py new file mode 100644 index 0000000000000000000000000000000000000000..22d256d33d12c288aca7627e51c54b72b9594ff3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/tschuprows.py @@ -0,0 +1,193 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update +from torchmetrics.functional.nominal.utils import ( + _compute_bias_corrected_values, + _compute_chi_squared, + _drop_empty_rows_and_cols, + _handle_nan_in_data, + _nominal_input_validation, + _unable_to_use_bias_correction_warning, +) + + +def _tschuprows_t_update( + preds: Tensor, + target: Tensor, + num_classes: int, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + """Compute the bins to update the confusion matrix with for Tschuprow's T calculation. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data + target: 1D or 2D tensor of categorical (nominal) data + num_classes: Integer specifying the number of classes + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace``` + + Returns: + Non-reduced confusion matrix + + """ + preds = preds.argmax(1) if preds.ndim == 2 else preds + target = target.argmax(1) if target.ndim == 2 else target + preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value) + return _multiclass_confusion_matrix_update(preds, target, num_classes) + + +def _tschuprows_t_compute(confmat: Tensor, bias_correction: bool) -> Tensor: + """Compute Tschuprow's T statistic based on a pre-computed confusion matrix. + + Args: + confmat: Confusion matrix for observed data + bias_correction: Indication of whether to use bias correction. + + Returns: + Tschuprow's T statistic + + """ + confmat = _drop_empty_rows_and_cols(confmat) + cm_sum = confmat.sum() + chi_squared = _compute_chi_squared(confmat, bias_correction) + phi_squared = chi_squared / cm_sum + num_rows, num_cols = confmat.shape + + if bias_correction: + phi_squared_corrected, rows_corrected, cols_corrected = _compute_bias_corrected_values( + phi_squared, num_rows, num_cols, cm_sum + ) + if torch.min(rows_corrected, cols_corrected) == 1: + _unable_to_use_bias_correction_warning(metric_name="Tschuprow's T") + return torch.tensor(float("nan"), device=confmat.device) + tschuprows_t_value = torch.sqrt(phi_squared_corrected / torch.sqrt((rows_corrected - 1) * (cols_corrected - 1))) + else: + n_rows_tensor = torch.tensor(num_rows, device=phi_squared.device) + n_cols_tensor = torch.tensor(num_cols, device=phi_squared.device) + tschuprows_t_value = torch.sqrt(phi_squared / torch.sqrt((n_rows_tensor - 1) * (n_cols_tensor - 1))) + return tschuprows_t_value.clamp(0.0, 1.0) + + +def tschuprows_t( + preds: Tensor, + target: Tensor, + bias_correction: bool = True, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Tschuprow's T`_ statistic measuring the association between two categorical (nominal) data series. + + .. math:: + T = \sqrt{\frac{\chi^2 / n}{\sqrt{(r - 1) * (k - 1)}}} + + where + + .. math:: + \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}} + + where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j` + represent frequencies of values in ``preds`` and ``target``, respectively. + + Tschuprow's T is a symmetric coefficient, i.e. :math:`T(preds, target) = T(target, preds)`. + + The output values lies in [0, 1] with 1 meaning the perfect association. + + Args: + preds: 1D or 2D tensor of categorical (nominal) data: + + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + + target: 1D or 2D tensor of categorical (nominal) data: + + - 1D shape: (batch_size,) + - 2D shape: (batch_size, num_classes) + + bias_correction: Indication of whether to use bias correction. + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Tschuprow's T statistic + + Example: + >>> from torch import randint, round + >>> from torchmetrics.functional.nominal import tschuprows_t + >>> preds = randint(0, 4, (100,)) + >>> target = round(preds + torch.randn(100)).clamp(0, 4) + >>> tschuprows_t(preds, target) + tensor(0.4930) + + """ + _nominal_input_validation(nan_strategy, nan_replace_value) + num_classes = len(torch.cat([preds, target]).unique()) + confmat = _tschuprows_t_update(preds, target, num_classes, nan_strategy, nan_replace_value) + return _tschuprows_t_compute(confmat, bias_correction) + + +def tschuprows_t_matrix( + matrix: Tensor, + bias_correction: bool = True, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> Tensor: + r"""Compute `Tschuprow's T`_ statistic between a set of multiple variables. + + This can serve as a convenient tool to compute Tschuprow's T statistic for analyses of correlation between + categorical variables in your dataset. + + Args: + matrix: A tensor of categorical (nominal) data, where: + + - rows represent a number of data points + - columns represent a number of categorical (nominal) features + + bias_correction: Indication of whether to use bias correction. + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + + Returns: + Tschuprow's T statistic for a dataset of categorical variables + + Example: + >>> from torch import randint + >>> from torchmetrics.functional.nominal import tschuprows_t_matrix + >>> matrix = randint(0, 4, (200, 5)) + >>> tschuprows_t_matrix(matrix) + tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337], + [0.0637, 1.0000, 0.0000, 0.0000, 0.0000], + [0.0000, 0.0000, 1.0000, 0.0000, 0.0649], + [0.0542, 0.0000, 0.0000, 1.0000, 0.1100], + [0.1337, 0.0000, 0.0649, 0.1100, 1.0000]]) + + """ + _nominal_input_validation(nan_strategy, nan_replace_value) + num_variables = matrix.shape[1] + tschuprows_t_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device) + for i, j in itertools.combinations(range(num_variables), 2): + x, y = matrix[:, i], matrix[:, j] + num_classes = len(torch.cat([x, y]).unique()) + confmat = _tschuprows_t_update(x, y, num_classes, nan_strategy, nan_replace_value) + tschuprows_t_matrix_value[i, j] = tschuprows_t_matrix_value[j, i] = _tschuprows_t_compute( + confmat, bias_correction + ) + return tschuprows_t_matrix_value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8dd8dc4afdb7ef2028170fd74c3b289fa311d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/utils.py @@ -0,0 +1,146 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.utilities.prints import rank_zero_warn + + +def _nominal_input_validation(nan_strategy: str, nan_replace_value: Optional[float]) -> None: + if nan_strategy not in ["replace", "drop"]: + raise ValueError( + f"Argument `nan_strategy` is expected to be one of `['replace', 'drop']`, but got {nan_strategy}" + ) + if nan_strategy == "replace" and not isinstance(nan_replace_value, (float, int)): + raise ValueError( + "Argument `nan_replace` is expected to be of a type `int` or `float` when `nan_strategy = 'replace`, " + f"but got {nan_replace_value}" + ) + + +def _compute_expected_freqs(confmat: Tensor) -> Tensor: + """Compute the expected frequenceis from the provided confusion matrix.""" + margin_sum_rows, margin_sum_cols = confmat.sum(1), confmat.sum(0) + return torch.einsum("r, c -> rc", margin_sum_rows, margin_sum_cols) / confmat.sum() + + +def _compute_chi_squared(confmat: Tensor, bias_correction: bool) -> Tensor: + """Chi-square test of independenc of variables in a confusion matrix table. + + Adapted from: https://github.com/scipy/scipy/blob/v1.9.2/scipy/stats/contingency.py. + + """ + expected_freqs = _compute_expected_freqs(confmat) + # Get degrees of freedom + df = expected_freqs.numel() - sum(expected_freqs.shape) + expected_freqs.ndim - 1 + if df == 0: + return torch.tensor(0.0, device=confmat.device) + + if df == 1 and bias_correction: + diff = expected_freqs - confmat + direction = diff.sign() + confmat += direction * torch.minimum(0.5 * torch.ones_like(direction), direction.abs()) + + return torch.sum((confmat - expected_freqs) ** 2 / expected_freqs) + + +def _drop_empty_rows_and_cols(confmat: Tensor) -> Tensor: + """Drop all rows and columns containing only zeros. + + Example: + >>> from torch import randint + >>> from torchmetrics.functional.nominal.utils import _drop_empty_rows_and_cols + >>> matrix = randint(10, size=(4, 3)) + >>> matrix[1, :] = matrix[:, 1] = 0 + >>> matrix + tensor([[2, 0, 6], + [0, 0, 0], + [0, 0, 0], + [3, 0, 4]]) + >>> _drop_empty_rows_and_cols(matrix) + tensor([[2, 6], + [3, 4]]) + + """ + confmat = confmat[confmat.sum(1) != 0] + return confmat[:, confmat.sum(0) != 0] + + +def _compute_phi_squared_corrected( + phi_squared: Tensor, + num_rows: int, + num_cols: int, + confmat_sum: Tensor, +) -> Tensor: + """Compute bias-corrected Phi Squared.""" + return torch.max( + torch.tensor(0.0, device=phi_squared.device), + phi_squared - ((num_rows - 1) * (num_cols - 1)) / (confmat_sum - 1), + ) + + +def _compute_rows_and_cols_corrected(num_rows: int, num_cols: int, confmat_sum: Tensor) -> tuple[Tensor, Tensor]: + """Compute bias-corrected number of rows and columns.""" + rows_corrected = num_rows - (num_rows - 1) ** 2 / (confmat_sum - 1) + cols_corrected = num_cols - (num_cols - 1) ** 2 / (confmat_sum - 1) + return rows_corrected, cols_corrected + + +def _compute_bias_corrected_values( + phi_squared: Tensor, num_rows: int, num_cols: int, confmat_sum: Tensor +) -> tuple[Tensor, Tensor, Tensor]: + """Compute bias-corrected Phi Squared and number of rows and columns.""" + phi_squared_corrected = _compute_phi_squared_corrected(phi_squared, num_rows, num_cols, confmat_sum) + rows_corrected, cols_corrected = _compute_rows_and_cols_corrected(num_rows, num_cols, confmat_sum) + return phi_squared_corrected, rows_corrected, cols_corrected + + +def _handle_nan_in_data( + preds: Tensor, + target: Tensor, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, +) -> tuple[Tensor, Tensor]: + """Handle ``NaN`` values in input data. + + If ``nan_strategy = 'replace'``, all ``NaN`` values are replaced with ``nan_replace_value``. + If ``nan_strategy = 'drop'``, all rows containing ``NaN`` in any of two vectors are dropped. + + Args: + preds: 1D tensor of categorical (nominal) data + target: 1D tensor of categorical (nominal) data + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace``` + + Returns: + Updated ``preds`` and ``target`` tensors which contain no ``Nan`` + + Raises: + ValueError: If ``nan_strategy`` is not from ``['replace', 'drop']``. + ValueError: If ``nan_strategy = replace`` and ``nan_replace_value`` is not of a type ``int`` or ``float``. + + """ + if nan_strategy == "replace": + return preds.nan_to_num(nan_replace_value), target.nan_to_num(nan_replace_value) + rows_contain_nan = torch.logical_or(preds.isnan(), target.isnan()) + return preds[~rows_contain_nan], target[~rows_contain_nan] + + +def _unable_to_use_bias_correction_warning(metric_name: str) -> None: + rank_zero_warn( + f"Unable to compute {metric_name} using bias correction. Please consider to set `bias_correction=False`." + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c226169521d6a2ea8b3ea607f05e304b3b4bf99f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/__init__.py @@ -0,0 +1,26 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.functional.pairwise.cosine import pairwise_cosine_similarity +from torchmetrics.functional.pairwise.euclidean import pairwise_euclidean_distance +from torchmetrics.functional.pairwise.linear import pairwise_linear_similarity +from torchmetrics.functional.pairwise.manhattan import pairwise_manhattan_distance +from torchmetrics.functional.pairwise.minkowski import pairwise_minkowski_distance + +__all__ = [ + "pairwise_cosine_similarity", + "pairwise_euclidean_distance", + "pairwise_linear_similarity", + "pairwise_manhattan_distance", + "pairwise_minkowski_distance", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/cosine.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/cosine.py new file mode 100644 index 0000000000000000000000000000000000000000..246b9adf5af05c08f778431a2a65d077768467c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/cosine.py @@ -0,0 +1,91 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix +from torchmetrics.utilities.compute import _safe_matmul + + +def _pairwise_cosine_similarity_update( + x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None +) -> Tensor: + """Calculate the pairwise cosine similarity matrix. + + Args: + x: tensor of shape ``[N,d]`` + y: tensor of shape ``[M,d]`` + zero_diagonal: determines if the diagonal of the distance matrix should be set to zero + + """ + x, y, zero_diagonal = _check_input(x, y, zero_diagonal) + + norm = torch.norm(x, p=2, dim=1) + x = x / norm.unsqueeze(1) + norm = torch.norm(y, p=2, dim=1) + y = y / norm.unsqueeze(1) + + distance = _safe_matmul(x, y) + if zero_diagonal: + distance.fill_diagonal_(0) + return distance + + +def pairwise_cosine_similarity( + x: Tensor, + y: Optional[Tensor] = None, + reduction: Literal["mean", "sum", "none", None] = None, + zero_diagonal: Optional[bool] = None, +) -> Tensor: + r"""Calculate pairwise cosine similarity. + + .. math:: + s_{cos}(x,y) = \frac{}{||x|| \cdot ||y||} + = \frac{\sum_{d=1}^D x_d \cdot y_d }{\sqrt{\sum_{d=1}^D x_i^2} \cdot \sqrt{\sum_{d=1}^D y_i^2}} + + If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise + between the rows of :math:`x` and :math:`y`. + If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`. + + Args: + x: Tensor with shape ``[N, d]`` + y: Tensor with shape ``[M, d]``, optional + reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'` + (applied along column dimension) or `'none'`, `None` for no reduction + zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only :math:`x` is given + this defaults to ``True`` else if :math:`y` is also given it defaults to ``False`` + + Returns: + A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix + + Example: + >>> import torch + >>> from torchmetrics.functional.pairwise import pairwise_cosine_similarity + >>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32) + >>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32) + >>> pairwise_cosine_similarity(x, y) + tensor([[0.5547, 0.8682], + [0.5145, 0.8437], + [0.5300, 0.8533]]) + >>> pairwise_cosine_similarity(x) + tensor([[0.0000, 0.9989, 0.9996], + [0.9989, 0.0000, 0.9998], + [0.9996, 0.9998, 0.0000]]) + + """ + distance = _pairwise_cosine_similarity_update(x, y, zero_diagonal) + return _reduce_distance_matrix(distance, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/euclidean.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/euclidean.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc1e4b5b24a4042eaf99d844fea1d01e8694586 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/euclidean.py @@ -0,0 +1,89 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix + + +def _pairwise_euclidean_distance_update( + x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None +) -> Tensor: + """Calculate the pairwise euclidean distance matrix. + + Args: + x: tensor of shape ``[N,d]`` + y: tensor of shape ``[M,d]`` + zero_diagonal: determines if the diagonal of the distance matrix should be set to zero + + """ + x, y, zero_diagonal = _check_input(x, y, zero_diagonal) + # upcast to float64 to prevent precision issues + _orig_dtype = x.dtype + x = x.to(torch.float64) + y = y.to(torch.float64) + x_norm = (x * x).sum(dim=1, keepdim=True) + y_norm = (y * y).sum(dim=1) + distance = (x_norm + y_norm - 2 * x.mm(y.T)).to(_orig_dtype) + if zero_diagonal: + distance.fill_diagonal_(0) + return distance.sqrt() + + +def pairwise_euclidean_distance( + x: Tensor, + y: Optional[Tensor] = None, + reduction: Literal["mean", "sum", "none", None] = None, + zero_diagonal: Optional[bool] = None, +) -> Tensor: + r"""Calculate pairwise euclidean distances. + + .. math:: + d_{euc}(x,y) = ||x - y||_2 = \sqrt{\sum_{d=1}^D (x_d - y_d)^2} + + If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between + the rows of :math:`x` and :math:`y`. + If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`. + + Args: + x: Tensor with shape ``[N, d]`` + y: Tensor with shape ``[M, d]``, optional + reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'` + (applied along column dimension) or `'none'`, `None` for no reduction + zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given + this defaults to `True` else if `y` is also given it defaults to `False` + + Returns: + A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix + + Example: + >>> import torch + >>> from torchmetrics.functional.pairwise import pairwise_euclidean_distance + >>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32) + >>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32) + >>> pairwise_euclidean_distance(x, y) + tensor([[3.1623, 2.0000], + [5.3852, 4.1231], + [8.9443, 7.6158]]) + >>> pairwise_euclidean_distance(x) + tensor([[0.0000, 2.2361, 5.8310], + [2.2361, 0.0000, 3.6056], + [5.8310, 3.6056, 0.0000]]) + + """ + distance = _pairwise_euclidean_distance_update(x, y, zero_diagonal) + return _reduce_distance_matrix(distance, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/helpers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..703b5ddb083004a29b1178d6d53342adc326b340 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/helpers.py @@ -0,0 +1,60 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +from torch import Tensor + + +def _check_input( + x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None +) -> tuple[Tensor, Tensor, bool]: + """Check that input has the right dimensionality and sets the ``zero_diagonal`` argument if user has not set it. + + Args: + x: tensor of shape ``[N,d]`` + y: if provided, a tensor of shape ``[M,d]`` + zero_diagonal: determines if the diagonal of the distance matrix should be set to zero + + """ + if x.ndim != 2: + raise ValueError(f"Expected argument `x` to be a 2D tensor of shape `[N, d]` but got {x.shape}") + + if y is not None: + if y.ndim != 2 or y.shape[1] != x.shape[1]: + raise ValueError( + "Expected argument `y` to be a 2D tensor of shape `[M, d]` where" + " `d` should be same as the last dimension of `x`" + ) + zero_diagonal = False if zero_diagonal is None else zero_diagonal + else: + y = x.clone() + zero_diagonal = True if zero_diagonal is None else zero_diagonal + return x, y, zero_diagonal + + +def _reduce_distance_matrix(distmat: Tensor, reduction: Optional[str] = None) -> Tensor: + """Reduction of distance matrix. + + Args: + distmat: a ``[N,M]`` matrix + reduction: string determining how to reduce along last dimension + + """ + if reduction == "mean": + return distmat.mean(dim=-1) + if reduction == "sum": + return distmat.sum(dim=-1) + if reduction is None or reduction == "none": + return distmat + raise ValueError(f"Expected reduction to be one of `['mean', 'sum', None]` but got {reduction}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/linear.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..67bebbae1eaa2967738cc1d6bd8fc38cbacb2e76 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/linear.py @@ -0,0 +1,84 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix +from torchmetrics.utilities.compute import _safe_matmul + + +def _pairwise_linear_similarity_update( + x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None +) -> Tensor: + """Calculate the pairwise linear similarity matrix. + + Args: + x: tensor of shape ``[N,d]`` + y: tensor of shape ``[M,d]`` + zero_diagonal: determines if the diagonal of the distance matrix should be set to zero + + """ + x, y, zero_diagonal = _check_input(x, y, zero_diagonal) + + distance = _safe_matmul(x, y) + if zero_diagonal: + distance.fill_diagonal_(0) + return distance + + +def pairwise_linear_similarity( + x: Tensor, + y: Optional[Tensor] = None, + reduction: Literal["mean", "sum", "none", None] = None, + zero_diagonal: Optional[bool] = None, +) -> Tensor: + r"""Calculate pairwise linear similarity. + + .. math:: + s_{lin}(x,y) = = \sum_{d=1}^D x_d \cdot y_d + + If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between + the rows of :math:`x` and :math:`y`. + If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`. + + Args: + x: Tensor with shape ``[N, d]`` + y: Tensor with shape ``[M, d]``, optional + reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'` + (applied along column dimension) or `'none'`, `None` for no reduction + zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given + this defaults to `True` else if `y` is also given it defaults to `False` + + Returns: + A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix + + Example: + >>> import torch + >>> from torchmetrics.functional.pairwise import pairwise_linear_similarity + >>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32) + >>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32) + >>> pairwise_linear_similarity(x, y) + tensor([[ 2., 7.], + [ 3., 11.], + [ 5., 18.]]) + >>> pairwise_linear_similarity(x) + tensor([[ 0., 21., 34.], + [21., 0., 55.], + [34., 55., 0.]]) + + """ + distance = _pairwise_linear_similarity_update(x, y, zero_diagonal) + return _reduce_distance_matrix(distance, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/manhattan.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/manhattan.py new file mode 100644 index 0000000000000000000000000000000000000000..3eda0c07a3820b56d92bc6497e667a05f63233a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/manhattan.py @@ -0,0 +1,83 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix + + +def _pairwise_manhattan_distance_update( + x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None +) -> Tensor: + """Calculate the pairwise manhattan similarity matrix. + + Args: + x: tensor of shape ``[N,d]`` + y: if provided, a tensor of shape ``[M,d]`` + zero_diagonal: determines if the diagonal of the distance matrix should be set to zero + + """ + x, y, zero_diagonal = _check_input(x, y, zero_diagonal) + + distance = (x.unsqueeze(1) - y.unsqueeze(0).repeat(x.shape[0], 1, 1)).abs().sum(dim=-1) + if zero_diagonal: + distance.fill_diagonal_(0) + return distance + + +def pairwise_manhattan_distance( + x: Tensor, + y: Optional[Tensor] = None, + reduction: Literal["mean", "sum", "none", None] = None, + zero_diagonal: Optional[bool] = None, +) -> Tensor: + r"""Calculate pairwise manhattan distance. + + .. math:: + d_{man}(x,y) = ||x-y||_1 = \sum_{d=1}^D |x_d - y_d| + + If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between + the rows of :math:`x` and :math:`y`. + If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`. + + Args: + x: Tensor with shape ``[N, d]`` + y: Tensor with shape ``[M, d]``, optional + reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'` + (applied along column dimension) or `'none'`, `None` for no reduction + zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given + this defaults to `True` else if `y` is also given it defaults to `False` + + Returns: + A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix + + Example: + >>> import torch + >>> from torchmetrics.functional.pairwise import pairwise_manhattan_distance + >>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32) + >>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32) + >>> pairwise_manhattan_distance(x, y) + tensor([[ 4., 2.], + [ 7., 5.], + [12., 10.]]) + >>> pairwise_manhattan_distance(x) + tensor([[0., 3., 8.], + [3., 0., 5.], + [8., 5., 0.]]) + + """ + distance = _pairwise_manhattan_distance_update(x, y, zero_diagonal) + return _reduce_distance_matrix(distance, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/minkowski.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/minkowski.py new file mode 100644 index 0000000000000000000000000000000000000000..298cedd14862511c9304699f2a531cf19d8a60ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/minkowski.py @@ -0,0 +1,93 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix +from torchmetrics.utilities.exceptions import TorchMetricsUserError + + +def _pairwise_minkowski_distance_update( + x: Tensor, y: Optional[Tensor] = None, exponent: float = 2, zero_diagonal: Optional[bool] = None +) -> Tensor: + """Calculate the pairwise minkowski distance matrix. + + Args: + x: tensor of shape ``[N,d]`` + y: tensor of shape ``[M,d]`` + exponent: int or float larger than 1, exponent to which the difference between preds and target is to be raised + zero_diagonal: determines if the diagonal of the distance matrix should be set to zero + + """ + x, y, zero_diagonal = _check_input(x, y, zero_diagonal) + if not (isinstance(exponent, (float, int)) and exponent >= 1): + raise TorchMetricsUserError(f"Argument ``p`` must be a float or int greater than 1, but got {exponent}") + # upcast to float64 to prevent precision issues + _orig_dtype = x.dtype + x = x.to(torch.float64) + y = y.to(torch.float64) + distance = (x.unsqueeze(1) - y.unsqueeze(0)).abs().pow(exponent).sum(-1).pow(1.0 / exponent) + if zero_diagonal: + distance.fill_diagonal_(0) + return distance.to(_orig_dtype) + + +def pairwise_minkowski_distance( + x: Tensor, + y: Optional[Tensor] = None, + exponent: float = 2, + reduction: Literal["mean", "sum", "none", None] = None, + zero_diagonal: Optional[bool] = None, +) -> Tensor: + r"""Calculate pairwise minkowski distances. + + .. math:: + d_{minkowski}(x,y,p) = ||x - y||_p = \sqrt[p]{\sum_{d=1}^D (x_d - y_d)^p} + + If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between the rows of + :math:`x` and :math:`y`. If only :math:`x` is passed in, the calculation will be performed between the rows + of :math:`x`. + + Args: + x: Tensor with shape ``[N, d]`` + y: Tensor with shape ``[M, d]``, optional + exponent: int or float larger than 1, exponent to which the difference between preds and target is to be raised + reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'` + (applied along column dimension) or `'none'`, `None` for no reduction + zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given + this defaults to `True` else if `y` is also given it defaults to `False` + + Returns: + A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix + + Example: + >>> import torch + >>> from torchmetrics.functional.pairwise import pairwise_minkowski_distance + >>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32) + >>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32) + >>> pairwise_minkowski_distance(x, y, exponent=4) + tensor([[3.0092, 2.0000], + [5.0317, 4.0039], + [8.1222, 7.0583]]) + >>> pairwise_minkowski_distance(x, exponent=4) + tensor([[0.0000, 2.0305, 5.1547], + [2.0305, 0.0000, 3.1383], + [5.1547, 3.1383, 0.0000]]) + + """ + distance = _pairwise_minkowski_distance_update(x, y, exponent, zero_diagonal) + return _reduce_distance_matrix(distance, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9727d4fdd8fce050a9f59d698c8fc41ec1bfa569 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/__init__.py @@ -0,0 +1,61 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.functional.regression.concordance import concordance_corrcoef +from torchmetrics.functional.regression.cosine_similarity import cosine_similarity +from torchmetrics.functional.regression.crps import continuous_ranked_probability_score +from torchmetrics.functional.regression.csi import critical_success_index +from torchmetrics.functional.regression.explained_variance import explained_variance +from torchmetrics.functional.regression.js_divergence import jensen_shannon_divergence +from torchmetrics.functional.regression.kendall import kendall_rank_corrcoef +from torchmetrics.functional.regression.kl_divergence import kl_divergence +from torchmetrics.functional.regression.log_cosh import log_cosh_error +from torchmetrics.functional.regression.log_mse import mean_squared_log_error +from torchmetrics.functional.regression.mae import mean_absolute_error +from torchmetrics.functional.regression.mape import mean_absolute_percentage_error +from torchmetrics.functional.regression.minkowski import minkowski_distance +from torchmetrics.functional.regression.mse import mean_squared_error +from torchmetrics.functional.regression.nrmse import normalized_root_mean_squared_error +from torchmetrics.functional.regression.pearson import pearson_corrcoef +from torchmetrics.functional.regression.r2 import r2_score +from torchmetrics.functional.regression.rse import relative_squared_error +from torchmetrics.functional.regression.spearman import spearman_corrcoef +from torchmetrics.functional.regression.symmetric_mape import symmetric_mean_absolute_percentage_error +from torchmetrics.functional.regression.tweedie_deviance import tweedie_deviance_score +from torchmetrics.functional.regression.wmape import weighted_mean_absolute_percentage_error + +__all__ = [ + "concordance_corrcoef", + "continuous_ranked_probability_score", + "cosine_similarity", + "critical_success_index", + "explained_variance", + "jensen_shannon_divergence", + "kendall_rank_corrcoef", + "kl_divergence", + "log_cosh_error", + "mean_absolute_error", + "mean_absolute_percentage_error", + "mean_absolute_percentage_error", + "mean_squared_error", + "mean_squared_log_error", + "minkowski_distance", + "normalized_root_mean_squared_error", + "pearson_corrcoef", + "r2_score", + "relative_squared_error", + "spearman_corrcoef", + "symmetric_mean_absolute_percentage_error", + "tweedie_deviance_score", + "weighted_mean_absolute_percentage_error", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/concordance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/concordance.py new file mode 100644 index 0000000000000000000000000000000000000000..42b32bbe02f47f1ed4974fbe811b1bc77bbb3b81 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/concordance.py @@ -0,0 +1,83 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from torch import Tensor + +from torchmetrics.functional.regression.pearson import _pearson_corrcoef_compute, _pearson_corrcoef_update + + +def _concordance_corrcoef_compute( + max_abs_dev_x: Tensor, + max_abs_dev_y: Tensor, + mean_x: Tensor, + mean_y: Tensor, + var_x: Tensor, + var_y: Tensor, + corr_xy: Tensor, + nb: Tensor, +) -> Tensor: + """Compute the final concordance correlation coefficient based on accumulated statistics.""" + pearson = _pearson_corrcoef_compute(max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb) + var_x = var_x / (nb - 1) + var_y = var_y / (nb - 1) + return 2.0 * pearson * var_x.sqrt() * var_y.sqrt() / (var_x + var_y + (mean_x - mean_y) ** 2) + + +def concordance_corrcoef(preds: Tensor, target: Tensor) -> Tensor: + r"""Compute concordance correlation coefficient that measures the agreement between two variables. + + .. math:: + \rho_c = \frac{2 \rho \sigma_x \sigma_y}{\sigma_x^2 + \sigma_y^2 + (\mu_x - \mu_y)^2} + + where :math:`\mu_x, \mu_y` is the means for the two variables, :math:`\sigma_x^2, \sigma_y^2` are the corresponding + variances and \rho is the pearson correlation coefficient between the two variables. + + Args: + preds: estimated scores + target: ground truth scores + + Example (single output regression): + >>> from torchmetrics.functional.regression import concordance_corrcoef + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> concordance_corrcoef(preds, target) + tensor([0.9777]) + + Example (multi output regression): + >>> from torchmetrics.functional.regression import concordance_corrcoef + >>> target = torch.tensor([[3, -0.5], [2, 7]]) + >>> preds = torch.tensor([[2.5, 0.0], [2, 8]]) + >>> concordance_corrcoef(preds, target) + tensor([0.7273, 0.9887]) + + """ + d = preds.shape[1] if preds.ndim == 2 else 1 + _temp = torch.zeros(d, dtype=preds.dtype, device=preds.device) + mean_x, mean_y, var_x = _temp.clone(), _temp.clone(), _temp.clone() + var_y, corr_xy, nb = _temp.clone(), _temp.clone(), _temp.clone() + max_abs_dev_x, max_abs_dev_y = _temp.clone(), _temp.clone() + mean_x, mean_y, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb = _pearson_corrcoef_update( + preds=preds, + target=target, + mean_x=mean_x, + mean_y=mean_y, + max_abs_dev_x=max_abs_dev_x, + max_abs_dev_y=max_abs_dev_y, + var_x=var_x, + var_y=var_y, + corr_xy=corr_xy, + num_prior=nb, + num_outputs=1 if preds.ndim == 1 else preds.shape[-1], + ) + return _concordance_corrcoef_compute(max_abs_dev_x, max_abs_dev_y, mean_x, mean_y, var_x, var_y, corr_xy, nb) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/cosine_similarity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/cosine_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..c57623931a4ef3202633b636d21a6e37d945acf2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/cosine_similarity.py @@ -0,0 +1,101 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _cosine_similarity_update( + preds: Tensor, + target: Tensor, +) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute Cosine Similarity. Checks for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + _check_same_shape(preds, target) + if preds.ndim != 2: + raise ValueError( + "Expected input to cosine similarity to be 2D tensors of shape `[N,D]` where `N` is the number of samples" + f" and `D` is the number of dimensions, but got tensor of shape {preds.shape}" + ) + preds = preds.float() + target = target.float() + + return preds, target + + +def _cosine_similarity_compute(preds: Tensor, target: Tensor, reduction: Optional[str] = "sum") -> Tensor: + """Compute Cosine Similarity. + + Args: + preds: Predicted tensor + target: Ground truth tensor + reduction: + The method of reducing along the batch dimension using sum, mean or taking the individual scores + + Example: + >>> target = torch.tensor([[1, 2, 3, 4], [1, 2, 3, 4]]) + >>> preds = torch.tensor([[1, 2, 3, 4], [-1, -2, -3, -4]]) + >>> preds, target = _cosine_similarity_update(preds, target) + >>> _cosine_similarity_compute(preds, target, 'none') + tensor([ 1.0000, -1.0000]) + + """ + dot_product = (preds * target).sum(dim=-1) + preds_norm = preds.norm(dim=-1) + target_norm = target.norm(dim=-1) + similarity = dot_product / (preds_norm * target_norm) + reduction_mapping = { + "sum": torch.sum, + "mean": torch.mean, + "none": lambda x: x, + None: lambda x: x, + } + return reduction_mapping[reduction](similarity) # type: ignore[operator] + + +def cosine_similarity(preds: Tensor, target: Tensor, reduction: Optional[str] = "sum") -> Tensor: + r"""Compute the `Cosine Similarity`_. + + .. math:: + cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} = + \frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}} + + where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions. + + Args: + preds: Predicted tensor with shape ``(N,d)`` + target: Ground truth tensor with shape ``(N,d)`` + reduction: + The method of reducing along the batch dimension using sum, mean or taking the individual scores + + Example: + >>> from torchmetrics.functional.regression import cosine_similarity + >>> target = torch.tensor([[1, 2, 3, 4], + ... [1, 2, 3, 4]]) + >>> preds = torch.tensor([[1, 2, 3, 4], + ... [-1, -2, -3, -4]]) + >>> cosine_similarity(preds, target, 'none') + tensor([ 1.0000, -1.0000]) + + """ + preds, target = _cosine_similarity_update(preds, target) + return _cosine_similarity_compute(preds, target, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/crps.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/crps.py new file mode 100644 index 0000000000000000000000000000000000000000..5d92290296aa70c6962a4a818e9e320cce4ae2d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/crps.py @@ -0,0 +1,99 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Tuple + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _crps_update(preds: Tensor, target: Tensor) -> Tuple[int, Tensor, Tensor]: + """Compute intermediate CRPS values before aggregation. + + Args: + preds: Tensor of shape (batch_size, ensemble_members) + target: Tensor of shape (batch_size,) + + Returns: + batch_size: int + diff: Tensor (batch-wise absolute error term) + ensemble_sum: Tensor (pairwise ensemble term) + + """ + # Only second dimension should deviate in shape (the ensemble members) + _check_same_shape(preds[:, 0], target) + + batch_size, n_ensemble_members = preds.shape + if n_ensemble_members < 2: + raise ValueError(f"CRPS requires at least 2 ensemble members, but you provided {preds.shape}.") + + # sort forecasts + preds = torch.sort(preds, dim=1)[0] + + # inflate observations: + observation_inflated = target.unsqueeze(1).expand_as(preds) + + # Compute mean absolute difference between predictions and target + diff = torch.sum(torch.abs(preds - observation_inflated), dim=1) / n_ensemble_members + + # Compute ensemble term using the reference implementation formula + ensemble_diffs = torch.abs(preds.unsqueeze(2) - preds.unsqueeze(1)) + ensemble_sum = torch.sum(ensemble_diffs, dim=(1, 2)) / (2 * n_ensemble_members * n_ensemble_members) + + return batch_size, diff, ensemble_sum + + +def _crps_compute(batch_size: int, diff: Tensor, ensemble_sum: Tensor) -> Tensor: + """Final CRPS computation.""" + return torch.mean(diff - ensemble_sum) # Changed from sum to mean + + +def continuous_ranked_probability_score(preds: Tensor, target: Tensor) -> Tensor: + r"""Computes continuous ranked probability score. + + .. math:: + CRPS(F, y) = \int_{-\infty}^{\infty} (F(x) - 1_{x \geq y})^2 dx + + where :math:`F` is the predicted cumulative distribution function and :math:`y` is the true target. The metric is + usually used to evaluate probabilistic regression models, such as forecasting models. A lower CRPS indicates a + better forecast, meaning that forecasted probabilities are closer to the true observed values. CRPS can also be + seen as a generalization of the brier score for non binary classification problems. + + Args: + preds: a 2d tensor of shape (batch_size, ensemble_members) with predictions. The second dimension represents + the ensemble members. + target: a 1d tensor of shape (batch_size) with the target values. + + Return: + Tensor with CRPS + + Raises: + ValueError: + If the number of ensemble members is less than 2. + ValueError: + If the first dimension of preds and target do not match. + + Example:: + >>> from torchmetrics.functional.regression import continuous_ranked_probability_score + >>> from torch import randn + >>> preds = randn(10, 5) + >>> target = randn(10) + >>> continuous_ranked_probability_score(preds, target) + tensor(0.7731) + + """ + batch_size, diff, ensemble_sum = _crps_update(preds, target) + return _crps_compute(batch_size, diff, ensemble_sum) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/csi.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/csi.py new file mode 100644 index 0000000000000000000000000000000000000000..65d38e6f573e92f749a4c8790503bdaeeb618b7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/csi.py @@ -0,0 +1,112 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.compute import _safe_divide + + +def _critical_success_index_update( + preds: Tensor, target: Tensor, threshold: float, keep_sequence_dim: Optional[int] = None +) -> tuple[Tensor, Tensor, Tensor]: + """Update and return variables required to compute Critical Success Index. Checks for same shape of tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + threshold: Values above or equal to threshold are replaced with 1, below by 0 + keep_sequence_dim: Index of the sequence dimension if the inputs are sequences of images. If specified, + the score will be calculated separately for each image in the sequence. If ``None``, the score will be + calculated across all dimensions. + + """ + _check_same_shape(preds, target) + + if keep_sequence_dim is None: + sum_dims = None + elif not 0 <= keep_sequence_dim < preds.ndim: + raise ValueError(f"Expected keep_sequence dim to be in range [0, {preds.ndim}] but got {keep_sequence_dim}") + else: + sum_dims = tuple(i for i in range(preds.ndim) if i != keep_sequence_dim) + + # binarize the tensors with the threshold + preds_bin = (preds >= threshold).bool() + target_bin = (target >= threshold).bool() + + if keep_sequence_dim is None: + hits = torch.sum(preds_bin & target_bin).int() + misses = torch.sum((preds_bin ^ target_bin) & target_bin).int() + false_alarms = torch.sum((preds_bin ^ target_bin) & preds_bin).int() + else: + hits = torch.sum(preds_bin & target_bin, dim=sum_dims).int() + misses = torch.sum((preds_bin ^ target_bin) & target_bin, dim=sum_dims).int() + false_alarms = torch.sum((preds_bin ^ target_bin) & preds_bin, dim=sum_dims).int() + return hits, misses, false_alarms + + +def _critical_success_index_compute(hits: Tensor, misses: Tensor, false_alarms: Tensor) -> Tensor: + """Compute critical success index. + + Args: + hits: Number of true positives after binarization + misses: Number of false negatives after binarization + false_alarms: Number of false positives after binarization + + Returns: + If input tensors are 5-dimensional and ``keep_sequence_dim=True``, the metric returns a ``(S,)`` vector + with CSI scores for each image in the sequence. Otherwise, it returns a scalar tensor with the CSI score. + + """ + return _safe_divide(hits, hits + misses + false_alarms) + + +def critical_success_index( + preds: Tensor, target: Tensor, threshold: float, keep_sequence_dim: Optional[int] = None +) -> Tensor: + """Compute critical success index. + + Args: + preds: Predicted tensor + target: Ground truth tensor + threshold: Values above or equal to threshold are replaced with 1, below by 0 + keep_sequence_dim: Index of the sequence dimension if the inputs are sequences of images. If specified, + the score will be calculated separately for each image in the sequence. If ``None``, the score will be + calculated across all dimensions. + + Returns: + If ``keep_sequence_dim`` is specified, the metric returns a vector of with CSI scores for each image + in the sequence. Otherwise, it returns a scalar tensor with the CSI score. + + Example: + >>> import torch + >>> from torchmetrics.functional.regression import critical_success_index + >>> x = torch.Tensor([[0.2, 0.7], [0.9, 0.3]]) + >>> y = torch.Tensor([[0.4, 0.2], [0.8, 0.6]]) + >>> critical_success_index(x, y, 0.5) + tensor(0.3333) + + Example: + >>> import torch + >>> from torchmetrics.functional.regression import critical_success_index + >>> x = torch.Tensor([[[0.2, 0.7], [0.9, 0.3]], [[0.2, 0.7], [0.9, 0.3]]]) + >>> y = torch.Tensor([[[0.4, 0.2], [0.8, 0.6]], [[0.4, 0.2], [0.8, 0.6]]]) + >>> critical_success_index(x, y, 0.5, keep_sequence_dim=0) + tensor([0.3333, 0.3333]) + + """ + hits, misses, false_alarms = _critical_success_index_update(preds, target, threshold, keep_sequence_dim) + return _critical_success_index_compute(hits, misses, false_alarms) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/explained_variance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/explained_variance.py new file mode 100644 index 0000000000000000000000000000000000000000..d401bb5a349b89ccf4c00b96ddafe9179348e6cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/explained_variance.py @@ -0,0 +1,142 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.utilities.checks import _check_same_shape + +ALLOWED_MULTIOUTPUT = ("raw_values", "uniform_average", "variance_weighted") + + +def _explained_variance_update(preds: Tensor, target: Tensor) -> tuple[int, Tensor, Tensor, Tensor, Tensor]: + """Update and returns variables required to compute Explained Variance. Checks for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + _check_same_shape(preds, target) + + num_obs = preds.size(0) + sum_error = torch.sum(target - preds, dim=0) + diff = target - preds + sum_squared_error = torch.sum(diff * diff, dim=0) + + sum_target = torch.sum(target, dim=0) + sum_squared_target = torch.sum(target * target, dim=0) + + return num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target + + +def _explained_variance_compute( + num_obs: Union[int, Tensor], + sum_error: Tensor, + sum_squared_error: Tensor, + sum_target: Tensor, + sum_squared_target: Tensor, + multioutput: Literal["raw_values", "uniform_average", "variance_weighted"] = "uniform_average", +) -> Tensor: + """Compute Explained Variance. + + Args: + num_obs: Number of predictions or observations + sum_error: Sum of errors over all observations + sum_squared_error: Sum of square of errors over all observations + sum_target: Sum of target values + sum_squared_target: Sum of squares of target values + multioutput: Defines aggregation in the case of multiple output scores. Can be one + of the following strings: + + * ``'raw_values'`` returns full set of scores + * ``'uniform_average'`` scores are uniformly averaged + * ``'variance_weighted'`` scores are weighted by their individual variances + + Example: + >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) + >>> num_obs, sum_error, ss_error, sum_target, ss_target = _explained_variance_update(preds, target) + >>> _explained_variance_compute(num_obs, sum_error, ss_error, sum_target, ss_target, multioutput='raw_values') + tensor([0.9677, 1.0000]) + + """ + diff_avg = sum_error / num_obs + numerator = sum_squared_error / num_obs - (diff_avg * diff_avg) + + target_avg = sum_target / num_obs + denominator = sum_squared_target / num_obs - (target_avg * target_avg) + + # Take care of division by zero + nonzero_numerator = numerator != 0 + nonzero_denominator = denominator != 0 + valid_score = nonzero_numerator & nonzero_denominator + output_scores = torch.ones_like(diff_avg) + output_scores[valid_score] = 1.0 - (numerator[valid_score] / denominator[valid_score]) + output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 + + # Decide what to do in multioutput case + # Todo: allow user to pass in tensor with weights + if multioutput == "raw_values": + return output_scores + if multioutput == "uniform_average": + return torch.mean(output_scores) + denom_sum = torch.sum(denominator) + return torch.sum(denominator / denom_sum * output_scores) + + +def explained_variance( + preds: Tensor, + target: Tensor, + multioutput: Literal["raw_values", "uniform_average", "variance_weighted"] = "uniform_average", +) -> Union[Tensor, Sequence[Tensor]]: + """Compute explained variance. + + Args: + preds: estimated labels + target: ground truth labels + multioutput: Defines aggregation in the case of multiple output scores. Can be one + of the following strings): + + * ``'raw_values'`` returns full set of scores + * ``'uniform_average'`` scores are uniformly averaged + * ``'variance_weighted'`` scores are weighted by their individual variances + + Example: + >>> from torchmetrics.functional.regression import explained_variance + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> explained_variance(preds, target) + tensor(0.9572) + + >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) + >>> explained_variance(preds, target, multioutput='raw_values') + tensor([0.9677, 1.0000]) + + """ + if multioutput not in ALLOWED_MULTIOUTPUT: + raise ValueError(f"Invalid input to argument `multioutput`. Choose one of the following: {ALLOWED_MULTIOUTPUT}") + num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target = _explained_variance_update(preds, target) + return _explained_variance_compute( + num_obs, + sum_error, + sum_squared_error, + sum_target, + sum_squared_target, + multioutput, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/js_divergence.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/js_divergence.py new file mode 100644 index 0000000000000000000000000000000000000000..24e3295d861e2ce8e9c7cca46c1f871a7c2f6c85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/js_divergence.py @@ -0,0 +1,102 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.kl_divergence import kl_divergence +from torchmetrics.utilities.checks import _check_same_shape + + +def _jsd_update(p: Tensor, q: Tensor, log_prob: bool) -> tuple[Tensor, int]: + """Update and returns jensen-shannon divergence scores for each observation and the total number of observations. + + Args: + p: data distribution with shape ``[N, d]`` + q: prior or approximate distribution with shape ``[N, d]`` + log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities, + will normalize to make sure the distributes sum to 1 + + """ + _check_same_shape(p, q) + if p.ndim != 2 or q.ndim != 2: + raise ValueError(f"Expected both p and q distribution to be 2D but got {p.ndim} and {q.ndim} respectively") + + total = p.shape[0] + if log_prob: + mean = torch.logsumexp(torch.stack([p, q]), dim=0) - torch.log(torch.tensor(2.0)) + measures = 0.5 * kl_divergence(p, mean, log_prob=log_prob, reduction=None) + 0.5 * kl_divergence( + q, mean, log_prob=log_prob, reduction=None + ) + else: + p = p / p.sum(axis=-1, keepdim=True) # type: ignore[call-overload] + q = q / q.sum(axis=-1, keepdim=True) # type: ignore[call-overload] + mean = (p + q) / 2 + measures = 0.5 * kl_divergence(p, mean, log_prob=log_prob, reduction=None) + 0.5 * kl_divergence( + q, mean, log_prob=log_prob, reduction=None + ) + return measures, total + + +def _jsd_compute( + measures: Tensor, total: Union[int, Tensor], reduction: Literal["mean", "sum", "none", None] = "mean" +) -> Tensor: + """Compute and reduce the Jensen-Shannon divergence based on the type of reduction.""" + if reduction == "sum": + return measures.sum() + if reduction == "mean": + return measures.sum() / total + if reduction is None or reduction == "none": + return measures + return measures / total + + +def jensen_shannon_divergence( + p: Tensor, q: Tensor, log_prob: bool = False, reduction: Literal["mean", "sum", "none", None] = "mean" +) -> Tensor: + r"""Compute `Jensen-Shannon divergence`_. + + .. math:: + D_{JS}(P||Q) = \frac{1}{2} D_{KL}(P||M) + \frac{1}{2} D_{KL}(Q||M) + + Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution + over data and :math:`Q` is often a prior or approximation of :math:`P`. :math:`D_{KL}` is the `KL divergence`_ and + :math:`M` is the average of the two distributions. It should be noted that the Jensen-Shannon divergence is a + symmetrical metric i.e. :math:`D_{JS}(P||Q) = D_{JS}(Q||P)`. + + Args: + p: data distribution with shape ``[N, d]`` + q: prior or approximate distribution with shape ``[N, d]`` + log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities, + will normalize to make sure the distributes sum to 1 + reduction: + Determines how to reduce over the ``N``/batch dimension: + + - ``'mean'`` [default]: Averages score across samples + - ``'sum'``: Sum score across samples + - ``'none'`` or ``None``: Returns score per sample + + Example: + >>> from torch import tensor + >>> p = tensor([[0.36, 0.48, 0.16]]) + >>> q = tensor([[1/3, 1/3, 1/3]]) + >>> jensen_shannon_divergence(p, q) + tensor(0.0225) + + """ + measures, total = _jsd_update(p, q, log_prob) + return _jsd_compute(measures, total, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kendall.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kendall.py new file mode 100644 index 0000000000000000000000000000000000000000..a34f032943a3fd99d07e1fad710cba93e73acffc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kendall.py @@ -0,0 +1,430 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import List, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.data import _bincount, _cumsum, dim_zero_cat +from torchmetrics.utilities.enums import EnumStr + + +class _MetricVariant(EnumStr): + """Enumerate for metric variants.""" + + A = "a" + B = "b" + C = "c" + + @staticmethod + def _name() -> str: + return "variant" + + +class _TestAlternative(EnumStr): + """Enumerate for test alternative options.""" + + TWO_SIDED = "two-sided" + LESS = "less" + GREATER = "greater" + + @staticmethod + def _name() -> str: + return "alternative" + + +def _sort_on_first_sequence(x: Tensor, y: Tensor) -> tuple[Tensor, Tensor]: + """Sort sequences in an ascent order according to the sequence ``x``.""" + # We need to clone `y` tensor not to change an object in memory + y = torch.clone(y) + x, y = x.T, y.T + x, perm = x.sort() + for i in range(x.shape[0]): + y[i] = y[i][perm[i]] + return x.T, y.T + + +def _concordant_element_sum(x: Tensor, y: Tensor, i: int) -> Tensor: + """Count a total number of concordant pairs in a single sequence.""" + return torch.logical_and(x[i] < x[(i + 1) :], y[i] < y[(i + 1) :]).sum(0).unsqueeze(0) + + +def _count_concordant_pairs(preds: Tensor, target: Tensor) -> Tensor: + """Count a total number of concordant pairs in given sequences.""" + return torch.cat([_concordant_element_sum(preds, target, i) for i in range(preds.shape[0])]).sum(0) + + +def _discordant_element_sum(x: Tensor, y: Tensor, i: int) -> Tensor: + """Count a total number of discordant pairs in a single sequences.""" + return ( + torch.logical_or( + torch.logical_and(x[i] > x[(i + 1) :], y[i] < y[(i + 1) :]), + torch.logical_and(x[i] < x[(i + 1) :], y[i] > y[(i + 1) :]), + ) + .sum(0) + .unsqueeze(0) + ) + + +def _count_discordant_pairs(preds: Tensor, target: Tensor) -> Tensor: + """Count a total number of discordant pairs in given sequences.""" + return torch.cat([_discordant_element_sum(preds, target, i) for i in range(preds.shape[0])]).sum(0) + + +def _convert_sequence_to_dense_rank(x: Tensor, sort: bool = False) -> Tensor: + """Convert a sequence to the rank tensor.""" + # Sort if a sequence has not been sorted before + if sort: + x = x.sort(dim=0).values + _ones = torch.zeros(1, x.shape[1], dtype=torch.int32, device=x.device) + return _cumsum(torch.cat([_ones, (x[1:] != x[:-1]).int()], dim=0), dim=0) + + +def _get_ties(x: Tensor) -> tuple[Tensor, Tensor, Tensor]: + """Get a total number of ties and staistics for p-value calculation for a given sequence.""" + ties = torch.zeros(x.shape[1], dtype=x.dtype, device=x.device) + ties_p1 = torch.zeros(x.shape[1], dtype=x.dtype, device=x.device) + ties_p2 = torch.zeros(x.shape[1], dtype=x.dtype, device=x.device) + for dim in range(x.shape[1]): + n_ties = _bincount(x[:, dim]) + n_ties = n_ties[n_ties > 1] + ties[dim] = (n_ties * (n_ties - 1) // 2).sum() + ties_p1[dim] = (n_ties * (n_ties - 1.0) * (n_ties - 2)).sum() + ties_p2[dim] = (n_ties * (n_ties - 1.0) * (2 * n_ties + 5)).sum() + + return ties, ties_p1, ties_p2 + + +def _get_metric_metadata( + preds: Tensor, target: Tensor, variant: _MetricVariant +) -> tuple[ + Tensor, + Tensor, + Optional[Tensor], + Optional[Tensor], + Optional[Tensor], + Optional[Tensor], + Optional[Tensor], + Optional[Tensor], + Tensor, +]: + """Obtain statistics to calculate metric value.""" + preds, target = _sort_on_first_sequence(preds, target) + + concordant_pairs = _count_concordant_pairs(preds, target) + discordant_pairs = _count_discordant_pairs(preds, target) + + n_total = torch.tensor(preds.shape[0], device=preds.device) + preds_ties = target_ties = None + preds_ties_p1 = preds_ties_p2 = target_ties_p1 = target_ties_p2 = None + if variant != _MetricVariant.A: + preds = _convert_sequence_to_dense_rank(preds) + target = _convert_sequence_to_dense_rank(target, sort=True) + preds_ties, preds_ties_p1, preds_ties_p2 = _get_ties(preds) + target_ties, target_ties_p1, target_ties_p2 = _get_ties(target) + return ( + concordant_pairs, + discordant_pairs, + preds_ties, + preds_ties_p1, + preds_ties_p2, + target_ties, + target_ties_p1, + target_ties_p2, + n_total, + ) + + +def _calculate_tau( + preds: Tensor, + target: Tensor, + concordant_pairs: Tensor, + discordant_pairs: Tensor, + con_min_dis_pairs: Tensor, + n_total: Tensor, + preds_ties: Optional[Tensor], + target_ties: Optional[Tensor], + variant: _MetricVariant, +) -> Tensor: + """Calculate Kendall's tau from metric metadata.""" + if variant == _MetricVariant.A: + return con_min_dis_pairs / (concordant_pairs + discordant_pairs) + if variant == _MetricVariant.B: + total_combinations: Tensor = n_total * (n_total - 1) // 2 + if preds_ties is None: + preds_ties = torch.tensor(0.0, dtype=total_combinations.dtype, device=total_combinations.device) + if target_ties is None: + target_ties = torch.tensor(0.0, dtype=total_combinations.dtype, device=total_combinations.device) + denominator = (total_combinations - preds_ties) * (total_combinations - target_ties) + return con_min_dis_pairs / torch.sqrt(denominator) + + preds_unique = torch.tensor([len(p.unique()) for p in preds.T], dtype=preds.dtype, device=preds.device) + target_unique = torch.tensor([len(t.unique()) for t in target.T], dtype=target.dtype, device=target.device) + min_classes = torch.minimum(preds_unique, target_unique) + return 2 * con_min_dis_pairs / ((min_classes - 1) / min_classes * n_total**2) + + +def _get_p_value_for_t_value_from_dist(t_value: Tensor) -> Tensor: + """Obtain p-value for a given Tensor of t-values. Handle ``nan`` which cannot be passed into torch distributions. + + When t-value is ``nan``, a resulted p-value should be alson ``nan``. + + """ + device = t_value + normal_dist = torch.distributions.normal.Normal(torch.tensor([0.0]).to(device), torch.tensor([1.0]).to(device)) + + is_nan = t_value.isnan() + t_value = t_value.nan_to_num() + p_value = normal_dist.cdf(t_value) + return p_value.where(~is_nan, torch.tensor(float("nan"), dtype=p_value.dtype, device=p_value.device)) + + +def _calculate_p_value( + con_min_dis_pairs: Tensor, + n_total: Tensor, + preds_ties: Optional[Tensor], + preds_ties_p1: Optional[Tensor], + preds_ties_p2: Optional[Tensor], + target_ties: Optional[Tensor], + target_ties_p1: Optional[Tensor], + target_ties_p2: Optional[Tensor], + variant: _MetricVariant, + alternative: Optional[_TestAlternative], +) -> Tensor: + """Calculate p-value for Kendall's tau from metric metadata.""" + t_value_denominator_base = n_total * (n_total - 1) * (2 * n_total + 5) + if variant == _MetricVariant.A: + t_value = 3 * con_min_dis_pairs / torch.sqrt(t_value_denominator_base / 2) + else: + m = n_total * (n_total - 1) + t_value_denominator: Tensor = ( + t_value_denominator_base + - (preds_ties_p2 if preds_ties_p2 is not None else 0) + - (target_ties_p2 if target_ties_p2 is not None else 0) + ) / 18 + t_value_denominator += ( + 2 * (preds_ties if preds_ties is not None else 0) * (target_ties if target_ties is not None else 0) + ) / m + t_value_denominator += ( + (preds_ties_p1 if preds_ties_p1 is not None else 0) + * (target_ties_p1 if target_ties_p1 is not None else 0) + / (9 * m * (n_total - 2)) + ) + t_value = con_min_dis_pairs / torch.sqrt(t_value_denominator) + + if alternative == _TestAlternative.TWO_SIDED: + t_value = torch.abs(t_value) + if alternative in [_TestAlternative.TWO_SIDED, _TestAlternative.GREATER]: + t_value *= -1 + p_value = _get_p_value_for_t_value_from_dist(t_value) + if alternative == _TestAlternative.TWO_SIDED: + p_value *= 2 + return p_value + + +def _kendall_corrcoef_update( + preds: Tensor, + target: Tensor, + concat_preds: Optional[List[Tensor]] = None, + concat_target: Optional[List[Tensor]] = None, + num_outputs: int = 1, +) -> tuple[List[Tensor], List[Tensor]]: + """Update variables required to compute Kendall rank correlation coefficient. + + Args: + preds: Sequence of data + target: Sequence of data + concat_preds: List of batches of preds sequence to be concatenated + concat_target: List of batches of target sequence to be concatenated + num_outputs: Number of outputs in multioutput setting + + Raises: + RuntimeError: If ``preds`` and ``target`` do not have the same shape + + """ + concat_preds = concat_preds or [] + concat_target = concat_target or [] + # Data checking + _check_same_shape(preds, target) + _check_data_shape_to_num_outputs(preds, target, num_outputs) + + if num_outputs == 1: + preds = preds.unsqueeze(1) + target = target.unsqueeze(1) + + concat_preds.append(preds) + concat_target.append(target) + + return concat_preds, concat_target + + +def _kendall_corrcoef_compute( + preds: Tensor, + target: Tensor, + variant: _MetricVariant, + alternative: Optional[_TestAlternative] = None, +) -> tuple[Tensor, Optional[Tensor]]: + """Compute Kendall rank correlation coefficient, and optionally p-value of corresponding statistical test. + + Args: + Args: + preds: Sequence of data + target: Sequence of data + variant: Indication of which variant of Kendall's tau to be used + alternative: Alternative hypothesis for for t-test. Possible values: + - 'two-sided': the rank correlation is nonzero + - 'less': the rank correlation is negative (less than zero) + - 'greater': the rank correlation is positive (greater than zero) + + """ + ( + concordant_pairs, + discordant_pairs, + preds_ties, + preds_ties_p1, + preds_ties_p2, + target_ties, + target_ties_p1, + target_ties_p2, + n_total, + ) = _get_metric_metadata(preds, target, variant) + con_min_dis_pairs = concordant_pairs - discordant_pairs + + tau = _calculate_tau( + preds, target, concordant_pairs, discordant_pairs, con_min_dis_pairs, n_total, preds_ties, target_ties, variant + ) + p_value = ( + _calculate_p_value( + con_min_dis_pairs, + n_total, + preds_ties, + preds_ties_p1, + preds_ties_p2, + target_ties, + target_ties_p1, + target_ties_p2, + variant, + alternative, + ) + if alternative + else None + ) + + # Squeeze tensor if num_outputs=1 + if tau.shape[0] == 1: + tau = tau.squeeze() + p_value = p_value.squeeze() if p_value is not None else None + + return tau.clamp(-1, 1), p_value + + +def kendall_rank_corrcoef( + preds: Tensor, + target: Tensor, + variant: Literal["a", "b", "c"] = "b", + t_test: bool = False, + alternative: Optional[Literal["two-sided", "less", "greater"]] = "two-sided", +) -> Union[Tensor, tuple[Tensor, Tensor]]: + r"""Compute `Kendall Rank Correlation Coefficient`_. + + .. math:: + tau_a = \frac{C - D}{C + D} + + where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs. + + .. math:: + tau_b = \frac{C - D}{\sqrt{(C + D + T_{preds}) * (C + D + T_{target})}} + + where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs and :math:`T` represents + a total number of ties. + + .. math:: + tau_c = 2 * \frac{C - D}{n^2 * \frac{m - 1}{m}} + + where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs, :math:`n` is a total number + of observations and :math:`m` is a ``min`` of unique values in ``preds`` and ``target`` sequence. + + Definitions according to Definition according to `The Treatment of Ties in Ranking Problems`_. + + Args: + preds: Sequence of data of either shape ``(N,)`` or ``(N,d)`` + target: Sequence of data of either shape ``(N,)`` or ``(N,d)`` + variant: Indication of which variant of Kendall's tau to be used + t_test: Indication whether to run t-test + alternative: Alternative hypothesis for t-test. Possible values: + - 'two-sided': the rank correlation is nonzero + - 'less': the rank correlation is negative (less than zero) + - 'greater': the rank correlation is positive (greater than zero) + + Return: + Correlation tau statistic + (Optional) p-value of corresponding statistical test (asymptotic) + + Raises: + ValueError: If ``t_test`` is not of a type bool + ValueError: If ``t_test=True`` and ``alternative=None`` + + Example (single output regression): + >>> from torchmetrics.functional.regression import kendall_rank_corrcoef + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> target = torch.tensor([3, -0.5, 2, 1]) + >>> kendall_rank_corrcoef(preds, target) + tensor(0.3333) + + Example (multi output regression): + >>> from torchmetrics.functional.regression import kendall_rank_corrcoef + >>> preds = torch.tensor([[2.5, 0.0], [2, 8]]) + >>> target = torch.tensor([[3, -0.5], [2, 1]]) + >>> kendall_rank_corrcoef(preds, target) + tensor([1., 1.]) + + Example (single output regression with t-test) + >>> from torchmetrics.functional.regression import kendall_rank_corrcoef + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> target = torch.tensor([3, -0.5, 2, 1]) + >>> kendall_rank_corrcoef(preds, target, t_test=True, alternative='two-sided') + (tensor(0.3333), tensor(0.4969)) + + Example (multi output regression with t-test): + >>> from torchmetrics.functional.regression import kendall_rank_corrcoef + >>> preds = torch.tensor([[2.5, 0.0], [2, 8]]) + >>> target = torch.tensor([[3, -0.5], [2, 1]]) + >>> kendall_rank_corrcoef(preds, target, t_test=True, alternative='two-sided') + (tensor([1., 1.]), tensor([nan, nan])) + + """ + if not isinstance(t_test, bool): + raise ValueError(f"Argument `t_test` is expected to be of a type `bool`, but got {type(t_test)}.") + if t_test and alternative is None: + raise ValueError("Argument `alternative` is required if `t_test=True` but got `None`.") + + _variant = _MetricVariant.from_str(str(variant)) + _alternative = _TestAlternative.from_str(str(alternative)) if t_test else None + + _preds, _target = _kendall_corrcoef_update( + preds, target, [], [], num_outputs=1 if preds.ndim == 1 else preds.shape[-1] + ) + tau, p_value = _kendall_corrcoef_compute( + dim_zero_cat(_preds), + dim_zero_cat(_target), + _variant, # type: ignore[arg-type] # todo + _alternative, # type: ignore[arg-type] # todo + ) + + if p_value is not None: + return tau, p_value + return tau diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kl_divergence.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kl_divergence.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ed9efb25a94a7c317d1e04280dcb6a9352f617 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kl_divergence.py @@ -0,0 +1,115 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.compute import _safe_xlogy + + +def _kld_update(p: Tensor, q: Tensor, log_prob: bool) -> tuple[Tensor, int]: + """Update and returns KL divergence scores for each observation and the total number of observations. + + Args: + p: data distribution with shape ``[N, d]`` + q: prior or approximate distribution with shape ``[N, d]`` + log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities, + will normalize to make sure the distributes sum to 1 + + """ + _check_same_shape(p, q) + if p.ndim != 2 or q.ndim != 2: + raise ValueError(f"Expected both p and q distribution to be 2D but got {p.ndim} and {q.ndim} respectively") + + total = p.shape[0] + if log_prob: + measures = torch.sum(p.exp() * (p - q), axis=-1) # type: ignore[call-overload] + else: + p = p / p.sum(axis=-1, keepdim=True) # type: ignore[call-overload] + q = q / q.sum(axis=-1, keepdim=True) # type: ignore[call-overload] + measures = _safe_xlogy(p, p / q).sum(axis=-1) # type: ignore[call-overload] + + return measures, total + + +def _kld_compute( + measures: Tensor, total: Union[int, Tensor], reduction: Literal["mean", "sum", "none", None] = "mean" +) -> Tensor: + """Compute the KL divergenece based on the type of reduction. + + Args: + measures: Tensor of KL divergence scores for each observation + total: Number of observations + reduction: + Determines how to reduce over the ``N``/batch dimension: + + - ``'mean'`` [default]: Averages score across samples + - ``'sum'``: Sum score across samples + - ``'none'`` or ``None``: Returns score per sample + + Example: + >>> p = torch.tensor([[0.36, 0.48, 0.16]]) + >>> q = torch.tensor([[1/3, 1/3, 1/3]]) + >>> measures, total = _kld_update(p, q, log_prob=False) + >>> _kld_compute(measures, total) + tensor(0.0853) + + """ + if reduction == "sum": + return measures.sum() + if reduction == "mean": + return measures.sum() / total + if reduction is None or reduction == "none": + return measures + return measures / total + + +def kl_divergence( + p: Tensor, q: Tensor, log_prob: bool = False, reduction: Literal["mean", "sum", "none", None] = "mean" +) -> Tensor: + r"""Compute `KL divergence`_. + + .. math:: + D_{KL}(P||Q) = \sum_{x\in\mathcal{X}} P(x) \log\frac{P(x)}{Q{x}} + + Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution + over data and :math:`Q` is often a prior or approximation of :math:`P`. It should be noted that the KL divergence + is a non-symmetrical metric i.e. :math:`D_{KL}(P||Q) \neq D_{KL}(Q||P)`. + + Args: + p: data distribution with shape ``[N, d]`` + q: prior or approximate distribution with shape ``[N, d]`` + log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities, + will normalize to make sure the distributes sum to 1 + reduction: + Determines how to reduce over the ``N``/batch dimension: + + - ``'mean'`` [default]: Averages score across samples + - ``'sum'``: Sum score across samples + - ``'none'`` or ``None``: Returns score per sample + + Example: + >>> from torch import tensor + >>> p = tensor([[0.36, 0.48, 0.16]]) + >>> q = tensor([[1/3, 1/3, 1/3]]) + >>> kl_divergence(p, q) + tensor(0.0853) + + """ + measures, total = _kld_update(p, q, log_prob) + return _kld_compute(measures, total, reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_cosh.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_cosh.py new file mode 100644 index 0000000000000000000000000000000000000000..e13ee2a3e7afe2a166e443ca10f2eaea1bc0778f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_cosh.py @@ -0,0 +1,95 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs +from torchmetrics.utilities.checks import _check_same_shape + + +def _unsqueeze_tensors(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]: + if preds.ndim == 2: + return preds, target + return preds.unsqueeze(1), target.unsqueeze(1) + + +def _log_cosh_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute LogCosh error. + + Check for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + num_outputs: Number of outputs in multioutput setting + + Return: + Sum of LogCosh error over examples, and total number of examples + + """ + _check_same_shape(preds, target) + _check_data_shape_to_num_outputs(preds, target, num_outputs) + + preds, target = _unsqueeze_tensors(preds, target) + diff = preds - target + sum_log_cosh_error = torch.log((torch.exp(diff) + torch.exp(-diff)) / 2).sum(0).squeeze() + num_obs = torch.tensor(target.shape[0], device=preds.device) + return sum_log_cosh_error, num_obs + + +def _log_cosh_error_compute(sum_log_cosh_error: Tensor, num_obs: Tensor) -> Tensor: + """Compute Mean Squared Error. + + Args: + sum_log_cosh_error: Sum of LogCosh errors over all observations + num_obs: Number of predictions or observations + + """ + return (sum_log_cosh_error / num_obs).squeeze() + + +def log_cosh_error(preds: Tensor, target: Tensor) -> Tensor: + r"""Compute the `LogCosh Error`_. + + .. math:: \text{LogCoshError} = \log\left(\frac{\exp(\hat{y} - y) + \exp(\hat{y - y})}{2}\right) + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + Args: + preds: estimated labels with shape ``(batch_size,)`` or `(batch_size, num_outputs)`` + target: ground truth labels with shape ``(batch_size,)`` or `(batch_size, num_outputs)`` + + Return: + Tensor with LogCosh error + + Example (single output regression):: + >>> from torchmetrics.functional.regression import log_cosh_error + >>> preds = torch.tensor([3.0, 5.0, 2.5, 7.0]) + >>> target = torch.tensor([2.5, 5.0, 4.0, 8.0]) + >>> log_cosh_error(preds, target) + tensor(0.3523) + + Example (multi output regression):: + >>> from torchmetrics.functional.regression import log_cosh_error + >>> preds = torch.tensor([[3.0, 5.0, 1.2], [-2.1, 2.5, 7.0]]) + >>> target = torch.tensor([[2.5, 5.0, 1.3], [0.3, 4.0, 8.0]]) + >>> log_cosh_error(preds, target) + tensor([0.9176, 0.4277, 0.2194]) + + """ + sum_log_cosh_error, num_obs = _log_cosh_error_update( + preds, target, num_outputs=1 if preds.ndim == 1 else preds.shape[-1] + ) + return _log_cosh_error_compute(sum_log_cosh_error, num_obs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_mse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_mse.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3a3585127f47537d4fd5d4364fb990bcb36623 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_mse.py @@ -0,0 +1,76 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _mean_squared_log_error_update(preds: Tensor, target: Tensor) -> tuple[Tensor, int]: + """Return variables required to compute Mean Squared Log Error. Checks for same shape of tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + _check_same_shape(preds, target) + sum_squared_log_error = torch.sum(torch.pow(torch.log1p(preds) - torch.log1p(target), 2)) + return sum_squared_log_error, target.numel() + + +def _mean_squared_log_error_compute(sum_squared_log_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor: + """Compute Mean Squared Log Error. + + Args: + sum_squared_log_error: + Sum of square of log errors over all observations ``(log error = log(target) - log(prediction))`` + num_obs: Number of predictions or observations + + Example: + >>> preds = torch.tensor([0., 1, 2, 3]) + >>> target = torch.tensor([0., 1, 2, 2]) + >>> sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target) + >>> _mean_squared_log_error_compute(sum_squared_log_error, num_obs) + tensor(0.0207) + + """ + return sum_squared_log_error / num_obs + + +def mean_squared_log_error(preds: Tensor, target: Tensor) -> Tensor: + """Compute mean squared log error. + + Args: + preds: estimated labels + target: ground truth labels + + Return: + Tensor with RMSLE + + Example: + >>> from torchmetrics.functional.regression import mean_squared_log_error + >>> x = torch.tensor([0., 1, 2, 3]) + >>> y = torch.tensor([0., 1, 2, 2]) + >>> mean_squared_log_error(x, y) + tensor(0.0207) + + .. attention:: + Half precision is only support on GPU for this metric. + + """ + sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target) + return _mean_squared_log_error_compute(sum_squared_log_error, num_obs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mae.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mae.py new file mode 100644 index 0000000000000000000000000000000000000000..8774d67fbe16b05f336ef9ae6a86b135ec052fbc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mae.py @@ -0,0 +1,81 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _mean_absolute_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, int]: + """Update and returns variables required to compute Mean Absolute Error. + + Check for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + num_outputs: Number of outputs in multioutput setting + + """ + _check_same_shape(preds, target) + if num_outputs == 1: + preds = preds.view(-1) + target = target.view(-1) + preds = preds if preds.is_floating_point else preds.float() # type: ignore[truthy-function] # todo + target = target if target.is_floating_point else target.float() # type: ignore[truthy-function] # todo + sum_abs_error = torch.sum(torch.abs(preds - target), dim=0) + return sum_abs_error, target.shape[0] + + +def _mean_absolute_error_compute(sum_abs_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor: + """Compute Mean Absolute Error. + + Args: + sum_abs_error: Sum of absolute value of errors over all observations + num_obs: Number of predictions or observations + + Example: + >>> preds = torch.tensor([0., 1, 2, 3]) + >>> target = torch.tensor([0., 1, 2, 2]) + >>> sum_abs_error, num_obs = _mean_absolute_error_update(preds, target, num_outputs=1) + >>> _mean_absolute_error_compute(sum_abs_error, num_obs) + tensor(0.2500) + + """ + return sum_abs_error / num_obs + + +def mean_absolute_error(preds: Tensor, target: Tensor, num_outputs: int = 1) -> Tensor: + """Compute mean absolute error. + + Args: + preds: estimated labels + target: ground truth labels + num_outputs: Number of outputs in multioutput setting + + Return: + Tensor with MAE + + Example: + >>> from torchmetrics.functional.regression import mean_absolute_error + >>> x = torch.tensor([0., 1, 2, 3]) + >>> y = torch.tensor([0., 1, 2, 2]) + >>> mean_absolute_error(x, y) + tensor(0.2500) + + """ + sum_abs_error, num_obs = _mean_absolute_error_update(preds, target, num_outputs=num_outputs) + return _mean_absolute_error_compute(sum_abs_error, num_obs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mape.py new file mode 100644 index 0000000000000000000000000000000000000000..c109e898eeea59e39549fa2ca101a43964878687 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mape.py @@ -0,0 +1,91 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _mean_absolute_percentage_error_update( + preds: Tensor, + target: Tensor, + epsilon: float = 1.17e-06, +) -> tuple[Tensor, int]: + """Update and returns variables required to compute Mean Percentage Error. + + Check for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + epsilon: Specifies the lower bound for target values. Any target value below epsilon + is set to epsilon (avoids ``ZeroDivisionError``). + + """ + _check_same_shape(preds, target) + + abs_diff = torch.abs(preds - target) + abs_per_error = abs_diff / torch.clamp(torch.abs(target), min=epsilon) + + sum_abs_per_error = torch.sum(abs_per_error) + + num_obs = target.numel() + + return sum_abs_per_error, num_obs + + +def _mean_absolute_percentage_error_compute(sum_abs_per_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor: + """Compute Mean Absolute Percentage Error. + + Args: + sum_abs_per_error: Sum of absolute value of percentage errors over all observations + ``(percentage error = (target - prediction) / target)`` + num_obs: Number of predictions or observations + + Example: + >>> target = torch.tensor([1, 10, 1e6]) + >>> preds = torch.tensor([0.9, 15, 1.2e6]) + >>> sum_abs_per_error, num_obs = _mean_absolute_percentage_error_update(preds, target) + >>> _mean_absolute_percentage_error_compute(sum_abs_per_error, num_obs) + tensor(0.2667) + + """ + return sum_abs_per_error / num_obs + + +def mean_absolute_percentage_error(preds: Tensor, target: Tensor) -> Tensor: + """Compute mean absolute percentage error. + + Args: + preds: estimated labels + target: ground truth labels + + Return: + Tensor with MAPE + + Note: + The epsilon value is taken from `scikit-learn's implementation of MAPE`_. + + Example: + >>> from torchmetrics.functional.regression import mean_absolute_percentage_error + >>> target = torch.tensor([1, 10, 1e6]) + >>> preds = torch.tensor([0.9, 15, 1.2e6]) + >>> mean_absolute_percentage_error(preds, target) + tensor(0.2667) + + """ + sum_abs_per_error, num_obs = _mean_absolute_percentage_error_update(preds, target) + return _mean_absolute_percentage_error_compute(sum_abs_per_error, num_obs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/minkowski.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/minkowski.py new file mode 100644 index 0000000000000000000000000000000000000000..ce9915963fdb3cee234ecc09bda008a1debc3647 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/minkowski.py @@ -0,0 +1,84 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.exceptions import TorchMetricsUserError + + +def _minkowski_distance_update(preds: Tensor, targets: Tensor, p: float) -> Tensor: + """Update and return variables required to compute Minkowski distance. + + Checks for same shape of input tensors. + + Args: + preds: Predicted tensor + targets: Ground truth tensor + p: Non-negative number acting as the p to the errors + + """ + _check_same_shape(preds, targets) + + if not (isinstance(p, (float, int)) and p >= 1): + raise TorchMetricsUserError(f"Argument ``p`` must be a float or int greater than 1, but got {p}") + + difference = torch.abs(preds - targets) + return torch.sum(torch.pow(difference, p)) + + +def _minkowski_distance_compute(distance: Tensor, p: float) -> Tensor: + """Compute Minkowski Distance. + + Args: + distance: Sum of the p-th powers of errors over all observations + p: The non-negative numeric power the errors are to be raised to + + Example: + >>> preds = torch.tensor([0., 1, 2, 3]) + >>> target = torch.tensor([0., 2, 3, 1]) + >>> distance_p_sum = _minkowski_distance_update(preds, target, 5) + >>> _minkowski_distance_compute(distance_p_sum, 5) + tensor(2.0244) + + """ + return torch.pow(distance, 1.0 / p) + + +def minkowski_distance(preds: Tensor, targets: Tensor, p: float) -> Tensor: + r"""Compute the `Minkowski distance`_. + + .. math:: d_{\text{Minkowski}} = \\sum_{i}^N (| y_i - \\hat{y_i} |^p)^\frac{1}{p} + + This metric can be seen as generalized version of the standard euclidean distance which corresponds to minkowski + distance with p=2. + + Args: + preds: estimated labels of type Tensor + targets: ground truth labels of type Tensor + p: int or float larger than 1, exponent to which the difference between preds and target is to be raised + + Return: + Tensor with the Minkowski distance + + Example: + >>> from torchmetrics.functional.regression import minkowski_distance + >>> x = torch.tensor([1.0, 2.8, 3.5, 4.5]) + >>> y = torch.tensor([6.1, 2.11, 3.1, 5.6]) + >>> minkowski_distance(x, y, p=3) + tensor(5.1220) + + """ + minkowski_dist_sum = _minkowski_distance_update(preds, targets, p) + return _minkowski_distance_compute(minkowski_dist_sum, p) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mse.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea9490c8414bf3771f249bbf4237e4b35e31020 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mse.py @@ -0,0 +1,82 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _mean_squared_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, int]: + """Update and returns variables required to compute Mean Squared Error. + + Check for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + num_outputs: Number of outputs in multioutput setting + + """ + _check_same_shape(preds, target) + if num_outputs == 1: + preds = preds.view(-1) + target = target.view(-1) + diff = preds - target + sum_squared_error = torch.sum(diff * diff, dim=0) + return sum_squared_error, target.shape[0] + + +def _mean_squared_error_compute(sum_squared_error: Tensor, num_obs: Union[int, Tensor], squared: bool = True) -> Tensor: + """Compute Mean Squared Error. + + Args: + sum_squared_error: Sum of square of errors over all observations + num_obs: Number of predictions or observations + squared: Returns RMSE value if set to False. + + Example: + >>> preds = torch.tensor([0., 1, 2, 3]) + >>> target = torch.tensor([0., 1, 2, 2]) + >>> sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=1) + >>> _mean_squared_error_compute(sum_squared_error, num_obs) + tensor(0.2500) + + """ + return sum_squared_error / num_obs if squared else torch.sqrt(sum_squared_error / num_obs) + + +def mean_squared_error(preds: Tensor, target: Tensor, squared: bool = True, num_outputs: int = 1) -> Tensor: + """Compute mean squared error. + + Args: + preds: estimated labels + target: ground truth labels + squared: returns RMSE value if set to False + num_outputs: Number of outputs in multioutput setting + + Return: + Tensor with MSE + + Example: + >>> from torchmetrics.functional.regression import mean_squared_error + >>> x = torch.tensor([0., 1, 2, 3]) + >>> y = torch.tensor([0., 1, 2, 2]) + >>> mean_squared_error(x, y) + tensor(0.2500) + + """ + sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=num_outputs) + return _mean_squared_error_compute(sum_squared_error, num_obs, squared=squared) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/nrmse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/nrmse.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbe81c333d922ed30d96d8961c4a045b4c5a58c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/nrmse.py @@ -0,0 +1,106 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.mse import _mean_squared_error_update + + +def _normalized_root_mean_squared_error_update( + preds: Tensor, target: Tensor, num_outputs: int, normalization: Literal["mean", "range", "std", "l2"] = "mean" +) -> tuple[Tensor, int, Tensor]: + """Updates and returns the sum of squared errors and the number of observations for NRMSE computation. + + Args: + preds: Predicted tensor + target: Ground truth tensor + num_outputs: Number of outputs in multioutput setting + normalization: type of normalization to be applied. Choose from "mean", "range", "std", "l2" + + """ + sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs) + + target = target.view(-1) if num_outputs == 1 else target + if normalization == "mean": + denom = torch.mean(target, dim=0) + elif normalization == "range": + denom = torch.max(target, dim=0).values - torch.min(target, dim=0).values + elif normalization == "std": + denom = torch.std(target, correction=0, dim=0) + elif normalization == "l2": + denom = torch.norm(target, p=2, dim=0) + else: + raise ValueError( + f"Argument `normalization` should be either 'mean', 'range', 'std' or 'l2' but got {normalization}" + ) + return sum_squared_error, num_obs, denom + + +def _normalized_root_mean_squared_error_compute( + sum_squared_error: Tensor, num_obs: Union[int, Tensor], denom: Tensor +) -> Tensor: + """Calculates RMSE and normalizes it.""" + rmse = torch.sqrt(sum_squared_error / num_obs) + return rmse / denom + + +def normalized_root_mean_squared_error( + preds: Tensor, + target: Tensor, + normalization: Literal["mean", "range", "std", "l2"] = "mean", + num_outputs: int = 1, +) -> Tensor: + """Calculates the `Normalized Root Mean Squared Error`_ (NRMSE) also know as scatter index. + + Args: + preds: estimated labels + target: ground truth labels + normalization: type of normalization to be applied. Choose from "mean", "range", "std", "l2" which corresponds + to normalizing the RMSE by the mean of the target, the range of the target, the standard deviation of the + target or the L2 norm of the target. + num_outputs: Number of outputs in multioutput setting + + Return: + Tensor with the NRMSE score + + Example: + >>> import torch + >>> from torchmetrics.functional.regression import normalized_root_mean_squared_error + >>> preds = torch.tensor([0., 1, 2, 3]) + >>> target = torch.tensor([0., 1, 2, 2]) + >>> normalized_root_mean_squared_error(preds, target, normalization="mean") + tensor(0.4000) + >>> normalized_root_mean_squared_error(preds, target, normalization="range") + tensor(0.2500) + >>> normalized_root_mean_squared_error(preds, target, normalization="std") + tensor(0.6030) + >>> normalized_root_mean_squared_error(preds, target, normalization="l2") + tensor(0.1667) + + Example (multioutput): + >>> import torch + >>> from torchmetrics.functional.regression import normalized_root_mean_squared_error + >>> preds = torch.tensor([[0., 1], [2, 3], [4, 5], [6, 7]]) + >>> target = torch.tensor([[0., 1], [3, 3], [4, 5], [8, 9]]) + >>> normalized_root_mean_squared_error(preds, target, normalization="mean", num_outputs=2) + tensor([0.2981, 0.2222]) + + """ + sum_squared_error, num_obs, denom = _normalized_root_mean_squared_error_update( + preds, target, num_outputs=num_outputs, normalization=normalization + ) + return _normalized_root_mean_squared_error_compute(sum_squared_error, num_obs, denom) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/pearson.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/pearson.py new file mode 100644 index 0000000000000000000000000000000000000000..ad42f4f937ce2f8e5a88e109a6b97bf6be396de1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/pearson.py @@ -0,0 +1,189 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.checks import _check_same_shape + + +def _pearson_corrcoef_update( + preds: Tensor, + target: Tensor, + mean_x: Tensor, + mean_y: Tensor, + max_abs_dev_x: Tensor, + max_abs_dev_y: Tensor, + var_x: Tensor, + var_y: Tensor, + corr_xy: Tensor, + num_prior: Tensor, + num_outputs: int, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: + """Update and returns variables required to compute Pearson Correlation Coefficient. + + Check for same shape of input tensors. + + Args: + preds: estimated scores + target: ground truth scores + mean_x: current mean estimate of x tensor + mean_y: current mean estimate of y tensor + max_abs_dev_x: current maximum absolute value of x tensor + max_abs_dev_y: current maximum absolute value of y tensor + var_x: current variance estimate of x tensor + var_y: current variance estimate of y tensor + corr_xy: current covariance estimate between x and y tensor + num_prior: current number of observed observations + num_outputs: Number of outputs in multioutput setting + + """ + # Data checking + _check_same_shape(preds, target) + _check_data_shape_to_num_outputs(preds, target, num_outputs) + num_obs = preds.shape[0] + + batch_mean_x = preds.mean(0) + batch_mean_y = target.mean(0) + delta_x = batch_mean_x - mean_x + delta_y = batch_mean_y - mean_y + n_total = num_prior + num_obs + mx_new = mean_x + delta_x * num_obs / n_total + my_new = mean_y + delta_y * num_obs / n_total + if num_obs == 1: + delta2_x = batch_mean_x - mx_new + delta2_y = batch_mean_y - my_new + var_x = var_x + delta2_x * delta_x + var_y = var_y + delta2_y * delta_y + corr_xy = corr_xy + delta_x * delta2_y + else: + preds_centered = preds - batch_mean_x + target_centered = target - batch_mean_y + + batch_var_x = (preds_centered**2).sum(0) + batch_var_y = (target_centered**2).sum(0) + batch_cov_xy = (preds_centered * target_centered).sum(0) + + correction = num_prior * num_obs / n_total + var_x = var_x + batch_var_x + delta_x**2 * correction + var_y = var_y + batch_var_y + delta_y**2 * correction + + corr_xy = corr_xy + batch_cov_xy + delta_x * delta_y * correction + max_abs_dev_x = torch.maximum(max_abs_dev_x, torch.max((preds - mx_new).abs(), dim=0)[0]) + max_abs_dev_y = torch.maximum(max_abs_dev_y, torch.max((target - my_new).abs(), dim=0)[0]) + return mx_new, my_new, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, n_total + + +def _pearson_corrcoef_compute( + max_abs_dev_x: Tensor, + max_abs_dev_y: Tensor, + var_x: Tensor, + var_y: Tensor, + corr_xy: Tensor, + nb: Tensor, +) -> Tensor: + """Compute the final pearson correlation based on accumulated statistics. + + Args: + max_abs_dev_x: maximum absolute value of x tensor + max_abs_dev_y: maximum absolute value of y tensor + var_x: variance estimate of x tensor + var_y: variance estimate of y tensor + corr_xy: covariance estimate between x and y tensor + nb: number of observations + + """ + # prevent overwrite the inputs + var_x = var_x / (nb - 1) + var_y = var_y / (nb - 1) + corr_xy = corr_xy / (nb - 1) + # if var_x, var_y is float16 and on cpu, make it bfloat16 as sqrt is not supported for float16 + # on cpu, remove this after https://github.com/pytorch/pytorch/issues/54774 is fixed + if var_x.dtype == torch.float16 and var_x.device == torch.device("cpu"): + var_x = var_x.bfloat16() + var_y = var_y.bfloat16() + var_x = var_x * torch.pow(max_abs_dev_x, -2) + var_y = var_y * torch.pow(max_abs_dev_y, -2) + corr_xy = corr_xy / (max_abs_dev_x * max_abs_dev_y) + bound = math.sqrt(torch.finfo(var_x.dtype).eps) + if ( + (var_x < bound).any() + or (var_y < bound).any() + or ~torch.isfinite(var_x).any() + or ~torch.isfinite(var_y).any() + or ~torch.isfinite(corr_xy).any() + ): + rank_zero_warn( + "The variance of predictions or target is close to zero. This can cause instability in Pearson correlation" + "coefficient, leading to wrong results. Consider re-scaling the input if possible or computing using a" + f"larger dtype (currently using {var_x.dtype}). Setting the correlation coefficient to nan.", + UserWarning, + ) + zero_var_mask = ( + (var_x < bound) | (var_y < bound) | ~torch.isfinite(var_x) | ~torch.isfinite(var_y) | ~torch.isfinite(corr_xy) + ) + corrcoef = torch.full_like(corr_xy, float("nan"), device=corr_xy.device, dtype=corr_xy.dtype) + valid_mask = ~zero_var_mask + if valid_mask.any(): + corrcoef[valid_mask] = ( + (corr_xy[valid_mask] / (var_x[valid_mask] * var_y[valid_mask]).sqrt()).squeeze().to(corrcoef.dtype) + ) + corrcoef = torch.clamp(corrcoef, -1.0, 1.0) + return corrcoef.squeeze() + + +def pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor: + """Compute pearson correlation coefficient. + + Args: + preds: estimated scores + target: ground truth scores + + Example (single output regression): + >>> from torchmetrics.functional.regression import pearson_corrcoef + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> pearson_corrcoef(preds, target) + tensor(0.9849) + + Example (multi output regression): + >>> from torchmetrics.functional.regression import pearson_corrcoef + >>> target = torch.tensor([[3, -0.5], [2, 7]]) + >>> preds = torch.tensor([[2.5, 0.0], [2, 8]]) + >>> pearson_corrcoef(preds, target) + tensor([1., 1.]) + + """ + d = preds.shape[1] if preds.ndim == 2 else 1 + _temp = torch.zeros(d, dtype=preds.dtype, device=preds.device) + mean_x, mean_y, var_x = _temp.clone(), _temp.clone(), _temp.clone() + var_y, corr_xy, nb = _temp.clone(), _temp.clone(), _temp.clone() + max_abs_dev_x, max_abs_dev_y = _temp.clone(), _temp.clone() + _, _, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb = _pearson_corrcoef_update( + preds=preds, + target=target, + mean_x=mean_x, + mean_y=mean_y, + max_abs_dev_x=max_abs_dev_x, + max_abs_dev_y=max_abs_dev_y, + var_x=var_x, + var_y=var_y, + corr_xy=corr_xy, + num_prior=nb, + num_outputs=1 if preds.ndim == 1 else preds.shape[-1], + ) + return _pearson_corrcoef_compute(max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/r2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/r2.py new file mode 100644 index 0000000000000000000000000000000000000000..c8227ae5ccf3da64ba98ddb06d024395c324a128 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/r2.py @@ -0,0 +1,174 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor + +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.checks import _check_same_shape + + +def _r2_score_update(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor, Tensor, int]: + """Update and returns variables required to compute R2 score. + + Check for same shape and 1D/2D input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + _check_same_shape(preds, target) + if preds.ndim > 2: + raise ValueError( + "Expected both prediction and target to be 1D or 2D tensors," + f" but received tensors with dimension {preds.shape}" + ) + + sum_obs = torch.sum(target, dim=0) + sum_squared_obs = torch.sum(target * target, dim=0) + residual = target - preds + rss = torch.sum(residual * residual, dim=0) + return sum_squared_obs, sum_obs, rss, target.size(0) + + +def _r2_score_compute( + sum_squared_obs: Tensor, + sum_obs: Tensor, + rss: Tensor, + num_obs: Union[int, Tensor], + adjusted: int = 0, + multioutput: str = "uniform_average", +) -> Tensor: + """Compute R2 score. + + Args: + sum_squared_obs: Sum of square of all observations + sum_obs: Sum of all observations + rss: Residual sum of squares + num_obs: Number of predictions or observations + adjusted: number of independent regressors for calculating adjusted r2 score. + multioutput: Defines aggregation in the case of multiple output scores. Can be one of the following strings: + + * `'raw_values'` returns full set of scores + * `'uniform_average'` scores are uniformly averaged + * `'variance_weighted'` scores are weighted by their individual variances + + Example: + >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) + >>> sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + >>> _r2_score_compute(sum_squared_obs, sum_obs, rss, num_obs, multioutput="raw_values") + tensor([0.9654, 0.9082]) + + """ + if num_obs < 2: + raise ValueError("Needs at least two samples to calculate r2 score.") + + mean_obs = sum_obs / num_obs + tss = sum_squared_obs - sum_obs * mean_obs + + # Account for near constant targets + cond_rss = ~torch.isclose(rss, torch.zeros_like(rss), atol=1e-4) + cond_tss = ~torch.isclose(tss, torch.zeros_like(tss), atol=1e-4) + cond = cond_rss & cond_tss + + raw_scores = torch.ones_like(rss) + raw_scores[cond] = 1 - (rss[cond] / tss[cond]) + raw_scores[cond_rss & ~cond_tss] = 0.0 + + if multioutput == "raw_values": + r2 = raw_scores + elif multioutput == "uniform_average": + r2 = torch.mean(raw_scores) + elif multioutput == "variance_weighted": + tss_sum = torch.sum(tss) + r2 = torch.sum(tss / tss_sum * raw_scores) + else: + raise ValueError( + "Argument `multioutput` must be either `raw_values`," + f" `uniform_average` or `variance_weighted`. Received {multioutput}." + ) + + if adjusted < 0 or not isinstance(adjusted, int): + raise ValueError("`adjusted` parameter should be an integer larger or equal to 0.") + + if adjusted != 0: + if adjusted > num_obs - 1: + rank_zero_warn( + "More independent regressions than data points in adjusted r2 score. Falls back to standard r2 score.", + UserWarning, + ) + elif adjusted == num_obs - 1: + rank_zero_warn("Division by zero in adjusted r2 score. Falls back to standard r2 score.", UserWarning) + else: + return 1 - (1 - r2) * (num_obs - 1) / (num_obs - adjusted - 1) + return r2 + + +def r2_score( + preds: Tensor, + target: Tensor, + adjusted: int = 0, + multioutput: str = "uniform_average", +) -> Tensor: + r"""Compute r2 score also known as `R2 Score_Coefficient Determination`_. + + .. math:: R^2 = 1 - \frac{SS_{res}}{SS_{tot}} + + where :math:`SS_{res}=\sum_i (y_i - f(x_i))^2` is the sum of residual squares, and + :math:`SS_{tot}=\sum_i (y_i - \bar{y})^2` is total sum of squares. Can also calculate + adjusted r2 score given by + + .. math:: R^2_{adj} = 1 - \frac{(1-R^2)(n-1)}{n-k-1} + + where the parameter :math:`k` (the number of independent regressors) should + be provided as the ``adjusted`` argument. + + Args: + preds: estimated labels + target: ground truth labels + adjusted: number of independent regressors for calculating adjusted r2 score. + multioutput: Defines aggregation in the case of multiple output scores. Can be one of the following strings: + + * ``'raw_values'`` returns full set of scores + * ``'uniform_average'`` scores are uniformly averaged + * ``'variance_weighted'`` scores are weighted by their individual variances + + Raises: + ValueError: + If both ``preds`` and ``targets`` are not ``1D`` or ``2D`` tensors. + ValueError: + If ``len(preds)`` is less than ``2`` since at least ``2`` samples are needed to calculate r2 score. + ValueError: + If ``multioutput`` is not one of ``raw_values``, ``uniform_average`` or ``variance_weighted``. + ValueError: + If ``adjusted`` is not an ``integer`` greater than ``0``. + + Example: + >>> from torchmetrics.functional.regression import r2_score + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> r2_score(preds, target) + tensor(0.9486) + + >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) + >>> r2_score(preds, target, multioutput='raw_values') + tensor([0.9654, 0.9082]) + + """ + sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + return _r2_score_compute(sum_squared_obs, sum_obs, rss, num_obs, adjusted, multioutput) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/rse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/rse.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb07002bfc3d8355baeed5953b9c89ead8813a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/rse.py @@ -0,0 +1,80 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.r2 import _r2_score_update + + +def _relative_squared_error_compute( + sum_squared_obs: Tensor, + sum_obs: Tensor, + sum_squared_error: Tensor, + num_obs: Union[int, Tensor], + squared: bool = True, +) -> Tensor: + """Computes Relative Squared Error. + + Args: + sum_squared_obs: Sum of square of all observations + sum_obs: Sum of all observations + sum_squared_error: Residual sum of squares + num_obs: Number of predictions or observations + squared: Returns RRSE value if set to False. + + Example: + >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) + >>> # RSE uses the same update function as R2 score. + >>> sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + >>> _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=True) + tensor(0.0632) + + """ + epsilon = torch.finfo(sum_squared_error.dtype).eps + rse = sum_squared_error / torch.clamp(sum_squared_obs - sum_obs * sum_obs / num_obs, min=epsilon) + if not squared: + rse = torch.sqrt(rse) + return torch.mean(rse) + + +def relative_squared_error(preds: Tensor, target: Tensor, squared: bool = True) -> Tensor: + r"""Computes the relative squared error (RSE). + + .. math:: \text{RSE} = \frac{\sum_i^N(y_i - \hat{y_i})^2}{\sum_i^N(y_i - \overline{y})^2} + + Where :math:`y` is a tensor of target values with mean :math:`\overline{y}`, and + :math:`\hat{y}` is a tensor of predictions. + + If `preds` and `targets` are 2D tensors, the RSE is averaged over the second dim. + + Args: + preds: estimated labels + target: ground truth labels + squared: returns RRSE value if set to False + Return: + Tensor with RSE + + Example: + >>> from torchmetrics.functional.regression import relative_squared_error + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> relative_squared_error(preds, target) + tensor(0.0514) + + """ + sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + return _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=squared) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/spearman.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/spearman.py new file mode 100644 index 0000000000000000000000000000000000000000..094f87c5c83352c53b96adcbfd7f46fad59c4114 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/spearman.py @@ -0,0 +1,126 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs +from torchmetrics.utilities.checks import _check_same_shape + + +def _rank_data(data: Tensor) -> Tensor: + """Calculate the rank for each element of a tensor. + + The rank refers to the indices of an element in the corresponding sorted tensor (starting from 1). Duplicates of the + same value will be assigned the mean of their rank. + + Adopted from `Rank of element tensor`_ + + """ + n = data.numel() + rank = torch.empty_like(data, dtype=torch.int32) + idx = data.argsort() + rank[idx[:n]] = torch.arange(1, n + 1, dtype=torch.int32, device=data.device) + uniq, inv, counts = torch.unique(data, sorted=True, return_inverse=True, return_counts=True) + sum_ranks = torch.zeros_like(uniq, dtype=torch.int32) + sum_ranks.scatter_add_(0, inv, rank.to(torch.int32)) + mean_ranks = sum_ranks / counts + return mean_ranks[inv] + + +def _spearman_corrcoef_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute Spearman Correlation Coefficient. + + Check for same shape and type of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + num_outputs: Number of outputs in multioutput setting + + """ + if not (preds.is_floating_point() and target.is_floating_point()): + raise TypeError( + "Expected `preds` and `target` both to be floating point tensors, but got {pred.dtype} and {target.dtype}" + ) + _check_same_shape(preds, target) + _check_data_shape_to_num_outputs(preds, target, num_outputs) + + return preds, target + + +def _spearman_corrcoef_compute(preds: Tensor, target: Tensor, eps: float = 1e-6) -> Tensor: + """Compute Spearman Correlation Coefficient. + + Args: + preds: Predicted tensor + target: Ground truth tensor + eps: Avoids ``ZeroDivisionError``. + + Example: + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> preds, target = _spearman_corrcoef_update(preds, target, num_outputs=1) + >>> _spearman_corrcoef_compute(preds, target) + tensor(1.0000) + + """ + if preds.ndim == 1: + preds = _rank_data(preds) + target = _rank_data(target) + else: + preds = torch.stack([_rank_data(p) for p in preds.T]).T + target = torch.stack([_rank_data(t) for t in target.T]).T + + preds_diff = preds - preds.mean(0) + target_diff = target - target.mean(0) + + cov = (preds_diff * target_diff).mean(0) + preds_std = torch.sqrt((preds_diff * preds_diff).mean(0)) + target_std = torch.sqrt((target_diff * target_diff).mean(0)) + + corrcoef = cov / (preds_std * target_std + eps) + return torch.clamp(corrcoef, -1.0, 1.0) + + +def spearman_corrcoef(preds: Tensor, target: Tensor) -> Tensor: + r"""Compute `spearmans rank correlation coefficient`_. + + .. math: + r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}} + + where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables x and y. Spearmans correlations + coefficient corresponds to the standard pearsons correlation coefficient calculated on the rank variables. + + Args: + preds: estimated scores + target: ground truth scores + + Example (single output regression): + >>> from torchmetrics.functional.regression import spearman_corrcoef + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> spearman_corrcoef(preds, target) + tensor(1.0000) + + Example (multi output regression): + >>> from torchmetrics.functional.regression import spearman_corrcoef + >>> target = torch.tensor([[3, -0.5], [2, 7]]) + >>> preds = torch.tensor([[2.5, 0.0], [2, 8]]) + >>> spearman_corrcoef(preds, target) + tensor([1.0000, 1.0000]) + + """ + preds, target = _spearman_corrcoef_update(preds, target, num_outputs=1 if preds.ndim == 1 else preds.shape[-1]) + return _spearman_corrcoef_compute(preds, target) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/symmetric_mape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/symmetric_mape.py new file mode 100644 index 0000000000000000000000000000000000000000..3fca98258c7fe3409097e632274e7db77b5accd4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/symmetric_mape.py @@ -0,0 +1,97 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _symmetric_mean_absolute_percentage_error_update( + preds: Tensor, + target: Tensor, + epsilon: float = 1.17e-06, +) -> tuple[Tensor, int]: + """Update and returns variables required to compute Symmetric Mean Absolute Percentage Error. + + Check for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + epsilon: Avoids ``ZeroDivisionError``. + + """ + _check_same_shape(preds, target) + + abs_diff = torch.abs(preds - target) + abs_per_error = abs_diff / torch.clamp(torch.abs(target) + torch.abs(preds), min=epsilon) + + sum_abs_per_error = 2 * torch.sum(abs_per_error) + + num_obs = target.numel() + + return sum_abs_per_error, num_obs + + +def _symmetric_mean_absolute_percentage_error_compute(sum_abs_per_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor: + """Compute Symmetric Mean Absolute Percentage Error. + + Args: + sum_abs_per_error: Sum of values of symmetric absolute percentage errors over all observations + ``(symmetric absolute percentage error = 2 * |target - prediction| / (target + prediction))`` + num_obs: Number of predictions or observations + + Example: + >>> target = torch.tensor([1, 10, 1e6]) + >>> preds = torch.tensor([0.9, 15, 1.2e6]) + >>> sum_abs_per_error, num_obs = _symmetric_mean_absolute_percentage_error_update(preds, target) + >>> _symmetric_mean_absolute_percentage_error_compute(sum_abs_per_error, num_obs) + tensor(0.2290) + + """ + return sum_abs_per_error / num_obs + + +def symmetric_mean_absolute_percentage_error(preds: Tensor, target: Tensor) -> Tensor: + r"""Compute symmetric mean absolute percentage error (SMAPE_). + + .. math:: \text{SMAPE} = \frac{2}{n}\sum_1^n\frac{| y_i - \hat{y_i} |}{max(| y_i | + | \hat{y_i} |, \epsilon)} + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + Args: + preds: estimated labels + target: ground truth labels + + Return: + Tensor with SMAPE. + + Example: + >>> from torchmetrics.functional.regression import symmetric_mean_absolute_percentage_error + >>> target = torch.tensor([1, 10, 1e6]) + >>> preds = torch.tensor([0.9, 15, 1.2e6]) + >>> symmetric_mean_absolute_percentage_error(preds, target) + tensor(0.2290) + + """ + sum_abs_per_error, num_obs = _symmetric_mean_absolute_percentage_error_update( + preds, + target, + ) + return _symmetric_mean_absolute_percentage_error_compute( + sum_abs_per_error, + num_obs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/tweedie_deviance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/tweedie_deviance.py new file mode 100644 index 0000000000000000000000000000000000000000..328829dffe36f0e26a859e58e1766380ec1fb809 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/tweedie_deviance.py @@ -0,0 +1,141 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.compute import _safe_xlogy + + +def _tweedie_deviance_score_update(preds: Tensor, targets: Tensor, power: float = 0.0) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute Deviance Score for the given power. + + Check for same shape of input tensors. + + Args: + preds: Predicted tensor + targets: Ground truth tensor + power: see :func:`tweedie_deviance_score` + + Example: + >>> targets = torch.tensor([1.0, 2.0, 3.0, 4.0]) + >>> preds = torch.tensor([4.0, 3.0, 2.0, 1.0]) + >>> _tweedie_deviance_score_update(preds, targets, power=2) + (tensor(4.8333), tensor(4)) + + """ + _check_same_shape(preds, targets) + + zero_tensor = torch.zeros(preds.shape, device=preds.device) + + if 0 < power < 1: + raise ValueError(f"Deviance Score is not defined for power={power}.") + + if power == 0: + deviance_score = torch.pow(targets - preds, exponent=2) + elif power == 1: + # Poisson distribution + if torch.any(preds <= 0) or torch.any(targets < 0): + raise ValueError( + f"For power={power}, 'preds' has to be strictly positive and 'targets' cannot be negative." + ) + + deviance_score = 2 * (_safe_xlogy(targets, targets / preds) + preds - targets) + elif power == 2: + # Gamma distribution + if torch.any(preds <= 0) or torch.any(targets <= 0): + raise ValueError(f"For power={power}, both 'preds' and 'targets' have to be strictly positive.") + + deviance_score = 2 * (torch.log(preds / targets) + (targets / preds) - 1) + else: + if power < 0: + if torch.any(preds <= 0): + raise ValueError(f"For power={power}, 'preds' has to be strictly positive.") + elif 1 < power < 2: + if torch.any(preds <= 0) or torch.any(targets < 0): + raise ValueError( + f"For power={power}, 'targets' has to be strictly positive and 'preds' cannot be negative." + ) + else: + if torch.any(preds <= 0) or torch.any(targets <= 0): + raise ValueError(f"For power={power}, both 'preds' and 'targets' have to be strictly positive.") + + term_1 = torch.pow(torch.max(targets, zero_tensor), 2 - power) / ((1 - power) * (2 - power)) + term_2 = targets * torch.pow(preds, 1 - power) / (1 - power) + term_3 = torch.pow(preds, 2 - power) / (2 - power) + deviance_score = 2 * (term_1 - term_2 + term_3) + + sum_deviance_score = torch.sum(deviance_score) + num_observations = torch.tensor(torch.numel(deviance_score), device=preds.device) + + return sum_deviance_score, num_observations + + +def _tweedie_deviance_score_compute(sum_deviance_score: Tensor, num_observations: Tensor) -> Tensor: + """Compute Deviance Score. + + Args: + sum_deviance_score: Sum of deviance scores accumulated until now. + num_observations: Number of observations encountered until now. + + Example: + >>> targets = torch.tensor([1.0, 2.0, 3.0, 4.0]) + >>> preds = torch.tensor([4.0, 3.0, 2.0, 1.0]) + >>> sum_deviance_score, num_observations = _tweedie_deviance_score_update(preds, targets, power=2) + >>> _tweedie_deviance_score_compute(sum_deviance_score, num_observations) + tensor(1.2083) + + """ + return sum_deviance_score / num_observations + + +def tweedie_deviance_score(preds: Tensor, targets: Tensor, power: float = 0.0) -> Tensor: + r"""Compute the `Tweedie Deviance Score`_. + + .. math:: + deviance\_score(\hat{y},y) = + \begin{cases} + (\hat{y} - y)^2, & \text{for }p=0\\ + 2 * (y * log(\frac{y}{\hat{y}}) + \hat{y} - y), & \text{for }p=1\\ + 2 * (log(\frac{\hat{y}}{y}) + \frac{y}{\hat{y}} - 1), & \text{for }p=2\\ + 2 * (\frac{(max(y,0))^{2 - p}}{(1 - p)(2 - p)} - \frac{y(\hat{y})^{1 - p}}{1 - p} + \frac{( + \hat{y})^{2 - p}}{2 - p}), & \text{otherwise} + \end{cases} + + where :math:`y` is a tensor of targets values, :math:`\hat{y}` is a tensor of predictions, and + :math:`p` is the `power`. + + Args: + preds: Predicted tensor with shape ``(N,...)`` + targets: Ground truth tensor with shape ``(N,...)`` + power: + - `power < 0` : Extreme stable distribution. (Requires: preds > 0.) + - `power = 0` : Normal distribution. (Requires: targets and preds can be any real numbers.) + - `power = 1` : Poisson distribution. (Requires: targets >= 0 and y_pred > 0.) + - `1 < p < 2` : Compound Poisson distribution. (Requires: targets >= 0 and preds > 0.) + - `power = 2` : Gamma distribution. (Requires: targets > 0 and preds > 0.) + - `power = 3` : Inverse Gaussian distribution. (Requires: targets > 0 and preds > 0.) + - `otherwise` : Positive stable distribution. (Requires: targets > 0 and preds > 0.) + + Example: + >>> from torchmetrics.functional.regression import tweedie_deviance_score + >>> targets = torch.tensor([1.0, 2.0, 3.0, 4.0]) + >>> preds = torch.tensor([4.0, 3.0, 2.0, 1.0]) + >>> tweedie_deviance_score(preds, targets, power=2) + tensor(1.2083) + + """ + sum_deviance_score, num_observations = _tweedie_deviance_score_update(preds, targets, power=power) + return _tweedie_deviance_score_compute(sum_deviance_score, num_observations) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..59612927f26bf8578e45b6a00fc1663c4326cca0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/utils.py @@ -0,0 +1,43 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torch import Tensor + + +def _check_data_shape_to_num_outputs( + preds: Tensor, target: Tensor, num_outputs: int, allow_1d_reshape: bool = False +) -> None: + """Check that predictions and target have the correct shape, else raise error. + + Args: + preds: Predicted tensor + target: Ground truth tensor + num_outputs: Number of outputs in multioutput setting + allow_1d_reshape: Allow that for num_outputs=1 that preds and target does not need to be 1d tensors. Instead + code that follows are expected to reshape the tensors to 1d. + + """ + if preds.ndim > 2 or target.ndim > 2: + raise ValueError( + f"Expected both predictions and target to be either 1- or 2-dimensional tensors," + f" but got {target.ndim} and {preds.ndim}." + ) + cond1 = False + if not allow_1d_reshape: + cond1 = num_outputs == 1 and not (preds.ndim == 1 or preds.shape[1] == 1) + cond2 = num_outputs > 1 and preds.ndim > 1 and num_outputs != preds.shape[1] + if cond1 or cond2: + raise ValueError( + f"Expected argument `num_outputs` to match the second dimension of input, but got {num_outputs}" + f" and {preds.shape[1]}." + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/wmape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/wmape.py new file mode 100644 index 0000000000000000000000000000000000000000..1781f306608a6a65f747f83e9f09b66105972b54 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/wmape.py @@ -0,0 +1,84 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_same_shape + + +def _weighted_mean_absolute_percentage_error_update( + preds: Tensor, + target: Tensor, +) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute Weighted Absolute Percentage Error. + + Check for same shape of input tensors. + + Args: + preds: Predicted tensor + target: Ground truth tensor + + """ + _check_same_shape(preds, target) + + sum_abs_error = (preds - target).abs().sum() + sum_scale = target.abs().sum() + + return sum_abs_error, sum_scale + + +def _weighted_mean_absolute_percentage_error_compute( + sum_abs_error: Tensor, + sum_scale: Tensor, + epsilon: float = 1.17e-06, +) -> Tensor: + """Compute Weighted Absolute Percentage Error. + + Args: + sum_abs_error: scalar with sum of absolute errors + sum_scale: scalar with sum of target values + epsilon: small float to prevent division by zero + + """ + return sum_abs_error / torch.clamp(sum_scale, min=epsilon) + + +def weighted_mean_absolute_percentage_error(preds: Tensor, target: Tensor) -> Tensor: + r"""Compute weighted mean absolute percentage error (`WMAPE`_). + + The output of WMAPE metric is a non-negative floating point, where the optimal value is 0. It is computes as: + + .. math:: + \text{WMAPE} = \frac{\sum_{t=1}^n | y_t - \hat{y}_t | }{\sum_{t=1}^n |y_t| } + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + Args: + preds: estimated labels + target: ground truth labels + + Return: + Tensor with WMAPE. + + Example: + >>> from torch import randn + >>> preds = randn(20,) + >>> target = randn(20,) + >>> weighted_mean_absolute_percentage_error(preds, target) + tensor(1.3967) + + """ + sum_abs_error, sum_scale = _weighted_mean_absolute_percentage_error_update(preds, target) + return _weighted_mean_absolute_percentage_error_compute(sum_abs_error, sum_scale) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..069b6a3089cd053f05067c252face8c5d67a4148 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/__init__.py @@ -0,0 +1,36 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.functional.retrieval.auroc import retrieval_auroc +from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision +from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out +from torchmetrics.functional.retrieval.hit_rate import retrieval_hit_rate +from torchmetrics.functional.retrieval.ndcg import retrieval_normalized_dcg +from torchmetrics.functional.retrieval.precision import retrieval_precision +from torchmetrics.functional.retrieval.precision_recall_curve import retrieval_precision_recall_curve +from torchmetrics.functional.retrieval.r_precision import retrieval_r_precision +from torchmetrics.functional.retrieval.recall import retrieval_recall +from torchmetrics.functional.retrieval.reciprocal_rank import retrieval_reciprocal_rank + +__all__ = [ + "retrieval_auroc", + "retrieval_average_precision", + "retrieval_fall_out", + "retrieval_hit_rate", + "retrieval_normalized_dcg", + "retrieval_precision", + "retrieval_precision_recall_curve", + "retrieval_r_precision", + "retrieval_recall", + "retrieval_reciprocal_rank", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/_deprecated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..6284470d1b2fd97164c98b8eccf0006add39c8ca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/_deprecated.py @@ -0,0 +1,149 @@ +from typing import Optional + +from torch import Tensor + +from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision +from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out +from torchmetrics.functional.retrieval.hit_rate import retrieval_hit_rate +from torchmetrics.functional.retrieval.ndcg import retrieval_normalized_dcg +from torchmetrics.functional.retrieval.precision import retrieval_precision +from torchmetrics.functional.retrieval.precision_recall_curve import retrieval_precision_recall_curve +from torchmetrics.functional.retrieval.r_precision import retrieval_r_precision +from torchmetrics.functional.retrieval.recall import retrieval_recall +from torchmetrics.functional.retrieval.reciprocal_rank import retrieval_reciprocal_rank +from torchmetrics.utilities.prints import _deprecated_root_import_func + + +def _retrieval_average_precision(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> _retrieval_average_precision(preds, target) + tensor(0.8333) + + """ + _deprecated_root_import_func("retrieval_average_precision", "retrieval") + return retrieval_average_precision(preds=preds, target=target, top_k=top_k) + + +def _retrieval_fall_out(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> _retrieval_fall_out(preds, target, top_k=2) + tensor(1.) + + """ + _deprecated_root_import_func("retrieval_fall_out", "retrieval") + return retrieval_fall_out(preds=preds, target=target, top_k=top_k) + + +def _retrieval_hit_rate(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> _retrieval_hit_rate(preds, target, top_k=2) + tensor(1.) + + """ + _deprecated_root_import_func("retrieval_hit_rate", "retrieval") + return retrieval_hit_rate(preds=preds, target=target, top_k=top_k) + + +def _retrieval_normalized_dcg(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([.1, .2, .3, 4, 70]) + >>> target = tensor([10, 0, 0, 1, 5]) + >>> _retrieval_normalized_dcg(preds, target) + tensor(0.6957) + + """ + _deprecated_root_import_func("retrieval_normalized_dcg", "retrieval") + return retrieval_normalized_dcg(preds=preds, target=target, top_k=top_k) + + +def _retrieval_precision( + preds: Tensor, target: Tensor, top_k: Optional[int] = None, adaptive_k: bool = False +) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> _retrieval_precision(preds, target, top_k=2) + tensor(0.5000) + + """ + _deprecated_root_import_func("retrieval_precision", "retrieval") + return retrieval_precision(preds=preds, target=target, top_k=top_k, adaptive_k=adaptive_k) + + +def _retrieval_precision_recall_curve( + preds: Tensor, target: Tensor, max_k: Optional[int] = None, adaptive_k: bool = False +) -> tuple[Tensor, Tensor, Tensor]: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> precisions, recalls, top_k = _retrieval_precision_recall_curve(preds, target, max_k=2) + >>> precisions + tensor([1.0000, 0.5000]) + >>> recalls + tensor([0.5000, 0.5000]) + >>> top_k + tensor([1, 2]) + + """ + _deprecated_root_import_func("retrieval_precision_recall_curve", "retrieval") + return retrieval_precision_recall_curve(preds=preds, target=target, max_k=max_k, adaptive_k=adaptive_k) + + +def _retrieval_r_precision(preds: Tensor, target: Tensor) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> _retrieval_r_precision(preds, target) + tensor(0.5000) + + """ + _deprecated_root_import_func("retrieval_r_precision", "retrieval") + return retrieval_r_precision(preds=preds, target=target) + + +def _retrieval_recall(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> _retrieval_recall(preds, target, top_k=2) + tensor(0.5000) + + """ + _deprecated_root_import_func("retrieval_recall", "retrieval") + return retrieval_recall(preds=preds, target=target, top_k=top_k) + + +def _retrieval_reciprocal_rank(preds: Tensor, target: Tensor) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([False, True, False]) + >>> _retrieval_reciprocal_rank(preds, target) + tensor(0.5000) + + """ + _deprecated_root_import_func("retrieval_reciprocal_rank", "retrieval") + return retrieval_reciprocal_rank(preds=preds, target=target) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/auroc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/auroc.py new file mode 100644 index 0000000000000000000000000000000000000000..e0dc68794db34f46c9458ab21407d721a67ff694 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/auroc.py @@ -0,0 +1,64 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +from torch import Tensor, tensor + +from torchmetrics.functional.classification.auroc import binary_auroc +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_auroc( + preds: Tensor, target: Tensor, top_k: Optional[int] = None, max_fpr: Optional[float] = None +) -> Tensor: + """Compute area under the receiver operating characteristic curve (AUROC) for information retrieval. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + top_k: consider only the top k elements (default: ``None``, which considers them all) + max_fpr: If not ``None``, calculates standardized partial AUC over the range ``[0, max_fpr]``. + + Return: + a single-value tensor with the auroc value of the predictions ``preds`` w.r.t. the labels ``target``. + + Raises: + ValueError: + If ``top_k`` is not ``None`` or an integer larger than 0. + + Example: + >>> from torchmetrics.functional.retrieval import retrieval_auroc + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> retrieval_auroc(preds, target) + tensor(0.5000) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + top_k = top_k or preds.shape[-1] + if not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + + top_k_idx = preds.topk(min(top_k, preds.shape[-1]), sorted=True, dim=-1)[1] + target = target[top_k_idx] + if (0 not in target) or (1 not in target): + return tensor(0.0, device=preds.device, dtype=preds.dtype) + + preds = preds[top_k_idx] + return binary_auroc(preds, target.int(), max_fpr=max_fpr) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/average_precision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/average_precision.py new file mode 100644 index 0000000000000000000000000000000000000000..9631c09874567f889d41f6ead1e179fda4f2b758 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/average_precision.py @@ -0,0 +1,62 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor, tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_average_precision(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Compute average precision (for information retrieval), as explained in `IR Average precision`_. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + top_k: consider only the top k elements (default: ``None``, which considers them all) + + Return: + a single-value tensor with the average precision (AP) of the predictions ``preds`` w.r.t. the labels ``target``. + + Raises: + ValueError: + If ``top_k`` is not ``None`` or an integer larger than 0. + + Example: + >>> from torchmetrics.functional.retrieval import retrieval_average_precision + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> retrieval_average_precision(preds, target) + tensor(0.8333) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + top_k = top_k or preds.shape[-1] + if not isinstance(top_k, int) and top_k <= 0: + raise ValueError(f"Argument ``top_k`` has to be a positive integer or None, but got {top_k}.") + + target = torch.where(preds > 0, target, torch.zeros_like(target)) + target = target[preds.topk(min(top_k, preds.shape[-1]), sorted=True, dim=-1)[1]] + + if not target.sum(): + return tensor(0.0, device=preds.device) + + positions = torch.arange(1, len(target) + 1, device=target.device, dtype=torch.float32)[target > 0] + return torch.div((torch.arange(len(positions), device=positions.device, dtype=torch.float32) + 1), positions).mean() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/fall_out.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/fall_out.py new file mode 100644 index 0000000000000000000000000000000000000000..65665e86f6cb772eb720a3091674ff213dec5eda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/fall_out.py @@ -0,0 +1,64 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor, tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_fall_out(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Compute the Fall-out for information retrieval, as explained in `IR Fall-out`_. + + Fall-out is the fraction of non-relevant documents retrieved among all the non-relevant documents. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. If you want to measure Fall-out@K, ``top_k`` must be a positive integer. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + top_k: consider only the top k elements (default: ``None``, which considers them all) + + Returns: + A single-value tensor with the fall-out (at ``top_k``) of the predictions ``preds`` w.r.t. the labels ``target`` + + Raises: + ValueError: + If ``top_k`` parameter is not `None` or an integer larger than 0 + + Example: + >>> from torchmetrics.functional import retrieval_fall_out + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> retrieval_fall_out(preds, target, top_k=2) + tensor(1.) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + top_k = preds.shape[-1] if top_k is None else top_k + + if not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + + target = 1 - target # we want to compute the probability of getting a non-relevant doc among all non-relevant docs + + if not target.sum(): + return tensor(0.0, device=preds.device) + + relevant = target[torch.argsort(preds, dim=-1, descending=True)][:top_k].sum().float() + return relevant / target.sum() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/hit_rate.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/hit_rate.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd33305a7f3f774bc6f2a99a693f82ebfa5bdec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/hit_rate.py @@ -0,0 +1,61 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_hit_rate(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Compute the hit rate for information retrieval. + + The hit rate is 1.0 if there is at least one relevant document among all the top `k` retrieved documents. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. If you want to measure HitRate@K, ``top_k`` must be a positive integer. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + top_k: consider only the top k elements (default: `None`, which considers them all) + + Returns: + A single-value tensor with the hit rate (at ``top_k``) of the predictions ``preds`` w.r.t. the labels + ``target``. + + Raises: + ValueError: + If ``top_k`` parameter is not `None` or an integer larger than 0 + + Example: + >>> from torch import tensor + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> retrieval_hit_rate(preds, target, top_k=2) + tensor(1.) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + if top_k is None: + top_k = preds.shape[-1] + + if not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + + relevant = target[torch.argsort(preds, dim=-1, descending=True)][:top_k].sum() + return (relevant > 0).float() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/ndcg.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/ndcg.py new file mode 100644 index 0000000000000000000000000000000000000000..d381718c79377813ccb8f4cbab09586396b1158a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/ndcg.py @@ -0,0 +1,113 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def _tie_average_dcg(target: Tensor, preds: Tensor, discount_cumsum: Tensor) -> Tensor: + """Translated version of sklearns `_tie_average_dcg` function. + + Args: + target: ground truth about each document relevance. + preds: estimated probabilities of each document to be relevant. + discount_cumsum: cumulative sum of the discount. + + Returns: + The cumulative gain of the tied elements. + + """ + _, inv, counts = torch.unique(-preds, return_inverse=True, return_counts=True) + ranked = torch.zeros_like(counts, dtype=torch.float32) + ranked.scatter_add_(0, inv, target.to(dtype=ranked.dtype)) + ranked = ranked / counts + groups = counts.cumsum(dim=0) - 1 + discount_sums = torch.zeros_like(counts, dtype=torch.float32) + discount_sums[0] = discount_cumsum[groups[0]] + discount_sums[1:] = discount_cumsum[groups].diff() + return (ranked * discount_sums).sum() + + +def _dcg_sample_scores(target: Tensor, preds: Tensor, top_k: int, ignore_ties: bool) -> Tensor: + """Translated version of sklearns `_dcg_sample_scores` function. + + Args: + target: ground truth about each document relevance. + preds: estimated probabilities of each document to be relevant. + top_k: consider only the top k elements + ignore_ties: If True, ties are ignored. If False, ties are averaged. + + Returns: + The cumulative gain + + """ + discount = 1.0 / (torch.log2(torch.arange(target.shape[-1], device=target.device) + 2.0)) + discount[top_k:] = 0.0 + + if ignore_ties: + ranking = preds.argsort(descending=True) + ranked = target[ranking] + cumulative_gain = (discount * ranked).sum() + else: + discount_cumsum = discount.cumsum(dim=-1) + cumulative_gain = _tie_average_dcg(target, preds, discount_cumsum) + return cumulative_gain + + +def retrieval_normalized_dcg(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Compute `Normalized Discounted Cumulative Gain`_ (for information retrieval). + + ``preds`` and ``target`` should be of the same shape and live on the same device. + ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document relevance. + top_k: consider only the top k elements (default: ``None``, which considers them all) + + Return: + A single-value tensor with the nDCG of the predictions ``preds`` w.r.t. the labels ``target``. + + Raises: + ValueError: + If ``top_k`` parameter is not `None` or an integer larger than 0 + + Example: + >>> from torchmetrics.functional.retrieval import retrieval_normalized_dcg + >>> preds = torch.tensor([.1, .2, .3, 4, 70]) + >>> target = torch.tensor([10, 0, 0, 1, 5]) + >>> retrieval_normalized_dcg(preds, target) + tensor(0.6957) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target, allow_non_binary_target=True) + + top_k = preds.shape[-1] if top_k is None else top_k + + if not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + + gain = _dcg_sample_scores(target, preds, top_k, ignore_ties=False) + normalized_gain = _dcg_sample_scores(target, target, top_k, ignore_ties=True) + + # filter undefined scores + all_irrelevant = normalized_gain == 0 + gain[all_irrelevant] = 0 + gain[~all_irrelevant] /= normalized_gain[~all_irrelevant] + + return gain.mean() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/precision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..09feca9839a6f728c7c7f32b50d84c201f3d7c60 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/precision.py @@ -0,0 +1,71 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor, tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_precision(preds: Tensor, target: Tensor, top_k: Optional[int] = None, adaptive_k: bool = False) -> Tensor: + """Compute the precision metric for information retrieval. + + Precision is the fraction of relevant documents among all the retrieved documents. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. If you want to measure Precision@K, ``top_k`` must be a positive integer. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + top_k: consider only the top k elements (default: ``None``, which considers them all) + adaptive_k: adjust `k` to `min(k, number of documents)` for each query + + Returns: + A single-value tensor with the precision (at ``top_k``) of the predictions ``preds`` w.r.t. the labels + ``target``. + + Raises: + ValueError: + If ``top_k`` is not `None` or an integer larger than 0. + ValueError: + If ``adaptive_k`` is not boolean. + + Example: + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> retrieval_precision(preds, target, top_k=2) + tensor(0.5000) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + if not isinstance(adaptive_k, bool): + raise ValueError("`adaptive_k` has to be a boolean") + + if top_k is None or (adaptive_k and top_k > preds.shape[-1]): + top_k = preds.shape[-1] + + if not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + + if not target.sum(): + return tensor(0.0, device=preds.device) + + target_filtered = torch.where(preds > 0, target, torch.zeros_like(target)) + relevant = target_filtered[preds.topk(min(top_k, preds.shape[-1]), dim=-1)[1]].sum().float() + + return relevant / top_k diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/precision_recall_curve.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/precision_recall_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..269dca04016aed53573d62afcec4841521189ed2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/precision_recall_curve.py @@ -0,0 +1,100 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor +from torch.nn.functional import pad + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs +from torchmetrics.utilities.data import _cumsum + + +def retrieval_precision_recall_curve( + preds: Tensor, target: Tensor, max_k: Optional[int] = None, adaptive_k: bool = False +) -> tuple[Tensor, Tensor, Tensor]: + """Compute precision-recall pairs for different k (from 1 to `max_k`). + + In a ranked retrieval context, appropriate sets of retrieved documents are naturally given by + the top k retrieved documents. + + Recall is the fraction of relevant documents retrieved among all the relevant documents. + Precision is the fraction of relevant documents among all the retrieved documents. + + For each such set, precision and recall values can be plotted to give a recall-precision + curve. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + max_k: Calculate recall and precision for all possible top k from 1 to max_k + (default: `None`, which considers all possible top k) + adaptive_k: adjust `max_k` to `min(max_k, number of documents)` for each query + + Returns: + Tensor with the precision values for each k (at ``top_k``) from 1 to `max_k` + Tensor with the recall values for each k (at ``top_k``) from 1 to `max_k` + Tensor with all possibles k + + Raises: + ValueError: + If ``max_k`` is not `None` or an integer larger than 0. + ValueError: + If ``adaptive_k`` is not boolean. + + Example: + >>> from torch import tensor + >>> from torchmetrics.functional import retrieval_precision_recall_curve + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> precisions, recalls, top_k = retrieval_precision_recall_curve(preds, target, max_k=2) + >>> precisions + tensor([1.0000, 0.5000]) + >>> recalls + tensor([0.5000, 0.5000]) + >>> top_k + tensor([1, 2]) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + if not isinstance(adaptive_k, bool): + raise ValueError("`adaptive_k` has to be a boolean") + + if max_k is None: + max_k = preds.shape[-1] + + if not (isinstance(max_k, int) and max_k > 0): + raise ValueError("`max_k` has to be a positive integer or None") + + if adaptive_k and max_k > preds.shape[-1]: + topk = torch.arange(1, preds.shape[-1] + 1, device=preds.device) + topk = pad(topk, (0, max_k - preds.shape[-1]), "constant", float(preds.shape[-1])) + else: + topk = torch.arange(1, max_k + 1, device=preds.device) + + if not target.sum(): + return torch.zeros(max_k, device=preds.device), torch.zeros(max_k, device=preds.device), topk + + relevant = target[preds.topk(min(max_k, preds.shape[-1]), dim=-1)[1]].float() + relevant = _cumsum(pad(relevant, (0, max(0, max_k - len(relevant))), "constant", 0.0), dim=0) + + recall = relevant / target.sum() + precision = relevant / topk + + return precision, recall, topk diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/r_precision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/r_precision.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb81b487ea2e2c61dcda8281d7cd65390de7497 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/r_precision.py @@ -0,0 +1,51 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from torch import Tensor, tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_r_precision(preds: Tensor, target: Tensor) -> Tensor: + """Compute the r-precision metric for information retrieval. + + R-Precision is the fraction of relevant documents among all the top ``k`` retrieved documents where ``k`` is equal + to the total number of relevant documents. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. If you want to measure Precision@K, ``top_k`` must be a positive integer. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + + Returns: + A single-value tensor with the r-precision of the predictions ``preds`` w.r.t. the labels ``target``. + + Example: + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> retrieval_r_precision(preds, target) + tensor(0.5000) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + relevant_number = target.sum() + if not relevant_number: + return tensor(0.0, device=preds.device) + + relevant = target[torch.argsort(preds, dim=-1, descending=True)][:relevant_number].sum().float() + return relevant / relevant_number diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/recall.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/recall.py new file mode 100644 index 0000000000000000000000000000000000000000..0f5398918f7c78c3712ce0b74805ffc53fc82595 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/recall.py @@ -0,0 +1,65 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor, tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_recall(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Compute the recall metric for information retrieval. + + Recall is the fraction of relevant documents retrieved among all the relevant documents. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. If you want to measure Recall@K, ``top_k`` must be a positive integer. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + top_k: consider only the top k elements (default: `None`, which considers them all) + + Returns: + A single-value tensor with the recall (at ``top_k``) of the predictions ``preds`` w.r.t. the labels ``target``. + + Raises: + ValueError: + If ``top_k`` parameter is not `None` or an integer larger than 0 + + Example: + >>> from torchmetrics.functional import retrieval_recall + >>> preds = tensor([0.2, 0.3, 0.5]) + >>> target = tensor([True, False, True]) + >>> retrieval_recall(preds, target, top_k=2) + tensor(0.5000) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + if top_k is None: + top_k = preds.shape[-1] + + if not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + + if not target.sum(): + return tensor(0.0, device=preds.device) + + target_filtered = torch.where(preds > 0, target, torch.zeros_like(target)) + relevant = target_filtered[torch.argsort(preds, dim=-1, descending=True)][:top_k].sum().float() + + return relevant / target.sum() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/reciprocal_rank.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/reciprocal_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..1909c4f3f5d918d1d0c6a94ceedbc2ec90e29424 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/retrieval/reciprocal_rank.py @@ -0,0 +1,62 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor, tensor + +from torchmetrics.utilities.checks import _check_retrieval_functional_inputs + + +def retrieval_reciprocal_rank(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor: + """Compute reciprocal rank (for information retrieval). See `Mean Reciprocal Rank`_. + + ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, + 0 is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, + otherwise an error is raised. + + Args: + preds: estimated probabilities of each document to be relevant. + target: ground truth about each document being relevant or not. + top_k: consider only the top k elements (default: ``None``, which considers them all) + + Return: + a single-value tensor with the reciprocal rank (RR) of the predictions ``preds`` wrt the labels ``target``. + + Raises: + ValueError: + If ``top_k`` is not ``None`` or an integer larger than 0. + + Example: + >>> from torchmetrics.functional.retrieval import retrieval_reciprocal_rank + >>> preds = torch.tensor([0.2, 0.3, 0.5]) + >>> target = torch.tensor([False, True, False]) + >>> retrieval_reciprocal_rank(preds, target) + tensor(0.5000) + + """ + preds, target = _check_retrieval_functional_inputs(preds, target) + + top_k = top_k or preds.shape[-1] + if not isinstance(top_k, int) and top_k <= 0: + raise ValueError(f"Argument ``top_k`` has to be a positive integer or None, but got {top_k}.") + + target = torch.where(preds > 0, target, torch.zeros_like(target)) + target = target[preds.topk(min(top_k, preds.shape[-1]), sorted=True, dim=-1)[1]] + + if not target.sum(): + return tensor(0.0, device=preds.device) + + position = torch.nonzero(target).view(-1) + return 1.0 / (position[0] + 1.0) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f65ea00d0fb7b2b45412693f5477e3e1b4f09a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/__init__.py @@ -0,0 +1,19 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.functional.segmentation.dice import dice_score +from torchmetrics.functional.segmentation.generalized_dice import generalized_dice_score +from torchmetrics.functional.segmentation.hausdorff_distance import hausdorff_distance +from torchmetrics.functional.segmentation.mean_iou import mean_iou + +__all__ = ["dice_score", "generalized_dice_score", "hausdorff_distance", "mean_iou"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/dice.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/dice.py new file mode 100644 index 0000000000000000000000000000000000000000..d402ca6724655d4bc2e498faceec79457627ea49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/dice.py @@ -0,0 +1,181 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.segmentation.utils import _segmentation_inputs_format +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.compute import _safe_divide + + +def _dice_score_validate_args( + num_classes: int, + include_background: bool, + average: Optional[Literal["micro", "macro", "weighted", "none"]] = "micro", + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", + aggregation_level: Optional[Literal["samplewise", "global"]] = "samplewise", +) -> None: + """Validate the arguments of the metric.""" + if not isinstance(num_classes, int) or num_classes <= 0: + raise ValueError(f"Expected argument `num_classes` must be a positive integer, but got {num_classes}.") + if not isinstance(include_background, bool): + raise ValueError(f"Expected argument `include_background` must be a boolean, but got {include_background}.") + allowed_average = ["micro", "macro", "weighted", "none"] + if average is not None and average not in allowed_average: + raise ValueError(f"Expected argument `average` to be one of {allowed_average} or None, but got {average}.") + if input_format not in ["one-hot", "index", "mixed"]: + raise ValueError( + f"Expected argument `input_format` to be one of 'one-hot', 'index', 'mixed', but got {input_format}." + ) + if aggregation_level not in ("samplewise", "global"): + raise ValueError( + f"Expected argument `aggregation_level` to be one of `samplewise`, `global`, but got {aggregation_level}" + ) + + +def _dice_score_update( + preds: Tensor, + target: Tensor, + num_classes: int, + include_background: bool, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> tuple[Tensor, Tensor, Tensor]: + """Update the state with the current prediction and target.""" + preds, target = _segmentation_inputs_format(preds, target, include_background, num_classes, input_format) + + reduce_axis = list(range(2, target.ndim)) + intersection = torch.sum(preds * target, dim=reduce_axis) + target_sum = torch.sum(target, dim=reduce_axis) + pred_sum = torch.sum(preds, dim=reduce_axis) + + numerator = 2 * intersection + denominator = pred_sum + target_sum + support = target_sum + return numerator, denominator, support + + +def _dice_score_compute( + numerator: Tensor, + denominator: Tensor, + average: Optional[Literal["micro", "macro", "weighted", "none"]] = "micro", + aggregation_level: Optional[Literal["samplewise", "global"]] = "samplewise", + support: Optional[Tensor] = None, +) -> Tensor: + """Compute the Dice score from the numerator and denominator.""" + if aggregation_level == "global": + numerator = torch.sum(numerator, dim=0).unsqueeze(0) + denominator = torch.sum(denominator, dim=0).unsqueeze(0) + support = torch.sum(support, dim=0) if support is not None else None + + if average == "micro": + numerator = torch.sum(numerator, dim=-1) + denominator = torch.sum(denominator, dim=-1) + return _safe_divide(numerator, denominator, zero_division="nan") + + dice = _safe_divide(numerator, denominator, zero_division="nan") + if average == "macro": + return torch.nanmean(dice, dim=-1) + if average == "weighted": + if not isinstance(support, torch.Tensor): + raise ValueError(f"Expected argument `support` to be a tensor, got: {type(support)}.") + weights = _safe_divide(support, torch.sum(support, dim=-1, keepdim=True), zero_division="nan") + nan_mask = dice.isnan().all(dim=-1) + dice = torch.nansum(dice * weights, dim=-1) + dice[nan_mask] = torch.nan + return dice + if average in ("none", None): + return dice + raise ValueError(f"Invalid value for `average`: {average}.") + + +def dice_score( + preds: Tensor, + target: Tensor, + num_classes: int, + include_background: bool = True, + average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro", + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", + aggregation_level: Optional[Literal["samplewise", "global"]] = "samplewise", +) -> Tensor: + """Compute the Dice score for semantic segmentation. + + Args: + preds: Predictions from model + target: Ground truth values + num_classes: Number of classes + include_background: Whether to include the background class in the computation + average: The method to average the dice score. Options are ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"`` + or ``None``. This determines how to average the dice score across different classes. + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor + aggregation_level: The level at which to aggregate the dice score. Options are ``"samplewise"`` or ``"global"``. + For ``"samplewise"`` the dice score is computed for each sample and then averaged. For ``"global"`` the dice + score is computed globally over all samples. + + Returns: + The Dice score. + + Example (with one-hot encoded tensors): + >>> from torch import randint + >>> from torchmetrics.functional.segmentation import dice_score + >>> _ = torch.manual_seed(42) + >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> # dice score micro averaged over all classes + >>> dice_score(preds, target, num_classes=5, average="micro") + tensor([0.4842, 0.4968, 0.5053, 0.4902]) + >>> # dice score per sample and class + >>> dice_score(preds, target, num_classes=5, average="none") + tensor([[0.4724, 0.5185, 0.4710, 0.5062, 0.4500], + [0.4571, 0.4980, 0.5191, 0.4380, 0.5649], + [0.5428, 0.4904, 0.5358, 0.4830, 0.4724], + [0.4715, 0.4925, 0.4797, 0.5267, 0.4788]]) + >>> # global dice score over all samples with macro averaging + >>> dice_score(preds, target, num_classes=5, average="macro", aggregation_level="global") + tensor([0.4942]) + + Example (with index tensors): + >>> from torch import randint + >>> from torchmetrics.functional.segmentation import dice_score + >>> _ = torch.manual_seed(42) + >>> preds = randint(0, 5, (4, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 5, (4, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> # dice score micro averaged over all classes + >>> dice_score(preds, target, num_classes=5, average="micro", input_format="index") + tensor([0.2031, 0.1914, 0.2266, 0.1641]) + >>> # dice score per sample and class + >>> dice_score(preds, target, num_classes=5, average="none", input_format="index") + tensor([[0.1731, 0.1667, 0.2400, 0.2424, 0.1947], + [0.2245, 0.2247, 0.2321, 0.1132, 0.1682], + [0.2500, 0.2476, 0.1887, 0.1818, 0.2718], + [0.1308, 0.1800, 0.1980, 0.1607, 0.1522]]) + >>> # global dice score over all samples with macro averaging + >>> dice_score(preds, target, num_classes=5, average="macro", aggregation_level="global", input_format="index") + tensor([0.1965]) + + """ + if average == "micro": + rank_zero_warn( + "dice_score metric currently defaults to `average=micro`, but will change to" + "`average=macro` in the v1.9 release." + " If you've explicitly set this parameter, you can ignore this warning.", + UserWarning, + ) + _dice_score_validate_args(num_classes, include_background, average, input_format, aggregation_level) + numerator, denominator, support = _dice_score_update(preds, target, num_classes, include_background, input_format) + return _dice_score_compute(numerator, denominator, average, aggregation_level=aggregation_level, support=support) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/generalized_dice.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/generalized_dice.py new file mode 100644 index 0000000000000000000000000000000000000000..1a110980a320a89e777604c9179da9b372e418ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/generalized_dice.py @@ -0,0 +1,152 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Tuple + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.segmentation.utils import _segmentation_inputs_format +from torchmetrics.utilities.compute import _safe_divide + + +def _generalized_dice_validate_args( + num_classes: int, + include_background: bool, + per_class: bool, + weight_type: Literal["square", "simple", "linear"], + input_format: Literal["one-hot", "index", "mixed"], +) -> None: + """Validate the arguments of the metric.""" + if not isinstance(num_classes, int) or num_classes <= 0: + raise ValueError(f"Expected argument `num_classes` must be a positive integer, but got {num_classes}.") + if not isinstance(include_background, bool): + raise ValueError(f"Expected argument `include_background` must be a boolean, but got {include_background}.") + if not isinstance(per_class, bool): + raise ValueError(f"Expected argument `per_class` must be a boolean, but got {per_class}.") + if weight_type not in ["square", "simple", "linear"]: + raise ValueError( + f"Expected argument `weight_type` to be one of 'square', 'simple', 'linear', but got {weight_type}." + ) + if input_format not in ["one-hot", "index", "mixed"]: + raise ValueError( + f"Expected argument `input_format` to be one of 'one-hot', 'index', 'mixed', but got {input_format}." + ) + + +def _generalized_dice_update( + preds: Tensor, + target: Tensor, + num_classes: int, + include_background: bool, + weight_type: Literal["square", "simple", "linear"] = "square", + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> Tuple[Tensor, Tensor]: + """Update the state with the current prediction and target.""" + preds, target = _segmentation_inputs_format(preds, target, include_background, num_classes, input_format) + + reduce_axis = list(range(2, target.ndim)) + intersection = torch.sum(preds * target, dim=reduce_axis) + target_sum = torch.sum(target, dim=reduce_axis) + pred_sum = torch.sum(preds, dim=reduce_axis) + cardinality = target_sum + pred_sum + if weight_type == "simple": + weights = 1.0 / target_sum + elif weight_type == "linear": + weights = torch.ones_like(target_sum) + elif weight_type == "square": + weights = 1.0 / (target_sum**2) + else: + raise ValueError( + f"Expected argument `weight_type` to be one of 'simple', 'linear', 'square', but got {weight_type}." + ) + + w_shape = weights.shape + weights_flatten = weights.flatten() + infs = torch.isinf(weights_flatten) + weights_flatten[infs] = 0 + w_max = torch.max(weights, 0).values.repeat(w_shape[0], 1).T.flatten() + weights_flatten[infs] = w_max[infs] + weights = weights_flatten.reshape(w_shape) + + numerator = 2.0 * intersection * weights + denominator = cardinality * weights + return numerator, denominator + + +def _generalized_dice_compute(numerator: Tensor, denominator: Tensor, per_class: bool = True) -> Tensor: + """Compute the generalized dice score.""" + if not per_class: + numerator = torch.sum(numerator, 1) + denominator = torch.sum(denominator, 1) + return _safe_divide(numerator, denominator) + + +def generalized_dice_score( + preds: Tensor, + target: Tensor, + num_classes: int, + include_background: bool = True, + per_class: bool = False, + weight_type: Literal["square", "simple", "linear"] = "square", + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> Tensor: + """Compute the Generalized Dice Score for semantic segmentation. + + Args: + preds: Predictions from model + target: Ground truth values + num_classes: Number of classes + include_background: Whether to include the background class in the computation + per_class: Whether to compute the score for each class separately, else average over all classes + weight_type: Type of weight factor to apply to the classes. One of ``"square"``, ``"simple"``, or ``"linear"`` + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor + + Returns: + The Generalized Dice Score + + Example (with one-hot encoded tensors): + >>> from torch import randint + >>> from torchmetrics.functional.segmentation import generalized_dice_score + >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> generalized_dice_score(preds, target, num_classes=5) + tensor([0.4830, 0.4935, 0.5044, 0.4880]) + >>> generalized_dice_score(preds, target, num_classes=5, per_class=True) + tensor([[0.4724, 0.5185, 0.4710, 0.5062, 0.4500], + [0.4571, 0.4980, 0.5191, 0.4380, 0.5649], + [0.5428, 0.4904, 0.5358, 0.4830, 0.4724], + [0.4715, 0.4925, 0.4797, 0.5267, 0.4788]]) + + Example (with index tensors): + >>> from torch import randint + >>> from torchmetrics.functional.segmentation import generalized_dice_score + >>> preds = randint(0, 5, (4, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 5, (4, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> generalized_dice_score(preds, target, num_classes=5, input_format="index") + tensor([0.1991, 0.1971, 0.2350, 0.2216]) + >>> generalized_dice_score(preds, target, num_classes=5, per_class=True, input_format="index") + tensor([[0.1714, 0.2500, 0.1304, 0.2524, 0.2069], + [0.1837, 0.2162, 0.0962, 0.2692, 0.1895], + [0.3866, 0.1348, 0.2526, 0.2301, 0.2083], + [0.1978, 0.2804, 0.1714, 0.1915, 0.2783]]) + + """ + _generalized_dice_validate_args(num_classes, include_background, per_class, weight_type, input_format) + numerator, denominator = _generalized_dice_update( + preds, target, num_classes, include_background, weight_type, input_format + ) + return _generalized_dice_compute(numerator, denominator, per_class) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/hausdorff_distance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/hausdorff_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..8adbd541d781dfe27d58a4ab1d04b91b2928d2d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/hausdorff_distance.py @@ -0,0 +1,107 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Literal, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.segmentation.utils import _segmentation_inputs_format, edge_surface_distance + + +def _hausdorff_distance_validate_args( + num_classes: int, + include_background: bool, + distance_metric: Literal["euclidean", "chessboard", "taxicab"] = "euclidean", + spacing: Optional[Union[Tensor, list[float]]] = None, + directed: bool = False, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> None: + """Validate the arguments of `hausdorff_distance` function.""" + if num_classes <= 0: + raise ValueError(f"Expected argument `num_classes` must be a positive integer, but got {num_classes}.") + if not isinstance(include_background, bool): + raise ValueError(f"Expected argument `include_background` must be a boolean, but got {include_background}.") + if distance_metric not in ["euclidean", "chessboard", "taxicab"]: + raise ValueError( + f"Arg `distance_metric` must be one of 'euclidean', 'chessboard', 'taxicab', but got {distance_metric}." + ) + if spacing is not None and not isinstance(spacing, (list, Tensor)): + raise ValueError(f"Arg `spacing` must be a list or tensor, but got {type(spacing)}.") + if not isinstance(directed, bool): + raise ValueError(f"Expected argument `directed` must be a boolean, but got {directed}.") + if input_format not in ["one-hot", "index", "mixed"]: + raise ValueError( + f"Expected argument `input_format` to be one of 'one-hot', 'index', 'mixed', but got {input_format}." + ) + + +def hausdorff_distance( + preds: Tensor, + target: Tensor, + num_classes: int, + include_background: bool = False, + distance_metric: Literal["euclidean", "chessboard", "taxicab"] = "euclidean", + spacing: Optional[Union[Tensor, list[float]]] = None, + directed: bool = False, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> Tensor: + """Calculate `Hausdorff Distance`_ for semantic segmentation. + + Args: + preds: predicted binarized segmentation map + target: target binarized segmentation map + num_classes: number of classes + include_background: whether to include background class in calculation + distance_metric: distance metric to calculate surface distance. Choose one of `"euclidean"`, + `"chessboard"` or `"taxicab"` + spacing: spacing between pixels along each spatial dimension. If not provided the spacing is assumed to be 1 + directed: whether to calculate directed or undirected Hausdorff distance + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor + + Returns: + Hausdorff Distance for each class and batch element + + Example: + >>> from torch import randint + >>> from torchmetrics.functional.segmentation import hausdorff_distance + >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> hausdorff_distance(preds, target, num_classes=5) + tensor([[2.0000, 1.4142, 2.0000, 2.0000], + [1.4142, 2.0000, 2.0000, 2.0000], + [2.0000, 2.0000, 1.4142, 2.0000], + [2.0000, 2.8284, 2.0000, 2.2361]]) + + """ + _hausdorff_distance_validate_args(num_classes, include_background, distance_metric, spacing, directed, input_format) + + preds, target = _segmentation_inputs_format(preds, target, include_background, num_classes, input_format) + + distances = torch.zeros(preds.shape[0], preds.shape[1], device=preds.device) + + # TODO: add support for batched inputs + for b in range(preds.shape[0]): + for c in range(preds.shape[1]): + dist = edge_surface_distance( + preds=preds[b, c], + target=target[b, c], + distance_metric=distance_metric, + spacing=spacing, + symmetric=not directed, + ) + distances[b, c] = torch.max(dist) if directed else torch.max(dist[0].max(), dist[1].max()) # type: ignore + return distances diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/mean_iou.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/mean_iou.py new file mode 100644 index 0000000000000000000000000000000000000000..747644c3a52e2f476e35811f657c68ed87f2b2da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/mean_iou.py @@ -0,0 +1,157 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional, Tuple, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.segmentation.utils import _segmentation_inputs_format +from torchmetrics.utilities.compute import _safe_divide + + +def _mean_iou_reshape_args( + preds: Tensor, + targets: Tensor, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> Tuple[Tensor, Tensor]: + """Reshape tensors to 3D if needed.""" + if input_format == "one-hot": + return preds, targets + + if preds.dim() == 1: + preds = preds.unsqueeze(0).unsqueeze(0) + elif preds.dim() == 2: + preds = preds.unsqueeze(0) + + if targets.dim() == 1: + targets = targets.unsqueeze(0).unsqueeze(0) + elif targets.dim() == 2: + targets = targets.unsqueeze(0) + return preds, targets + + +def _mean_iou_validate_args( + num_classes: Optional[int], + include_background: bool, + per_class: bool, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> None: + """Validate the arguments of the metric.""" + if input_format in ["index"] and num_classes is None: + raise ValueError("Argument `num_classes` must be provided when `input_format` is 'index'.") + if num_classes is not None and num_classes <= 0: + raise ValueError( + f"Expected argument `num_classes` must be `None` or a positive integer, but got {num_classes}." + ) + if not isinstance(include_background, bool): + raise ValueError(f"Expected argument `include_background` must be a boolean, but got {include_background}.") + if not isinstance(per_class, bool): + raise ValueError(f"Expected argument `per_class` must be a boolean, but got {per_class}.") + if input_format not in ["one-hot", "index", "mixed"]: + raise ValueError( + f"Expected argument `input_format` to be one of 'one-hot', 'index', 'mixed', but got {input_format}." + ) + + +def _mean_iou_update( + preds: Tensor, + target: Tensor, + num_classes: Optional[int] = None, + include_background: bool = False, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> tuple[Tensor, Tensor]: + """Update the intersection and union counts for the mean IoU computation.""" + preds, target = _mean_iou_reshape_args(preds, target, input_format) + + preds, target = _segmentation_inputs_format(preds, target, include_background, num_classes, input_format) + + reduce_axis = list(range(2, preds.ndim)) + intersection = torch.sum(preds & target, dim=reduce_axis) + target_sum = torch.sum(target, dim=reduce_axis) + pred_sum = torch.sum(preds, dim=reduce_axis) + union = target_sum + pred_sum - intersection + return intersection, union + + +def _mean_iou_compute( + intersection: Tensor, + union: Tensor, + zero_division: Union[float, Literal["warn", "nan"]], +) -> Tensor: + """Compute the mean IoU metric.""" + return _safe_divide(intersection, union, zero_division=zero_division) + + +def mean_iou( + preds: Tensor, + target: Tensor, + num_classes: Optional[int] = None, + include_background: bool = True, + per_class: bool = False, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> Tensor: + """Calculates the mean Intersection over Union (mIoU) for semantic segmentation. + + Returns -1 if class is completely absent both from predictions and ground truth labels. + + Args: + preds: Predictions from model + target: Ground truth values + num_classes: Number of classes + (required when input_format="index", optional when input_format="one-hot" or "mixed") + include_background: Whether to include the background class in the computation + per_class: Whether to compute the IoU for each class separately, else average over all classes + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor + + Returns: + The mean IoU score + + Example: + >>> import torch + >>> from torch import randint + >>> from torchmetrics.functional.segmentation import mean_iou + >>> # 4 samples, 5 classes, 16x16 prediction + >>> preds = randint(0, 2, (4, 5, 16, 16), generator=torch.Generator().manual_seed(42)) + >>> # 4 samples, 5 classes, 16x16 target + >>> target = randint(0, 2, (4, 5, 16, 16), generator=torch.Generator().manual_seed(43)) + >>> mean_iou(preds, target) + tensor([0.3323, 0.3336, 0.3397, 0.3435]) + >>> mean_iou(preds, target, include_background=False, num_classes=5) + tensor([0.3250, 0.3258, 0.3307, 0.3398]) + >>> mean_iou(preds, target, include_background=True, num_classes=5, per_class=True) + tensor([[0.3617, 0.3128, 0.3366, 0.3242, 0.3263], + [0.3646, 0.2893, 0.3297, 0.3073, 0.3770], + [0.3756, 0.3168, 0.3505, 0.3400, 0.3155], + [0.3579, 0.3317, 0.3797, 0.3523, 0.2957]]) + >>> # re-initialize tensors for ``input_format="index"`` + >>> preds = randint(0, 2, (4, 16, 16), generator=torch.Generator().manual_seed(42)) + >>> target = randint(0, 2, (4, 16, 16), generator=torch.Generator().manual_seed(43)) + >>> mean_iou(preds, target, num_classes=5, input_format = "index") + tensor([0.3617, 0.3128, 0.3047, 0.3499]) + >>> mean_iou(preds, target, num_classes=5, per_class=True, input_format="index") + tensor([[ 0.3617, 0.3617, -1.0000, -1.0000, -1.0000], + [ 0.3128, 0.3128, -1.0000, -1.0000, -1.0000], + [ 0.2727, 0.3366, -1.0000, -1.0000, -1.0000], + [ 0.3756, 0.3242, -1.0000, -1.0000, -1.0000]]) + + """ + _mean_iou_validate_args(num_classes, include_background, per_class, input_format) + intersection, union = _mean_iou_update(preds, target, num_classes, include_background, input_format) + scores = _mean_iou_compute(intersection, union, zero_division="nan") + valid_classes = union > 0 + return scores.nan_to_num(-1.0) if per_class else scores.nansum(dim=-1) / valid_classes.sum(dim=-1) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6610cdc8c19c098649d5f204dae994eb7547f35d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/segmentation/utils.py @@ -0,0 +1,900 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import functools +import math +from typing import Optional, Union + +import torch +from torch import Tensor +from torch.nn.functional import conv2d, conv3d, pad, unfold +from typing_extensions import Literal + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.imports import _SCIPY_AVAILABLE + + +def _ignore_background(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]: + """Ignore the background class in the computation assuming it is the first, index 0.""" + preds = preds[:, 1:] if preds.shape[1] > 1 else preds + target = target[:, 1:] if target.shape[1] > 1 else target + return preds, target + + +def _check_mixed_shape(preds: Tensor, target: Tensor) -> None: + """Check that predictions and target have the same shape, else raise error.""" + if preds.dim() == (target.dim() + 1): + if preds.shape[0] != target.shape[0] or preds.shape[2:] != target.shape[1:]: + raise RuntimeError( + f"Predictions and targets are expected to have the same shape, got {preds.shape} and {target.shape}." + ) + elif (preds.dim() + 1) == target.dim(): + if preds.shape[0] != target.shape[0] or preds.shape[1:] != target.shape[2:]: + raise RuntimeError( + f"Predictions and targets are expected to have the same shape, got {preds.shape} and {target.shape}." + ) + else: + raise RuntimeError( + f"Predictions and targets are expected to have the same shape, got {preds.shape} and {target.shape}." + ) + + +def _segmentation_inputs_format( + preds: Tensor, + target: Tensor, + include_background: bool, + num_classes: Optional[int] = None, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", +) -> tuple[Tensor, Tensor]: + """Check and format inputs to the one-hot encodings.""" + if input_format == "mixed": + _check_mixed_shape(preds, target) + else: + _check_same_shape(preds, target) + + if input_format == "index": + if num_classes is None: + raise ValueError("Argument `num_classes` must be provided when `input_format='index'`.") + preds = torch.nn.functional.one_hot(preds, num_classes=num_classes).movedim(-1, 1) + target = torch.nn.functional.one_hot(target, num_classes=num_classes).movedim(-1, 1) + elif input_format == "one-hot": + if num_classes is None: + num_classes = _get_num_classes(preds) + preds = _format_logits(preds, num_classes) + target = _format_logits(target, num_classes) + elif input_format == "mixed": + if preds.dim() == (target.dim() + 1): + if num_classes is None: + num_classes = _get_num_classes(preds) + preds = _format_logits(preds, num_classes) + target = torch.nn.functional.one_hot(target, num_classes=num_classes).movedim(-1, 1) + elif (preds.dim() + 1) == target.dim(): + if num_classes is None: + num_classes = _get_num_classes(target) + target = _format_logits(target, num_classes) + preds = torch.nn.functional.one_hot(preds, num_classes=num_classes).movedim(-1, 1) + + if preds.ndim < 3: + raise ValueError(f"Expected both `preds` and `target` to have at least 3 dimensions, but got {preds.ndim}.") + + if not include_background: + preds, target = _ignore_background(preds, target) + + return preds, target + + +def _format_logits(tensor: Tensor, num_classes: int) -> Tensor: + """Transform logits or probabilities into integer one-hot encodings.""" + if torch.is_floating_point(tensor): + tensor = tensor.argmax(dim=1) + tensor = torch.nn.functional.one_hot(tensor, num_classes=num_classes).movedim(-1, 1) + return tensor + + +def _get_num_classes(tensor: Tensor) -> int: + """Get num classes from a tensor if it is not set.""" + try: + num_classes = tensor.shape[1] + except IndexError as err: + raise IndexError(f"Cannot determine `num_classes` from tensor: {tensor}.") from err + if num_classes == 0: + raise ValueError(f"Expected argument `num_classes` to be a positive integer, but got {num_classes}.") + return num_classes + + +def check_if_binarized(x: Tensor) -> None: + """Check if tensor is binarized. + + Example: + >>> from torchmetrics.functional.segmentation.utils import check_if_binarized + >>> import torch + >>> check_if_binarized(torch.tensor([0, 1, 1, 0])) + + """ + if not torch.all(x.bool() == x): + raise ValueError("Input x should be binarized") + + +def _unfold(x: Tensor, kernel_size: tuple[int, ...]) -> Tensor: + """Unfold the input tensor to a matrix. Function supports 3d images e.g. (B, C, D, H, W). + + Inspired by: + https://github.com/f-dangel/unfoldNd/blob/main/unfoldNd/unfold.py + + Args: + x: Input tensor to be unfolded. + kernel_size: The size of the sliding blocks in each dimension. + + """ + batch_size, channels = x.shape[:2] + n = x.ndim - 2 + if n == 2: + return unfold(x, kernel_size) + + kernel_size_numel = kernel_size[0] * kernel_size[1] * kernel_size[2] + repeat = [channels, 1] + [1 for _ in kernel_size] + weight = torch.eye(kernel_size_numel, device=x.device, dtype=x.dtype) + weight = weight.reshape(kernel_size_numel, 1, *kernel_size).repeat(*repeat) + unfold_x = conv3d(x, weight=weight, bias=None) + return unfold_x.reshape(batch_size, channels * kernel_size_numel, -1) + + +def generate_binary_structure(rank: int, connectivity: int) -> Tensor: + """Translated version of the function from scipy.ndimage.morphology. + + Args: + rank: The rank of the structuring element. + connectivity: The number of neighbors connected to a given pixel. + + Returns: + The structuring element. + + Examples:: + >>> from torchmetrics.functional.segmentation.utils import generate_binary_structure + >>> import torch + >>> generate_binary_structure(2, 1) + tensor([[False, True, False], + [ True, True, True], + [False, True, False]]) + >>> generate_binary_structure(2, 2) + tensor([[True, True, True], + [True, True, True], + [True, True, True]]) + >>> generate_binary_structure(3, 2) # doctest: +NORMALIZE_WHITESPACE + tensor([[[False, True, False], + [ True, True, True], + [False, True, False]], + [[ True, True, True], + [ True, True, True], + [ True, True, True]], + [[False, True, False], + [ True, True, True], + [False, True, False]]]) + + """ + if connectivity < 1: + connectivity = 1 + if rank < 1: + return torch.tensor([1], dtype=torch.uint8) + grids = torch.meshgrid([torch.arange(3) for _ in range(rank)], indexing="ij") + output = torch.abs(torch.stack(grids, dim=0) - 1) + output = torch.sum(output, dim=0) + return output <= connectivity + + +def binary_erosion( + image: Tensor, structure: Optional[Tensor] = None, origin: Optional[tuple[int, ...]] = None, border_value: int = 0 +) -> Tensor: + """Binary erosion of a tensor image. + + Implementation inspired by answer to this question: https://stackoverflow.com/questions/56235733/ + + Args: + image: The image to be eroded, must be a binary tensor with shape ``(batch_size, channels, height, width)``. + structure: The structuring element used for the erosion. If no structuring element is provided, an element + is generated with a square connectivity equal to one. + origin: The origin of the structuring element. + border_value: The value to be used for the border. + + Examples:: + >>> from torchmetrics.functional.segmentation.utils import binary_erosion + >>> import torch + >>> image = torch.tensor([[[[0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]]]]) + >>> binary_erosion(image) + tensor([[[[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]]], dtype=torch.uint8) + >>> binary_erosion(image, structure=torch.ones(4, 4)) + tensor([[[[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]]], dtype=torch.uint8) + + """ + if not isinstance(image, Tensor): + raise TypeError(f"Expected argument `image` to be of type Tensor but found {type(image)}") + if image.ndim not in [4, 5]: + raise ValueError(f"Expected argument `image` to be of rank 4 or 5 but found rank {image.ndim}") + check_if_binarized(image) + + # construct the structuring element if not provided + if structure is None: + structure = generate_binary_structure(image.ndim - 2, 1).int().to(image.device) + check_if_binarized(structure) + + if origin is None: + origin = structure.ndim * (1,) + + # first pad the image to have correct unfolding; here is where the origins is used + image_pad = pad( + image, + [x for i in range(len(origin)) for x in [origin[i], structure.shape[i] - origin[i] - 1]], + mode="constant", + value=border_value, + ) + # Unfold the image to be able to perform operation on neighborhoods + image_unfold = _unfold(image_pad.float(), kernel_size=structure.shape) + + strel_flatten = torch.flatten(structure).unsqueeze(0).unsqueeze(-1) + sums = image_unfold - strel_flatten.int() + + # Take minimum over the neighborhood + result, _ = sums.min(dim=1) + + # Reshape the image to recover initial shape + return (torch.reshape(result, image.shape) + 1).byte() + + +def distance_transform( + x: Tensor, + sampling: Optional[Union[Tensor, list[float]]] = None, + metric: Literal["euclidean", "chessboard", "taxicab"] = "euclidean", + engine: Literal["pytorch", "scipy"] = "pytorch", +) -> Tensor: + """Calculate distance transform of a binary tensor. + + This function calculates the distance transform of a binary tensor, replacing each foreground pixel with the + distance to the closest background pixel. The distance is calculated using the euclidean, chessboard or taxicab + distance. + + The memory consumption of this function is in the worst cast N/2**2 where N is the number of pixel. Since we need + to compare all foreground pixels to all background pixels, the memory consumption is quadratic in the number of + pixels. The memory consumption can be reduced by using the ``scipy`` engine, which is more memory efficient but + should also be slower for larger images. + + Args: + x: The binary tensor to calculate the distance transform of. + sampling: The sampling refers to the pixel spacing in the image, i.e. the distance between two adjacent pixels. + If not provided, the pixel spacing is assumed to be 1. + metric: The distance to use for the distance transform. Can be one of ``"euclidean"``, ``"chessboard"`` + or ``"taxicab"``. + engine: The engine to use for the distance transform. Can be one of ``["pytorch", "scipy"]``. In general, + the ``pytorch`` engine is faster, but the ``scipy`` engine is more memory efficient. + + Returns: + The distance transform of the input tensor. + + Examples:: + >>> from torchmetrics.functional.segmentation.utils import distance_transform + >>> import torch + >>> x = torch.tensor([[0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]]) + >>> distance_transform(x) + tensor([[0., 0., 0., 0., 0.], + [0., 1., 1., 1., 0.], + [0., 1., 2., 1., 0.], + [0., 1., 1., 1., 0.], + [0., 0., 0., 0., 0.]]) + + """ + if not isinstance(x, Tensor): + raise ValueError(f"Expected argument `x` to be of type `torch.Tensor` but got `{type(x)}`.") + if x.ndim != 2: + raise ValueError(f"Expected argument `x` to be of rank 2 but got rank `{x.ndim}`.") + if sampling is not None and not isinstance(sampling, list): + raise ValueError( + f"Expected argument `sampling` to either be `None` or of type `list` but got `{type(sampling)}`." + ) + if metric not in ["euclidean", "chessboard", "taxicab"]: + raise ValueError( + f"Expected argument `metric` to be one of `['euclidean', 'chessboard', 'taxicab']` but got `{metric}`." + ) + if engine not in ["pytorch", "scipy"]: + raise ValueError(f"Expected argument `engine` to be one of `['pytorch', 'scipy']` but got `{engine}`.") + + if sampling is None: + sampling = [1, 1] + else: + if len(sampling) != 2: + raise ValueError(f"Expected argument `sampling` to have length 2 but got length `{len(sampling)}`.") + + if engine == "pytorch": + x = x.float() + # calculate distance from every foreground pixel to every background pixel + i0, j0 = torch.where(x == 0) + i1, j1 = torch.where(x == 1) + dis_row = (i1.view(-1, 1) - i0.view(1, -1)).abs() + dis_col = (j1.view(-1, 1) - j0.view(1, -1)).abs() + + # # calculate distance + h, _ = x.shape + if metric == "euclidean": + dis = ((sampling[0] * dis_row) ** 2 + (sampling[1] * dis_col) ** 2).sqrt() + if metric == "chessboard": + dis = torch.max(sampling[0] * dis_row, sampling[1] * dis_col).float() + if metric == "taxicab": + dis = (sampling[0] * dis_row + sampling[1] * dis_col).float() + + # select only the closest distance + mindis, _ = torch.min(dis, dim=1) + z = torch.zeros_like(x).view(-1) + z[i1 * h + j1] = mindis + return z.view(x.shape) + + if not _SCIPY_AVAILABLE: + raise ValueError( + "The `scipy` engine requires `scipy` to be installed. Either install `scipy` or use the `pytorch` engine." + ) + from scipy import ndimage + + if metric == "euclidean": + return ndimage.distance_transform_edt(x.cpu().numpy(), sampling) + return ndimage.distance_transform_cdt(x.cpu().numpy(), sampling, metric=metric) + + +def mask_edges( + preds: Tensor, + target: Tensor, + crop: bool = True, + spacing: Optional[Union[tuple[int, int], tuple[int, int, int]]] = None, +) -> Union[tuple[Tensor, Tensor], tuple[Tensor, Tensor, Tensor, Tensor]]: + """Get the edges of binary segmentation masks. + + Args: + preds: The predicted binary segmentation mask + target: The ground truth binary segmentation mask + crop: Whether to crop the edges to the region of interest. If ``True``, the edges are cropped to the bounding + spacing: The pixel spacing of the input images. If provided, the edges are calculated using the euclidean + + Returns: + If spacing is not provided, a 2-tuple containing the edges of the predicted and target mask respectively is + returned. If spacing is provided, a 4-tuple containing the edges and areas of the predicted and target mask + respectively is returned. + + """ + _check_same_shape(preds, target) + if preds.ndim not in [2, 3]: + raise ValueError(f"Expected argument `preds` to be of rank 2 or 3 but got rank `{preds.ndim}`.") + check_if_binarized(preds) + check_if_binarized(target) + + if crop: + or_val = preds | target + if not or_val.any(): + p, t = torch.zeros_like(preds), torch.zeros_like(target) + return p, t, p, t + # this seems to be working but does not seem to be right + preds, target = pad(preds, preds.ndim * [1, 1]), pad(target, target.ndim * [1, 1]) + + if spacing is None: + # no spacing, use binary erosion + be_pred = binary_erosion(preds.unsqueeze(0).unsqueeze(0)).squeeze() ^ preds + be_target = binary_erosion(target.unsqueeze(0).unsqueeze(0)).squeeze() ^ target + return be_pred, be_target + + # use neighborhood to get edges + table, kernel = get_neighbour_tables(spacing, device=preds.device) + spatial_dims = len(spacing) + conv_operator = conv2d if spatial_dims == 2 else conv3d + volume = torch.stack([preds.unsqueeze(0), target.unsqueeze(0)], dim=0).float() + code_preds, code_target = conv_operator(volume, kernel.to(volume)) + + # edges + all_ones = len(table) - 1 + edges_preds = (code_preds != 0) & (code_preds != all_ones) + edges_target = (code_target != 0) & (code_target != all_ones) + + # # areas of edges + areas_preds = torch.index_select(table, 0, code_preds.view(-1).int()).view_as(code_preds) + areas_target = torch.index_select(table, 0, code_target.view(-1).int()).view_as(code_target) + return edges_preds[0], edges_target[0], areas_preds[0], areas_target[0] + + +def surface_distance( + preds: Tensor, + target: Tensor, + distance_metric: Literal["euclidean", "chessboard", "taxicab"] = "euclidean", + spacing: Optional[Union[Tensor, list[float]]] = None, +) -> Tensor: + """Calculate the surface distance between two binary edge masks. + + May return infinity if the predicted mask is empty and the target mask is not, or vice versa. + + Args: + preds: The predicted binary edge mask. + target: The target binary edge mask. + distance_metric: The distance metric to use. One of `["euclidean", "chessboard", "taxicab"]`. + spacing: The spacing between pixels along each spatial dimension. + + Returns: + A tensor with length equal to the number of edges in predictions e.g. `preds.sum()`. Each element is the + distance from the corresponding edge in `preds` to the closest edge in `target`. + + Example:: + >>> import torch + >>> from torchmetrics.functional.segmentation.utils import surface_distance + >>> preds = torch.tensor([[1, 1, 1, 1, 1], + ... [1, 0, 0, 0, 1], + ... [1, 0, 0, 0, 1], + ... [1, 0, 0, 0, 1], + ... [1, 1, 1, 1, 1]], dtype=torch.bool) + >>> target = torch.tensor([[1, 1, 1, 1, 0], + ... [1, 0, 0, 1, 0], + ... [1, 0, 0, 1, 0], + ... [1, 0, 0, 1, 0], + ... [1, 1, 1, 1, 0]], dtype=torch.bool) + >>> surface_distance(preds, target, distance_metric="euclidean", spacing=[1, 1]) + tensor([0., 0., 0., 0., 1., 0., 1., 0., 1., 0., 1., 0., 0., 0., 0., 1.]) + + """ + if not (preds.dtype == torch.bool and target.dtype == torch.bool): + raise ValueError(f"Expected both inputs to be of type `torch.bool`, but got {preds.dtype} and {target.dtype}.") + + if not torch.any(target): + dis = torch.inf * torch.ones_like(target) + else: + if not torch.any(preds): + dis = torch.inf * torch.ones_like(preds) + return dis[target] + dis = distance_transform(~target, sampling=spacing, metric=distance_metric) + return dis[preds] + + +def edge_surface_distance( + preds: Tensor, + target: Tensor, + distance_metric: Literal["euclidean", "chessboard", "taxicab"] = "euclidean", + spacing: Optional[Union[Tensor, list[float]]] = None, + symmetric: bool = False, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Extracts the edges from the input masks and calculates the surface distance between them. + + Args: + preds: The predicted binary edge mask. + target: The target binary edge mask. + distance_metric: The distance metric to use. One of `["euclidean", "chessboard", "taxicab"]`. + spacing: The spacing between pixels along each spatial dimension. + symmetric: Whether to calculate the symmetric distance between the edges. + + Returns: + A tensor with length equal to the number of edges in predictions e.g. `preds.sum()`. Each element is the + distance from the corresponding edge in `preds` to the closest edge in `target`. If `symmetric` is `True`, the + function returns a tuple containing the distances from the predicted edges to the target edges and vice versa. + + """ + output = mask_edges(preds, target) + edges_preds, edges_target = output[0].bool(), output[1].bool() + if symmetric: + return ( + surface_distance(edges_preds, edges_target, distance_metric=distance_metric, spacing=spacing), + surface_distance(edges_target, edges_preds, distance_metric=distance_metric, spacing=spacing), + ) + return surface_distance(edges_preds, edges_target, distance_metric=distance_metric, spacing=spacing) + + +@functools.lru_cache +def get_neighbour_tables( + spacing: Union[tuple[int, int], tuple[int, int, int]], device: Optional[torch.device] = None +) -> tuple[Tensor, Tensor]: + """Create a table that maps neighbour codes to the contour length or surface area of the corresponding contour. + + Args: + spacing: The spacing between pixels along each spatial dimension. + device: The device on which the table should be created. + + Returns: + A tuple containing as its first element the table that maps neighbour codes to the contour length or surface + area of the corresponding contour and as its second element the kernel used to compute the neighbour codes. + + """ + if isinstance(spacing, tuple) and len(spacing) == 2: + return table_contour_length(spacing, device) + if isinstance(spacing, tuple) and len(spacing) == 3: + return table_surface_area(spacing, device) + raise ValueError("The spacing must be a tuple of length 2 or 3.") + + +def table_contour_length(spacing: tuple[int, int], device: Optional[torch.device] = None) -> tuple[Tensor, Tensor]: + """Create a table that maps neighbour codes to the contour length of the corresponding contour. + + Adopted from: + https://github.com/deepmind/surface-distance/blob/master/surface_distance/lookup_tables.py + + Args: + spacing: The spacing between pixels along each spatial dimension. Should be a tuple of length 2. + device: The device on which the table should be created. + + Returns: + A tuple containing as its first element the table that maps neighbour codes to the contour length of the + corresponding contour and as its second element the kernel used to compute the neighbour codes. + + Example:: + >>> from torchmetrics.functional.segmentation.utils import table_contour_length + >>> table, kernel = table_contour_length((2,2)) + >>> table + tensor([0.0000, 1.4142, 1.4142, 2.0000, 1.4142, 2.0000, 2.8284, 1.4142, 1.4142, + 2.8284, 2.0000, 1.4142, 2.0000, 1.4142, 1.4142, 0.0000]) + >>> kernel + tensor([[[[8, 4], + [2, 1]]]]) + + """ + if not isinstance(spacing, tuple) and len(spacing) != 2: + raise ValueError("The spacing must be a tuple of length 2.") + + first, second = spacing # spacing along the first and second spatial dimension respectively + diag = 0.5 * math.sqrt(first**2 + second**2) + table = torch.zeros(16, dtype=torch.float32, device=device) + for i in [1, 2, 4, 7, 8, 11, 13, 14]: + table[i] = diag + for i in [3, 12]: + table[i] = second + for i in [5, 10]: + table[i] = first + for i in [6, 9]: + table[i] = 2 * diag + kernel = torch.as_tensor([[[[8, 4], [2, 1]]]], device=device) + return table, kernel + + +@functools.lru_cache +def table_surface_area(spacing: tuple[int, int, int], device: Optional[torch.device] = None) -> tuple[Tensor, Tensor]: + """Create a table that maps neighbour codes to the surface area of the corresponding surface. + + Adopted from: + https://github.com/deepmind/surface-distance/blob/master/surface_distance/lookup_tables.py + + Args: + spacing: The spacing between pixels along each spatial dimension. Should be a tuple of length 3. + device: The device on which the table should be created. + + Returns: + A tuple containing as its first element the table that maps neighbour codes to the surface area of the + corresponding surface and as its second element the kernel used to compute the neighbour codes. + + Example:: + >>> from torchmetrics.functional.segmentation.utils import table_surface_area + >>> table, kernel = table_surface_area((2,2,2)) + >>> table + tensor([0.0000, 0.8660, 0.8660, 2.8284, 0.8660, 2.8284, 1.7321, 4.5981, 0.8660, + 1.7321, 2.8284, 4.5981, 2.8284, 4.5981, 4.5981, 4.0000, 0.8660, 2.8284, + 1.7321, 4.5981, 1.7321, 4.5981, 2.5981, 5.1962, 1.7321, 3.6945, 3.6945, + 6.2925, 3.6945, 6.2925, 5.4641, 4.5981, 0.8660, 1.7321, 2.8284, 4.5981, + 1.7321, 3.6945, 3.6945, 6.2925, 1.7321, 2.5981, 4.5981, 5.1962, 3.6945, + 5.4641, 6.2925, 4.5981, 2.8284, 4.5981, 4.5981, 4.0000, 3.6945, 6.2925, + 5.4641, 4.5981, 3.6945, 5.4641, 6.2925, 4.5981, 5.6569, 3.6945, 3.6945, + 2.8284, 0.8660, 1.7321, 1.7321, 3.6945, 2.8284, 4.5981, 3.6945, 6.2925, + 1.7321, 2.5981, 3.6945, 5.4641, 4.5981, 5.1962, 6.2925, 4.5981, 2.8284, + 4.5981, 3.6945, 6.2925, 4.5981, 4.0000, 5.4641, 4.5981, 3.6945, 5.4641, + 5.6569, 3.6945, 6.2925, 4.5981, 3.6945, 2.8284, 1.7321, 2.5981, 3.6945, + 5.4641, 3.6945, 5.4641, 5.6569, 3.6945, 2.5981, 3.4641, 5.4641, 2.5981, + 5.4641, 2.5981, 3.6945, 1.7321, 4.5981, 5.1962, 6.2925, 4.5981, 6.2925, + 4.5981, 3.6945, 2.8284, 5.4641, 2.5981, 3.6945, 1.7321, 3.6945, 1.7321, + 1.7321, 0.8660, 0.8660, 1.7321, 1.7321, 3.6945, 1.7321, 3.6945, 2.5981, + 5.4641, 2.8284, 3.6945, 4.5981, 6.2925, 4.5981, 6.2925, 5.1962, 4.5981, + 1.7321, 3.6945, 2.5981, 5.4641, 2.5981, 5.4641, 3.4641, 2.5981, 3.6945, + 5.6569, 5.4641, 3.6945, 5.4641, 3.6945, 2.5981, 1.7321, 2.8284, 3.6945, + 4.5981, 6.2925, 3.6945, 5.6569, 5.4641, 3.6945, 4.5981, 5.4641, 4.0000, + 4.5981, 6.2925, 3.6945, 4.5981, 2.8284, 4.5981, 6.2925, 5.1962, 4.5981, + 5.4641, 3.6945, 2.5981, 1.7321, 6.2925, 3.6945, 4.5981, 2.8284, 3.6945, + 1.7321, 1.7321, 0.8660, 2.8284, 3.6945, 3.6945, 5.6569, 4.5981, 6.2925, + 5.4641, 3.6945, 4.5981, 5.4641, 6.2925, 3.6945, 4.0000, 4.5981, 4.5981, + 2.8284, 4.5981, 6.2925, 5.4641, 3.6945, 5.1962, 4.5981, 2.5981, 1.7321, + 6.2925, 3.6945, 3.6945, 1.7321, 4.5981, 2.8284, 1.7321, 0.8660, 4.5981, + 5.4641, 6.2925, 3.6945, 6.2925, 3.6945, 3.6945, 1.7321, 5.1962, 2.5981, + 4.5981, 1.7321, 4.5981, 1.7321, 2.8284, 0.8660, 4.0000, 4.5981, 4.5981, + 2.8284, 4.5981, 2.8284, 1.7321, 0.8660, 4.5981, 1.7321, 2.8284, 0.8660, + 2.8284, 0.8660, 0.8660, 0.0000]) + >>> kernel + tensor([[[[[128, 64], + [ 32, 16]], + [[ 8, 4], + [ 2, 1]]]]]) + + """ + if not isinstance(spacing, tuple) and len(spacing) != 3: + raise ValueError("The spacing must be a tuple of length 3.") + + zeros = [0.0, 0.0, 0.0] + table = torch.tensor( + [ + [zeros, zeros, zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[-0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros, zeros], + [[0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros, zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros, zeros], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], zeros], + [[-0.5, 0.0, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[0.5, 0.0, 0.0], [0.5, 0.0, 0.0], zeros, zeros], + [[0.125, -0.125, -0.125], zeros, zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.5, 0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, 0.0, -0.5], [0.25, 0.25, 0.25], [-0.125, -0.125, -0.125], zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.125, 0.125, 0.125], [0.375, 0.375, 0.375], [0.0, -0.25, 0.25], [-0.25, 0.0, 0.25]], + [[0.125, -0.125, -0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.375, 0.375, 0.375], [0.0, 0.25, -0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.125, 0.125, 0.125]], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], zeros], + [[0.125, -0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros, zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, -0.125, 0.125], [-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.375, -0.375, 0.375], [-0.0, 0.25, 0.25], [0.125, 0.125, -0.125], [-0.25, -0.0, -0.25]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, 0.25, -0.25], [0.25, 0.25, -0.25], [0.125, 0.125, -0.125], [-0.125, -0.125, 0.125]], + [[0.125, -0.125, 0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], [0.125, -0.125, 0.125]], + [[0.0, 0.25, -0.25], [0.375, -0.375, -0.375], [-0.125, 0.125, 0.125], [0.25, 0.25, 0.0]], + [[-0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros, zeros], + [[0.0, 0.5, 0.0], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.0, 0.5, 0.0], [0.125, -0.125, 0.125], [-0.25, 0.25, -0.25], zeros], + [[0.0, 0.5, 0.0], [0.0, -0.5, 0.0], zeros, zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.125, -0.125, 0.125], zeros], + [[-0.375, -0.375, -0.375], [-0.25, 0.0, 0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[0.125, 0.125, 0.125], [0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]], + [[0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125], zeros], + [[-0.125, 0.125, 0.125], [0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.375, 0.375, -0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0]], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.125, -0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros, zeros], + [[-0.125, -0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.125, -0.125, 0.125], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], zeros, zeros], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.375, -0.375, 0.375], [0.0, -0.25, -0.25], [-0.125, 0.125, -0.125], [0.25, 0.25, 0.0]], + [[-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.25, 0.25, -0.25], [-0.25, 0.25, -0.25], [-0.125, 0.125, -0.125], [-0.125, 0.125, -0.125]], + [[-0.25, 0.0, -0.25], [0.375, -0.375, -0.375], [0.0, 0.25, -0.25], [-0.125, 0.125, 0.125]], + [[0.5, 0.0, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros, zeros], + [[-0.0, 0.0, 0.5], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros], + [[-0.25, -0.0, -0.25], [-0.375, 0.375, 0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, 0.125]], + [[0.0, 0.0, -0.5], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.0, 0.0, 0.5], [0.0, 0.0, 0.5], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]], + [[0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25]], + [[0.125, -0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[0.25, 0.0, 0.25], [-0.375, -0.375, 0.375], [-0.25, 0.25, 0.0], [-0.125, -0.125, 0.125]], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25]], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, -0.25, -0.25], [0.125, -0.125, -0.125], zeros], + [[-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]], + [[0.375, -0.375, 0.375], [0.0, 0.25, 0.25], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[0.0, -0.5, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.375, -0.375, 0.375], [0.25, -0.25, 0.0], [0.0, 0.25, 0.25], [-0.125, -0.125, 0.125]], + [[-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[0.125, 0.125, 0.125], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], [0.125, 0.125, 0.125]], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125], zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125], zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], [0.125, 0.125, 0.125]], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros], + [[-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[-0.375, -0.375, 0.375], [0.25, -0.25, 0.0], [0.0, 0.25, 0.25], [-0.125, -0.125, 0.125]], + [[0.0, -0.5, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[0.375, -0.375, 0.375], [0.0, 0.25, 0.25], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]], + [[0.5, 0.0, -0.0], [0.25, -0.25, -0.25], [0.125, -0.125, -0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25]], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]], + [[-0.125, -0.125, 0.125], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.25, 0.0, 0.25], [-0.375, -0.375, 0.375], [-0.25, 0.25, 0.0], [-0.125, -0.125, 0.125]], + [[0.125, -0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25]], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], [-0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]], + [[-0.0, 0.0, 0.5], [0.0, 0.0, 0.5], zeros, zeros], + [[0.0, 0.0, -0.5], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.25, -0.0, -0.25], [-0.375, 0.375, 0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, 0.125]], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros], + [[-0.0, 0.0, 0.5], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros, zeros], + [[0.5, 0.0, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.25, 0.0, -0.25], [0.375, -0.375, -0.375], [0.0, 0.25, -0.25], [-0.125, 0.125, 0.125]], + [[-0.25, 0.25, -0.25], [-0.25, 0.25, -0.25], [-0.125, 0.125, -0.125], [-0.125, 0.125, -0.125]], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[0.375, -0.375, 0.375], [0.0, -0.25, -0.25], [-0.125, 0.125, -0.125], [0.25, 0.25, 0.0]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], zeros, zeros], + [[-0.125, -0.125, 0.125], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros], + [[-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.125, -0.125, 0.125], zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0]], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.375, 0.375, -0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros], + [[0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125], zeros], + [[0.125, 0.125, 0.125], [0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]], + [[-0.375, -0.375, -0.375], [-0.25, 0.0, 0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.125, -0.125, 0.125], zeros], + [[0.0, 0.5, 0.0], [0.0, -0.5, 0.0], zeros, zeros], + [[0.0, 0.5, 0.0], [0.125, -0.125, 0.125], [-0.25, 0.25, -0.25], zeros], + [[0.0, 0.5, 0.0], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros, zeros], + [[-0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.0, 0.25, -0.25], [0.375, -0.375, -0.375], [-0.125, 0.125, 0.125], [0.25, 0.25, 0.0]], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], [0.125, -0.125, 0.125]], + [[0.125, -0.125, 0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.25, 0.25, -0.25], [0.25, 0.25, -0.25], [0.125, 0.125, -0.125], [-0.125, -0.125, 0.125]], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[-0.375, -0.375, 0.375], [-0.0, 0.25, 0.25], [0.125, 0.125, -0.125], [-0.25, -0.0, -0.25]], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], zeros], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], zeros], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.125, 0.125, 0.125]], + [[0.375, 0.375, 0.375], [0.0, 0.25, -0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[0.125, -0.125, -0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.125, 0.125, 0.125], [0.375, 0.375, 0.375], [0.0, -0.25, 0.25], [-0.25, 0.0, 0.25]], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[0.0, 0.0, -0.5], [0.25, 0.25, 0.25], [-0.125, -0.125, -0.125], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.5, 0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[0.125, -0.125, -0.125], zeros, zeros, zeros], + [[0.5, 0.0, 0.0], [0.5, 0.0, 0.0], zeros, zeros], + [[-0.5, 0.0, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], zeros], + [[0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros, zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[-0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [zeros, zeros, zeros, zeros], + ], + dtype=torch.float32, + device=device, + ) + + space = torch.as_tensor( + [[[spacing[1] * spacing[2], spacing[0] * spacing[2], spacing[0] * spacing[1]]]], + device=device, + dtype=table.dtype, + ) + norm = torch.linalg.norm(table * space, dim=-1) + table = norm.sum(-1) + kernel = torch.as_tensor([[[[[128, 64], [32, 16]], [[8, 4], [2, 1]]]]], device=device) + return table, kernel diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/shape/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/shape/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf4118b053461eb2b8c9d9dfbc39dda1f29ba37 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/shape/__init__.py @@ -0,0 +1,16 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.functional.shape.procrustes import procrustes_disparity + +__all__ = ["procrustes_disparity"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/shape/procrustes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/shape/procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..e72ca339306b046603e06b08ca57920ce8fca1cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/shape/procrustes.py @@ -0,0 +1,66 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from torch import Tensor, linalg + +from torchmetrics.utilities.checks import _check_same_shape +from torchmetrics.utilities.prints import rank_zero_warn + + +def procrustes_disparity( + point_cloud1: Tensor, point_cloud2: Tensor, return_all: bool = False +) -> Union[Tensor, tuple[Tensor, Tensor, Tensor]]: + """Runs procrustrus analysis on a batch of data points. + + Works similar ``scipy.spatial.procrustes`` but for batches of data points. + + Args: + point_cloud1: The first set of data points + point_cloud2: The second set of data points + return_all: If True, returns the scale and rotation matrices along with the disparity + + """ + _check_same_shape(point_cloud1, point_cloud2) + if point_cloud1.ndim != 3: + raise ValueError( + "Expected both datasets to be 3D tensors of shape (N, M, D), where N is the batch size, M is the number of" + f" data points and D is the dimensionality of the data points, but got {point_cloud1.ndim} dimensions." + ) + + point_cloud1 = point_cloud1 - point_cloud1.mean(dim=1, keepdim=True) + point_cloud2 = point_cloud2 - point_cloud2.mean(dim=1, keepdim=True) + point_cloud1 /= linalg.norm(point_cloud1, dim=[1, 2], keepdim=True) + point_cloud2 /= linalg.norm(point_cloud2, dim=[1, 2], keepdim=True) + + try: + u, w, v = linalg.svd( + torch.matmul(point_cloud2.transpose(1, 2), point_cloud1).transpose(1, 2), full_matrices=False + ) + except Exception as ex: + rank_zero_warn( + f"SVD calculation in procrustes_disparity failed with exception {ex}. Returning 0 disparity and identity" + " scale/rotation.", + UserWarning, + ) + return torch.tensor(0.0), torch.ones(point_cloud1.shape[0]), torch.eye(point_cloud1.shape[2]) + + rotation = torch.matmul(u, v) + scale = w.sum(1, keepdim=True) + point_cloud2 = scale[:, None] * torch.matmul(point_cloud2, rotation.transpose(1, 2)) + disparity = (point_cloud1 - point_cloud2).square().sum(dim=[1, 2]) + if return_all: + return disparity, scale, rotation + return disparity diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9282be6fbaee176d40f8b50deeef62ed22f87dfe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/__init__.py @@ -0,0 +1,53 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from torchmetrics.functional.text.bleu import bleu_score +from torchmetrics.functional.text.cer import char_error_rate +from torchmetrics.functional.text.chrf import chrf_score +from torchmetrics.functional.text.edit import edit_distance +from torchmetrics.functional.text.eed import extended_edit_distance +from torchmetrics.functional.text.mer import match_error_rate +from torchmetrics.functional.text.perplexity import perplexity +from torchmetrics.functional.text.rouge import rouge_score +from torchmetrics.functional.text.sacre_bleu import sacre_bleu_score +from torchmetrics.functional.text.squad import squad +from torchmetrics.functional.text.ter import translation_edit_rate +from torchmetrics.functional.text.wer import word_error_rate +from torchmetrics.functional.text.wil import word_information_lost +from torchmetrics.functional.text.wip import word_information_preserved +from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_4 + +__all__ = [ + "bleu_score", + "char_error_rate", + "chrf_score", + "edit_distance", + "extended_edit_distance", + "match_error_rate", + "perplexity", + "rouge_score", + "sacre_bleu_score", + "squad", + "translation_edit_rate", + "word_error_rate", + "word_information_lost", + "word_information_preserved", +] + + +if _TRANSFORMERS_GREATER_EQUAL_4_4: + from torchmetrics.functional.text.bert import bert_score + from torchmetrics.functional.text.infolm import infolm + + __all__ += ["bert_score", "infolm"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/_deprecated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..380c70489143a5057f0d5c19aea4179ae9d7b4ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/_deprecated.py @@ -0,0 +1,409 @@ +import os +from collections.abc import Sequence +from typing import Any, Callable, List, Literal, Optional, Union + +import torch +from torch import Tensor +from torch.nn import Module + +from torchmetrics.functional.text.bert import bert_score +from torchmetrics.functional.text.bleu import bleu_score +from torchmetrics.functional.text.cer import char_error_rate +from torchmetrics.functional.text.chrf import chrf_score +from torchmetrics.functional.text.eed import extended_edit_distance +from torchmetrics.functional.text.infolm import ( + _ALLOWED_INFORMATION_MEASURE_LITERAL as _INFOLM_ALLOWED_INFORMATION_MEASURE_LITERAL, +) +from torchmetrics.functional.text.infolm import infolm +from torchmetrics.functional.text.mer import match_error_rate +from torchmetrics.functional.text.perplexity import perplexity +from torchmetrics.functional.text.rouge import rouge_score +from torchmetrics.functional.text.sacre_bleu import sacre_bleu_score +from torchmetrics.functional.text.squad import squad +from torchmetrics.functional.text.ter import translation_edit_rate +from torchmetrics.functional.text.wer import word_error_rate +from torchmetrics.functional.text.wil import word_information_lost +from torchmetrics.functional.text.wip import word_information_preserved +from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_4 +from torchmetrics.utilities.prints import _deprecated_root_import_func + +__doctest_requires__ = {("_rouge_score"): ["nltk"]} + +if not _TRANSFORMERS_GREATER_EQUAL_4_4: + __doctest_skip__ = ["_bert_score", "_infolm"] + +SQUAD_SINGLE_TARGET_TYPE = dict[str, Union[str, dict[str, Union[list[str], list[int]]]]] +SQUAD_TARGETS_TYPE = Union[SQUAD_SINGLE_TARGET_TYPE, list[SQUAD_SINGLE_TARGET_TYPE]] + + +def _bert_score( + preds: Union[list[str], dict[str, Tensor]], + target: Union[list[str], dict[str, Tensor]], + model_name_or_path: Optional[str] = None, + num_layers: Optional[int] = None, + all_layers: bool = False, + model: Optional[Module] = None, + user_tokenizer: Any = None, + user_forward_fn: Optional[Callable[[Module, dict[str, Tensor]], Tensor]] = None, + verbose: bool = False, + idf: bool = False, + device: Optional[Union[str, torch.device]] = None, + max_length: int = 512, + batch_size: int = 64, + num_threads: int = 4, + return_hash: bool = False, + lang: str = "en", + rescale_with_baseline: bool = False, + baseline_path: Optional[str] = None, + baseline_url: Optional[str] = None, +) -> dict[str, Union[Tensor, list[float], str]]: + """Wrapper for deprecated import. + + >>> preds = ["hello there", "general kenobi"] + >>> target = ["hello there", "master kenobi"] + >>> score = _bert_score(preds, target) + >>> from pprint import pprint + >>> pprint(score) + {'f1': tensor([1.0000, 0.9961]), + 'precision': tensor([1.0000, 0.9961]), + 'recall': tensor([1.0000, 0.9961])} + + """ + _deprecated_root_import_func("bert_score", "text") + return bert_score( + preds=preds, + target=target, + model_name_or_path=model_name_or_path, + num_layers=num_layers, + all_layers=all_layers, + model=model, + user_tokenizer=user_tokenizer, + user_forward_fn=user_forward_fn, + verbose=verbose, + idf=idf, + device=device, + max_length=max_length, + batch_size=batch_size, + num_threads=num_threads, + return_hash=return_hash, + lang=lang, + rescale_with_baseline=rescale_with_baseline, + baseline_path=baseline_path, + baseline_url=baseline_url, + ) + + +def _bleu_score( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + n_gram: int = 4, + smooth: bool = False, + weights: Optional[Sequence[float]] = None, +) -> Tensor: + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> _bleu_score(preds, target) + tensor(0.7598) + + """ + _deprecated_root_import_func("bleu_score", "text") + return bleu_score(preds=preds, target=target, n_gram=n_gram, smooth=smooth, weights=weights) + + +def _char_error_rate(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> _char_error_rate(preds=preds, target=target) + tensor(0.3415) + + """ + _deprecated_root_import_func("char_error_rate", "text") + return char_error_rate(preds=preds, target=target) + + +def _chrf_score( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + n_char_order: int = 6, + n_word_order: int = 2, + beta: float = 2.0, + lowercase: bool = False, + whitespace: bool = False, + return_sentence_level_score: bool = False, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> _chrf_score(preds, target) + tensor(0.8640) + + """ + _deprecated_root_import_func("chrf_score", "text") + return chrf_score( + preds=preds, + target=target, + n_char_order=n_char_order, + n_word_order=n_word_order, + beta=beta, + lowercase=lowercase, + whitespace=whitespace, + return_sentence_level_score=return_sentence_level_score, + ) + + +def _extended_edit_distance( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + language: Literal["en", "ja"] = "en", + return_sentence_level_score: bool = False, + alpha: float = 2.0, + rho: float = 0.3, + deletion: float = 0.2, + insertion: float = 1.0, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "here is an other sample"] + >>> target = ["this is the reference", "here is another one"] + >>> _extended_edit_distance(preds=preds, target=target) + tensor(0.3078) + + """ + _deprecated_root_import_func("extended_edit_distance", "text") + return extended_edit_distance( + preds=preds, + target=target, + language=language, + return_sentence_level_score=return_sentence_level_score, + alpha=alpha, + rho=rho, + deletion=deletion, + insertion=insertion, + ) + + +def _infolm( + preds: Union[str, Sequence[str]], + target: Union[str, Sequence[str]], + model_name_or_path: Union[str, os.PathLike] = "bert-base-uncased", + temperature: float = 0.25, + information_measure: _INFOLM_ALLOWED_INFORMATION_MEASURE_LITERAL = "kl_divergence", + idf: bool = True, + alpha: Optional[float] = None, + beta: Optional[float] = None, + device: Optional[Union[str, torch.device]] = None, + max_length: Optional[int] = None, + batch_size: int = 64, + num_threads: int = 0, + verbose: bool = True, + return_sentence_level_score: bool = False, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Wrapper for deprecated import. + + >>> preds = ['he read the book because he was interested in world history'] + >>> target = ['he was interested in world history because he read the book'] + >>> _infolm(preds, target, model_name_or_path='google/bert_uncased_L-2_H-128_A-2', idf=False) + tensor(-0.1784) + + """ + _deprecated_root_import_func("infolm", "text") + return infolm( + preds=preds, + target=target, + model_name_or_path=model_name_or_path, + temperature=temperature, + information_measure=information_measure, + idf=idf, + alpha=alpha, + beta=beta, + device=device, + max_length=max_length, + batch_size=batch_size, + num_threads=num_threads, + verbose=verbose, + return_sentence_level_score=return_sentence_level_score, + ) + + +def _match_error_rate(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> _match_error_rate(preds=preds, target=target) + tensor(0.4444) + + """ + _deprecated_root_import_func("match_error_rate", "text") + return match_error_rate(preds=preds, target=target) + + +def _perplexity(preds: Tensor, target: Tensor, ignore_index: Optional[int] = None) -> Tensor: + """Wrapper for deprecated import. + + >>> from torch import rand, randint + >>> preds = rand(2, 8, 5) + >>> target = randint(5, (2, 8)) + >>> target[0, 6:] = -100 + >>> _perplexity(preds, target, ignore_index=-100) + tensor(5.8540) + + """ + _deprecated_root_import_func("perplexity", "text") + return perplexity(preds=preds, target=target, ignore_index=ignore_index) + + +def _rouge_score( + preds: Union[str, Sequence[str]], + target: Union[str, Sequence[str], Sequence[Sequence[str]]], + accumulate: Literal["avg", "best"] = "best", + use_stemmer: bool = False, + normalizer: Optional[Callable[[str], str]] = None, + tokenizer: Optional[Callable[[str], Sequence[str]]] = None, + rouge_keys: Union[str, tuple[str, ...]] = ("rouge1", "rouge2", "rougeL", "rougeLsum"), +) -> dict[str, Tensor]: + """Wrapper for deprecated import. + + >>> preds = "My name is John" + >>> target = "Is your name John" + >>> from pprint import pprint + >>> pprint(_rouge_score(preds, target)) + {'rouge1_fmeasure': tensor(0.7500), + 'rouge1_precision': tensor(0.7500), + 'rouge1_recall': tensor(0.7500), + 'rouge2_fmeasure': tensor(0.), + 'rouge2_precision': tensor(0.), + 'rouge2_recall': tensor(0.), + 'rougeL_fmeasure': tensor(0.5000), + 'rougeL_precision': tensor(0.5000), + 'rougeL_recall': tensor(0.5000), + 'rougeLsum_fmeasure': tensor(0.5000), + 'rougeLsum_precision': tensor(0.5000), + 'rougeLsum_recall': tensor(0.5000)} + + """ + _deprecated_root_import_func("rouge_score", "text") + return rouge_score( + preds=preds, + target=target, + accumulate=accumulate, + use_stemmer=use_stemmer, + normalizer=normalizer, + tokenizer=tokenizer, + rouge_keys=rouge_keys, + ) + + +def _sacre_bleu_score( + preds: Sequence[str], + target: Sequence[Sequence[str]], + n_gram: int = 4, + smooth: bool = False, + tokenize: Literal["none", "13a", "zh", "intl", "char"] = "13a", + lowercase: bool = False, + weights: Optional[Sequence[float]] = None, +) -> Tensor: + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> _sacre_bleu_score(preds, target) + tensor(0.7598) + + """ + _deprecated_root_import_func("sacre_bleu_score", "text") + return sacre_bleu_score( + preds=preds, + target=target, + n_gram=n_gram, + smooth=smooth, + tokenize=tokenize, + lowercase=lowercase, + weights=weights, + ) + + +def _squad(preds: Union[dict[str, str], list[dict[str, str]]], target: SQUAD_TARGETS_TYPE) -> dict[str, Tensor]: + """Wrapper for deprecated import. + + >>> preds = [{"prediction_text": "1976", "id": "56e10a3be3433e1400422b22"}] + >>> target = [{"answers": {"answer_start": [97], "text": ["1976"]},"id": "56e10a3be3433e1400422b22"}] + >>> _squad(preds, target) + {'exact_match': tensor(100.), 'f1': tensor(100.)} + + """ + _deprecated_root_import_func("squad", "text") + return squad(preds=preds, target=target) + + +def _translation_edit_rate( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + normalize: bool = False, + no_punctuation: bool = False, + lowercase: bool = True, + asian_support: bool = False, + return_sentence_level_score: bool = False, +) -> Union[Tensor, tuple[Tensor, List[Tensor]]]: + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> _translation_edit_rate(preds, target) + tensor(0.1538) + + """ + _deprecated_root_import_func("translation_edit_rate", "text") + return translation_edit_rate( + preds=preds, + target=target, + normalize=normalize, + no_punctuation=no_punctuation, + lowercase=lowercase, + asian_support=asian_support, + return_sentence_level_score=return_sentence_level_score, + ) + + +def _word_error_rate(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> _word_error_rate(preds=preds, target=target) + tensor(0.5000) + + """ + _deprecated_root_import_func("word_error_rate", "text") + return word_error_rate(preds=preds, target=target) + + +def _word_information_lost(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> _word_information_lost(preds, target) + tensor(0.6528) + + """ + _deprecated_root_import_func("word_information_lost", "text") + return word_information_lost(preds=preds, target=target) + + +def _word_information_preserved(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> _word_information_preserved(preds, target) + tensor(0.3472) + + """ + _deprecated_root_import_func("word_information_preserved", "text") + return word_information_preserved(preds=preds, target=target) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/bert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/bert.py new file mode 100644 index 0000000000000000000000000000000000000000..c283efa071e2809feaf11185036c63f39126666c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/bert.py @@ -0,0 +1,590 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import csv +import logging +import urllib +from collections.abc import Iterator, Sequence +from contextlib import contextmanager +from typing import Any, Callable, List, Optional, Tuple, Union, cast + +import torch +from torch import Tensor +from torch.nn import Module +from torch.utils.data import DataLoader + +from torchmetrics.functional.text.helper_embedding_metric import ( + TextDataset, + TokenizedDataset, + _check_shape_of_model_output, + _get_progress_bar, + _input_data_collator, + _output_data_collator, + _process_attention_mask_for_special_tokens, +) +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.imports import _TQDM_AVAILABLE, _TRANSFORMERS_GREATER_EQUAL_4_4 + + +@contextmanager +def _ignore_log_warning() -> Iterator[None]: + """Ignore irrelevant fine-tuning warning from transformers when loading the model for BertScore.""" + logger = logging.getLogger("transformers.modeling_utils") + original_level = logger.getEffectiveLevel() + try: + logger.setLevel(logging.ERROR) + yield + finally: + logger.setLevel(original_level) + + +# Default model recommended in the original implementation. +_DEFAULT_MODEL = "roberta-large" + +if _TRANSFORMERS_GREATER_EQUAL_4_4: + from transformers import AutoModel, AutoTokenizer + + def _download_model_for_bert_score() -> None: + """Download intensive operations.""" + with _ignore_log_warning(): + AutoTokenizer.from_pretrained(_DEFAULT_MODEL) + AutoModel.from_pretrained(_DEFAULT_MODEL) + + if _SKIP_SLOW_DOCTEST and not _try_proceed_with_timeout(_download_model_for_bert_score): + __doctest_skip__ = ["bert_score"] +else: + __doctest_skip__ = ["bert_score"] + + +def _get_embeddings_and_idf_scale( + dataloader: DataLoader, + target_len: int, + model: Module, + device: Optional[Union[str, torch.device]] = None, + num_layers: Optional[int] = None, + all_layers: bool = False, + idf: bool = False, + verbose: bool = False, + user_forward_fn: Optional[Callable[[Module, dict[str, Tensor]], Tensor]] = None, +) -> Tuple[Tensor, Tensor]: + """Calculate sentence embeddings and the inverse-document-frequency scaling factor. + + Args: + dataloader: dataloader instance. + target_len: A length of the longest sequence in the data. Used for padding the model output. + model: BERT model. + device: A device to be used for calculation. + num_layers: The layer of representation to use. + all_layers: An indication whether representation from all model layers should be used for BERTScore. + idf: An Indication whether normalization using inverse document frequencies should be used. + verbose: An indication of whether a progress bar to be displayed during the embeddings' calculation. + user_forward_fn: + A user's own forward function used in a combination with ``user_model``. This function must + take ``user_model`` and a python dictionary of containing ``"input_ids"`` and ``"attention_mask"`` + represented by :class:`~torch.Tensor` as an input and return the model's output represented by the single + :class:`~torch.Tensor`. + + Return: + A tuple of :class:`~torch.Tensor`s containing the model's embeddings and the normalized tokens IDF. + When ``idf = False``, tokens IDF is not calculated, and a matrix of mean weights is returned instead. + For a single sentence, ``mean_weight = 1/seq_len``, where ``seq_len`` is a sum over the corresponding + ``attention_mask``. + + Raises: + ValueError: + If ``all_layers = True`` and a model, which is not from the ``transformers`` package, is used. + + """ + embeddings_list: List[Tensor] = [] + idf_scale_list: List[Tensor] = [] + for batch in _get_progress_bar(dataloader, verbose): + with torch.no_grad(): + batch = _input_data_collator(batch, device) + # Output shape: batch_size x num_layers OR 1 x sequence_length x bert_dim + if not all_layers: + if not user_forward_fn: + out = model(batch["input_ids"], batch["attention_mask"], output_hidden_states=True) + out = out.hidden_states[num_layers if num_layers is not None else -1] + else: + out = user_forward_fn(model, batch) + _check_shape_of_model_output(out, batch["input_ids"]) + out = out.unsqueeze(1) + else: + if user_forward_fn: + raise ValueError( + "The option `all_layers=True` can be used only with default `transformers` models." + ) + out = model(batch["input_ids"], batch["attention_mask"], output_hidden_states=True) + out = torch.cat([o.unsqueeze(1) for o in out.hidden_states], dim=1) + + out /= out.norm(dim=-1).unsqueeze(-1) # normalize embeddings + out, attention_mask = _output_data_collator(out, batch["attention_mask"], target_len) + processed_attention_mask = _process_attention_mask_for_special_tokens(attention_mask) + # Multiply embeddings with attention_mask (b=batch_size, l=num_layers, s=seq_len, d=emb_dim) + out = torch.einsum("blsd, bs -> blsd", out, processed_attention_mask) + embeddings_list.append(out.cpu()) + + # Calculate weighted (w.r.t. sentence length) input_ids IDF matrix + input_ids_idf = ( + batch["input_ids_idf"] * processed_attention_mask if idf else processed_attention_mask.type(out.dtype) + ) + input_ids_idf /= input_ids_idf.sum(-1, keepdim=True) + idf_scale_list.append(input_ids_idf.cpu()) + + embeddings = torch.cat(embeddings_list) + idf_scale = torch.cat(idf_scale_list) + + return embeddings, idf_scale + + +def _get_scaled_precision_or_recall(cos_sim: Tensor, metric: str, idf_scale: Tensor) -> Tensor: + """Calculate precision or recall, transpose it and scale it with idf_scale factor.""" + dim = 3 if metric == "precision" else 2 + res = cos_sim.max(dim=dim).values + res = torch.einsum("bls, bs -> bls", res, idf_scale).sum(-1) + # We transpose the results and squeeze if possible to match the format of the original BERTScore implementation + return res.transpose(0, 1).squeeze() + + +def _get_precision_recall_f1( + preds_embeddings: Tensor, target_embeddings: Tensor, preds_idf_scale: Tensor, target_idf_scale: Tensor +) -> Tuple[Tensor, Tensor, Tensor]: + """Calculate precision, recall and F1 score over candidate and reference sentences. + + Args: + preds_embeddings: Embeddings of candidate sentences. + target_embeddings: Embeddings of reference sentences. + preds_idf_scale: An IDF scale factor for candidate sentences. + target_idf_scale: An IDF scale factor for reference sentences. + + Return: + Tensors containing precision, recall and F1 score, respectively. + + """ + # Dimensions: b = batch_size, l = num_layers, p = predictions_seq_len, r = references_seq_len, d = bert_dim + cos_sim = torch.einsum("blpd, blrd -> blpr", preds_embeddings, target_embeddings) + # Final metrics shape = (batch_size * num_layers | batch_size) + precision = _get_scaled_precision_or_recall(cos_sim, "precision", preds_idf_scale) + recall = _get_scaled_precision_or_recall(cos_sim, "recall", target_idf_scale) + + f1_score = 2 * precision * recall / (precision + recall) + f1_score = f1_score.masked_fill(torch.isnan(f1_score), 0.0) + + return precision, recall, f1_score + + +def _get_hash(model_name_or_path: Optional[str] = None, num_layers: Optional[int] = None, idf: bool = False) -> str: + """Compute `BERT_score`_ (copied and adjusted).""" + return f"{model_name_or_path}_L{num_layers}{'_idf' if idf else '_no-idf'}" + + +def _read_csv_from_local_file(baseline_path: str) -> Tensor: + """Read baseline from csv file from the local file. + + This method implemented to avoid `pandas` dependency. + + """ + with open(baseline_path) as fname: + csv_file = csv.reader(fname) + baseline_list = [[float(item) for item in row] for idx, row in enumerate(csv_file) if idx > 0] + return torch.tensor(baseline_list)[:, 1:] + + +def _read_csv_from_url(baseline_url: str) -> Tensor: + """Read baseline from csv file from URL. + + This method is implemented to avoid `pandas` dependency. + + """ + with urllib.request.urlopen(baseline_url) as http_request: + baseline_list = [ + [float(item) for item in row.strip().decode("utf-8").split(",")] + for idx, row in enumerate(http_request) + if idx > 0 + ] + return torch.tensor(baseline_list)[:, 1:] + + +def _load_baseline( + lang: str = "en", + model_name_or_path: Optional[str] = None, + baseline_path: Optional[str] = None, + baseline_url: Optional[str] = None, +) -> Optional[Tensor]: + """Load a CSV file with the baseline values used for rescaling.""" + if baseline_path: + baseline: Optional[Tensor] = _read_csv_from_local_file(baseline_path) + elif baseline_url: + baseline = _read_csv_from_url(baseline_url) + # Read default baseline from the original `bert-score` package https://github.com/Tiiiger/bert_score + elif lang and model_name_or_path: + url_base = "https://raw.githubusercontent.com/Tiiiger/bert_score/master/bert_score/rescale_baseline" + baseline_url = f"{url_base}/{lang}/{model_name_or_path}.tsv" + baseline = _read_csv_from_url(baseline_url) + else: + rank_zero_warn("Baseline was not successfully loaded. No baseline is going to be used.") + return None + + return baseline + + +def _rescale_metrics_with_baseline( + precision: Tensor, + recall: Tensor, + f1_score: Tensor, + baseline: Tensor, + num_layers: Optional[int] = None, + all_layers: bool = False, +) -> Tuple[Tensor, Tensor, Tensor]: + """Rescale the computed metrics with the pre-computed baseline.""" + if num_layers is None and all_layers is False: + num_layers = -1 + all_metrics = torch.stack([precision, recall, f1_score], dim=-1) + baseline_scale = baseline.unsqueeze(1) if all_layers else baseline[num_layers] + all_metrics = (all_metrics - baseline_scale) / (1 - baseline_scale) + + return all_metrics[..., 0], all_metrics[..., 1], all_metrics[..., 2] + + +def _preprocess_multiple_references( + preds: List[str], target: List[Union[str, Sequence[str]]] +) -> Tuple[List[str], List[str], Optional[List[Tuple[int, int]]]]: + """Preprocesses predictions and targets when dealing with multiple references. + + This function handles the case where a single prediction might have multiple + reference targets (represented as a list/tuple of strings). + + Args: + preds: A list of predictions + target: A list of targets, where each item could be a string or a list/tuple of strings + + Returns: + Tuple: (preds, target, ref_group_boundaries) + - preds: Flattened list of `str` + - target: Flattened list of `str` + - ref_group_boundaries: List of tuples (start, end) indicating the boundaries + of reference groups in the flattened lists or `None` + + """ + if not all(isinstance(item, str) for item in preds): + raise ValueError("Invalid input provided.") + + has_nested_sequences = any(isinstance(item, (list, tuple)) for item in target) + + if has_nested_sequences: + ref_group_boundaries: List[Tuple[int, int]] = [] + new_preds: List[str] = [] + new_target: List[str] = [] + count = 0 + + for pred, ref_group in zip(preds, target): + if isinstance(ref_group, (list, tuple)): + new_preds.extend([pred] * len(ref_group)) + new_target.extend(cast(List[str], ref_group)) + ref_group_boundaries.append((count, count + len(ref_group))) + count += len(ref_group) + else: + new_preds.append(pred) + new_target.append(cast(str, ref_group)) + ref_group_boundaries.append((count, count + 1)) + count += 1 + return new_preds, new_target, ref_group_boundaries + return preds, cast(List[str], target), None + + +def _postprocess_multiple_references( + precision: Tensor, recall: Tensor, f1_score: Tensor, ref_group_boundaries: List[Tuple[int, int]] +) -> Tuple[Tensor, Tensor, Tensor]: + """Postprocesses metrics when dealing with multiple references. + + For each group of references that correspond to a single prediction, + this function takes the maximum score among all references. + + Args: + precision: Tensor of precision scores + recall: Tensor of recall scores + f1_score: Tensor of F1 scores + ref_group_boundaries: List of tuples (start, end) indicating the boundaries + of reference groups + + Returns: + tuple: (precision, recall, f1_score) with updated metrics + + """ + max_precision, max_recall, max_f1 = [], [], [] + + for start, end in ref_group_boundaries: + if precision.dim() > 1: # all_layers=True case + max_precision.append(precision[:, start:end].max(dim=1)[0]) + max_recall.append(recall[:, start:end].max(dim=1)[0]) + max_f1.append(f1_score[:, start:end].max(dim=1)[0]) + else: # standard case + max_precision.append(precision[start:end].max()) + max_recall.append(recall[start:end].max()) + max_f1.append(f1_score[start:end].max()) + + if precision.dim() > 1: + precision = torch.stack(max_precision, dim=1) + recall = torch.stack(max_recall, dim=1) + f1_score = torch.stack(max_f1, dim=1) + else: + precision = torch.stack(max_precision) + recall = torch.stack(max_recall) + f1_score = torch.stack(max_f1) + + return precision, recall, f1_score + + +def bert_score( + preds: Union[str, Sequence[str], dict[str, Tensor]], + target: Union[str, Sequence[str], Sequence[Sequence[str]], dict[str, Tensor]], + model_name_or_path: Optional[str] = None, + num_layers: Optional[int] = None, + all_layers: bool = False, + model: Optional[Module] = None, + user_tokenizer: Any = None, + user_forward_fn: Optional[Callable[[Module, dict[str, Tensor]], Tensor]] = None, + verbose: bool = False, + idf: bool = False, + device: Optional[Union[str, torch.device]] = None, + max_length: int = 512, + batch_size: int = 64, + num_threads: int = 0, + return_hash: bool = False, + lang: str = "en", + rescale_with_baseline: bool = False, + baseline_path: Optional[str] = None, + baseline_url: Optional[str] = None, + truncation: bool = False, +) -> dict[str, Union[Tensor, List[float], str]]: + """`Bert_score Evaluating Text Generation`_ for text similirity matching. + + This metric leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference + sentences by cosine similarity. It has been shown to correlate with human judgment on sentence-level and + system-level evaluation. Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for + evaluating different language generation tasks. + + This implementation follows the original implementation from `BERT_score`_. + + Args: + preds (Union[str, Sequence[str]]): A single predicted sentence or a sequence of predicted sentences. + target (Union[str, Sequence[str], Sequence[Sequence[str]]]): A single target sentence, a sequence of target + sentences, or a sequence of sequences of target sentences for multiple references per prediction. + model_name_or_path: A name or a model path used to load ``transformers`` pretrained model. + num_layers: A layer of representation to use. + all_layers: + An indication of whether the representation from all model's layers should be used. + If ``all_layers = True``, the argument ``num_layers`` is ignored. + model: A user's own model. + user_tokenizer: + A user's own tokenizer used with the own model. This must be an instance with the ``__call__`` method. + This method must take an iterable of sentences (``List[str]``) and must return a python dictionary + containing ``"input_ids"`` and ``"attention_mask"`` represented by :class:`~torch.Tensor`. + It is up to the user's model of whether ``"input_ids"`` is a :class:`~torch.Tensor` of input ids + or embedding vectors. his tokenizer must prepend an equivalent of ``[CLS]`` token and append an equivalent + of ``[SEP]`` token as `transformers` tokenizer does. + user_forward_fn: + A user's own forward function used in a combination with ``user_model``. + This function must take ``user_model`` and a python dictionary of containing ``"input_ids"`` + and ``"attention_mask"`` represented by :class:`~torch.Tensor` as an input and return the model's output + represented by the single :class:`~torch.Tensor`. + verbose: An indication of whether a progress bar to be displayed during the embeddings' calculation. + idf: An indication of whether normalization using inverse document frequencies should be used. + device: A device to be used for calculation. + max_length: A maximum length of input sequences. Sequences longer than ``max_length`` are to be trimmed. + batch_size: A batch size used for model processing. + num_threads: A number of threads to use for a dataloader. + return_hash: An indication of whether the correspodning ``hash_code`` should be returned. + lang: A language of input sentences. It is used when the scores are rescaled with a baseline. + rescale_with_baseline: + An indication of whether bertscore should be rescaled with a pre-computed baseline. + When a pretrained model from ``transformers`` model is used, the corresponding baseline is downloaded + from the original ``bert-score`` package from `BERT_score`_ if available. + In other cases, please specify a path to the baseline csv/tsv file, which must follow the formatting + of the files from `BERT_score`_ + baseline_path: A path to the user's own local csv/tsv file with the baseline scale. + baseline_url: A url path to the user's own csv/tsv file with the baseline scale. + truncation: An indication of whether the input sequences should be truncated to the maximum length. + + Returns: + Python dictionary containing the keys ``precision``, ``recall`` and ``f1`` with corresponding values. + + Raises: + ValueError: + If ``len(preds) != len(target)``. + ModuleNotFoundError: + If `tqdm` package is required and not installed. + ModuleNotFoundError: + If ``transformers`` package is required and not installed. + ValueError: + If ``num_layer`` is larger than the number of the model layers. + ValueError: + If invalid input is provided. + + Example: + >>> from pprint import pprint + >>> from torchmetrics.functional.text.bert import bert_score + >>> preds = ["hello there", "general kenobi"] + >>> target = ["hello there", "master kenobi"] + >>> pprint(bert_score(preds, target)) + {'f1': tensor([1.0000, 0.9961]), 'precision': tensor([1.0000, 0.9961]), 'recall': tensor([1.0000, 0.9961])} + + Example: + >>> from pprint import pprint + >>> from torchmetrics.functional.text.bert import bert_score + >>> preds = ["hello there", "general kenobi"] + >>> target = [["hello there", "master kenobi"], ["hello there", "master kenobi"]] + >>> pprint(bert_score(preds, target)) + {'f1': tensor([1.0000, 0.9961]), 'precision': tensor([1.0000, 0.9961]), 'recall': tensor([1.0000, 0.9961])} + + """ + ref_group_boundaries: Optional[List[Tuple[int, int]]] = None + + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + if not isinstance(preds, (list, dict)): # dict for BERTScore class compute call + preds = list(preds) + if not isinstance(target, (list, dict)): # dict for BERTScore class compute call + target = list(target) + + if len(preds) != len(target): + raise ValueError( + "Expected number of predicted and reference sentences to be the same, but got" + f"{len(preds)} and {len(target)}" + ) + + if isinstance(preds, list) and len(preds) > 0 and isinstance(target, list) and len(target) > 0: + preds, target, ref_group_boundaries = _preprocess_multiple_references(preds, target) + + if not isinstance(idf, bool): + raise ValueError(f"Expected argument `idf` to be a boolean, but got {idf}.") + + if verbose and (not _TQDM_AVAILABLE): + raise ModuleNotFoundError( + "An argument `verbose = True` requires `tqdm` package be installed. Install with `pip install tqdm`." + ) + + if model is None: + if not _TRANSFORMERS_GREATER_EQUAL_4_4: + raise ModuleNotFoundError( + "`bert_score` metric with default models requires `transformers` package be installed." + " Either install with `pip install transformers>=4.4` or `pip install torchmetrics[text]`." + ) + if model_name_or_path is None: + rank_zero_warn( + "The argument `model_name_or_path` was not specified while it is required when default" + " `transformers` model are used." + f"It is, therefore, used the default recommended model - {_DEFAULT_MODEL}." + ) + with _ignore_log_warning(): + tokenizer = AutoTokenizer.from_pretrained(model_name_or_path or _DEFAULT_MODEL) + model = AutoModel.from_pretrained(model_name_or_path or _DEFAULT_MODEL) + else: + tokenizer = user_tokenizer + model.eval() + model.to(device) + + try: + if hasattr(model.config, "num_hidden_layers") and isinstance(model.config.num_hidden_layers, int): + if num_layers and num_layers > model.config.num_hidden_layers: + raise ValueError( + f"num_layers={num_layers} is forbidden for {model_name_or_path}." + f" Please use num_layers <= {model.config.num_hidden_layers}" + ) + else: + rank_zero_warn( + "Model config does not have `num_hidden_layers` as an integer attribute. " + "Unable to validate `num_layers`." + ) + except AttributeError: + rank_zero_warn("It was not possible to retrieve the parameter `num_layers` from the model specification.") + + _are_empty_lists = all(isinstance(text, list) and len(text) == 0 for text in (preds, target)) + _are_valid_lists = all( + isinstance(text, list) and len(text) > 0 and isinstance(text[0], str) for text in (preds, target) + ) + _are_valid_tensors = all( + isinstance(text, dict) and isinstance(text["input_ids"], Tensor) for text in (preds, target) + ) + if _are_empty_lists: + rank_zero_warn("Predictions and references are empty.") + output_dict: dict[str, Union[Tensor, List[float], str]] = { + "precision": [0.0], + "recall": [0.0], + "f1": [0.0], + } + if return_hash: + output_dict.update({"hash": _get_hash(model_name_or_path, num_layers, idf)}) + return output_dict + + # Load baselines if needed + baseline = _load_baseline(lang, model_name_or_path, baseline_path, baseline_url) if rescale_with_baseline else None + + # We ignore mypy typing below as the proper typing is ensured by conditions above, only mypy cannot infer that. + if _are_valid_lists: + target_dataset = TextDataset(target, tokenizer, max_length, idf=idf, truncation=truncation) # type: ignore + preds_dataset = TextDataset( + preds, # type: ignore + tokenizer, + max_length, + idf=idf, + tokens_idf=target_dataset.tokens_idf, + truncation=truncation, + ) + elif _are_valid_tensors: + target_dataset = TokenizedDataset(**target, idf=idf) # type: ignore + preds_dataset = TokenizedDataset(**preds, idf=idf, tokens_idf=target_dataset.tokens_idf) # type: ignore + else: + raise ValueError("Invalid input provided.") + + target_loader = DataLoader(target_dataset, batch_size=batch_size, num_workers=num_threads) + preds_loader = DataLoader(preds_dataset, batch_size=batch_size, num_workers=num_threads) + + target_embeddings, target_idf_scale = _get_embeddings_and_idf_scale( + target_loader, target_dataset.max_length, model, device, num_layers, all_layers, idf, verbose, user_forward_fn + ) + preds_embeddings, preds_idf_scale = _get_embeddings_and_idf_scale( + preds_loader, preds_dataset.max_length, model, device, num_layers, all_layers, idf, verbose, user_forward_fn + ) + + preds_embeddings = preds_embeddings[preds_loader.dataset.sorting_indices] + target_embeddings = target_embeddings[target_loader.dataset.sorting_indices] + + preds_idf_scale = preds_idf_scale[preds_loader.dataset.sorting_indices] + target_idf_scale = target_idf_scale[target_loader.dataset.sorting_indices] + + precision, recall, f1_score = _get_precision_recall_f1( + preds_embeddings, target_embeddings, preds_idf_scale, target_idf_scale + ) + + if baseline is not None: + precision, recall, f1_score = _rescale_metrics_with_baseline( + precision, recall, f1_score, baseline, num_layers, all_layers + ) + + if ref_group_boundaries is not None: + precision, recall, f1_score = _postprocess_multiple_references( + precision, recall, f1_score, ref_group_boundaries + ) + + output_dict = { + "precision": precision, + "recall": recall, + "f1": f1_score, + } + if return_hash: + output_dict.update({"hash": _get_hash(model_name_or_path, num_layers, idf)}) + return output_dict diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/bleu.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/bleu.py new file mode 100644 index 0000000000000000000000000000000000000000..52b8bb17432ba6ad61073f30517f58c137e48fc1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/bleu.py @@ -0,0 +1,210 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# referenced from +# Library Name: torchtext +# Authors: torchtext authors and @sluks +# Date: 2020-07-18 +# Link: https://pytorch.org/text/_modules/torchtext/data/metrics.html#bleu_score +from collections import Counter +from collections.abc import Sequence +from typing import Callable, Optional, Union + +import torch +from torch import Tensor, tensor + + +def _count_ngram(ngram_input_list: Sequence[str], n_gram: int) -> Counter: + """Count how many times each word appears in a given text with ngram. + + Args: + ngram_input_list: A list of translated text or reference texts + n_gram: gram value ranged 1 to 4 + + Return: + ngram_counter: a collections.Counter object of ngram + + """ + ngram_counter: Counter = Counter() + + for i in range(1, n_gram + 1): + for j in range(len(ngram_input_list) - i + 1): + ngram_key = tuple(ngram_input_list[j : (i + j)]) + ngram_counter[ngram_key] += 1 + + return ngram_counter + + +def _tokenize_fn(sentence: str) -> Sequence[str]: + """Tokenizes sentence into list of words. + + Args: + sentence: A sentence separated by white space. + + Return: + List of words + + """ + return sentence.split() + + +def _bleu_score_update( + preds: Sequence[str], + target: Sequence[Sequence[str]], + numerator: Tensor, + denominator: Tensor, + preds_len: Tensor, + target_len: Tensor, + n_gram: int = 4, + tokenizer: Callable[[str], Sequence[str]] = _tokenize_fn, +) -> tuple[Tensor, Tensor]: + """Update and returns variables required to compute the BLEU score. + + Args: + preds: An iterable of machine translated corpus + target: An iterable of iterables of reference corpus + numerator: Numerator of precision score (true positives) + denominator: Denominator of precision score (true positives + false positives) + preds_len: count of words in a candidate prediction + target_len: count of words in a reference translation + target: count of words in a reference translation + n_gram: gram value ranged 1 to 4 + tokenizer: A function that turns sentence into list of words + + """ + target_: Sequence[Sequence[Sequence[str]]] = [[tokenizer(line) if line else [] for line in t] for t in target] + preds_: Sequence[Sequence[str]] = [tokenizer(line) if line else [] for line in preds] + + for pred, targets in zip(preds_, target_): + preds_len += len(pred) + target_len_list = [len(tgt) for tgt in targets] + target_len_diff = [abs(len(pred) - x) for x in target_len_list] + target_len += target_len_list[target_len_diff.index(min(target_len_diff))] + preds_counter: Counter = _count_ngram(pred, n_gram) + target_counter: Counter = Counter() + + for tgt in targets: + target_counter |= _count_ngram(tgt, n_gram) + + ngram_counter_clip = preds_counter & target_counter + + for counter_clip in ngram_counter_clip: + numerator[len(counter_clip) - 1] += ngram_counter_clip[counter_clip] + + for counter in preds_counter: + denominator[len(counter) - 1] += preds_counter[counter] + + return preds_len, target_len + + +def _bleu_score_compute( + preds_len: Tensor, + target_len: Tensor, + numerator: Tensor, + denominator: Tensor, + n_gram: int, + weights: Sequence[float], + smooth: bool, +) -> Tensor: + """Compute the BLEU score. + + Args: + preds_len: count of words in a candidate translation + target_len: count of words in a reference translation + numerator: Numerator of precision score (true positives) + denominator: Denominator of precision score (true positives + false positives) + n_gram: gram value ranged 1 to 4 + weights: Weights used for unigrams, bigrams, etc. to calculate BLEU score. + smooth: Whether to apply smoothing + + """ + device = numerator.device + if min(numerator) == 0.0: + return tensor(0.0, device=device) + + if smooth: + precision_scores = torch.div( + torch.add(numerator, torch.ones(n_gram, device=device)), + torch.add(denominator, torch.ones(n_gram, device=device)), + ) + precision_scores[0] = numerator[0] / denominator[0] + else: + precision_scores = numerator / denominator + + log_precision_scores = tensor(weights, device=device) * torch.log(precision_scores) + geometric_mean = torch.exp(torch.sum(log_precision_scores)) + brevity_penalty = tensor(1.0, device=device) if preds_len > target_len else torch.exp(1 - (target_len / preds_len)) + return brevity_penalty * geometric_mean + + +def bleu_score( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + n_gram: int = 4, + smooth: bool = False, + weights: Optional[Sequence[float]] = None, +) -> Tensor: + """Calculate `BLEU score`_ of machine translated text with one or more references. + + Args: + preds: An iterable of machine translated corpus + target: An iterable of iterables of reference corpus + n_gram: Gram value ranged from 1 to 4 + smooth: Whether to apply smoothing - see [2] + weights: + Weights used for unigrams, bigrams, etc. to calculate BLEU score. + If not provided, uniform weights are used. + + Return: + Tensor with BLEU Score + + Raises: + ValueError: If ``preds`` and ``target`` corpus have different lengths. + ValueError: If a length of a list of weights is not ``None`` and not equal to ``n_gram``. + + Example: + >>> from torchmetrics.functional.text import bleu_score + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> bleu_score(preds, target) + tensor(0.7598) + + References: + [1] BLEU: a Method for Automatic Evaluation of Machine Translation by Papineni, + Kishore, Salim Roukos, Todd Ward, and Wei-Jing Zhu `BLEU`_ + + [2] Automatic Evaluation of Machine Translation Quality Using Longest Common Subsequence + and Skip-Bigram Statistics by Chin-Yew Lin and Franz Josef Och `Machine Translation Evolution`_ + + """ + preds_ = [preds] if isinstance(preds, str) else preds + target_ = [[tgt] if isinstance(tgt, str) else tgt for tgt in target] + + if len(preds_) != len(target_): + raise ValueError(f"Corpus has different size {len(preds_)} != {len(target_)}") + + if weights is not None and len(weights) != n_gram: + raise ValueError(f"List of weights has different weights than `n_gram`: {len(weights)} != {n_gram}") + if weights is None: + weights = [1.0 / n_gram] * n_gram + + numerator = torch.zeros(n_gram) + denominator = torch.zeros(n_gram) + preds_len = tensor(0.0) + target_len = tensor(0.0) + + preds_len, target_len = _bleu_score_update( + preds_, target_, numerator, denominator, preds_len, target_len, n_gram, _tokenize_fn + ) + + return _bleu_score_compute(preds_len, target_len, numerator, denominator, n_gram, weights, smooth) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/cer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/cer.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ee191c449ceea88772c7ea263fea5b2b896a08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/cer.py @@ -0,0 +1,87 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.helper import _edit_distance + + +def _cer_update( + preds: Union[str, list[str]], + target: Union[str, list[str]], +) -> tuple[Tensor, Tensor]: + """Update the cer score with the current set of references and predictions. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Number of edit operations to get from the reference to the prediction, summed over all samples + Number of character overall references + + """ + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + errors = tensor(0, dtype=torch.float) + total = tensor(0, dtype=torch.float) + for pred, tgt in zip(preds, target): + pred_tokens = pred + tgt_tokens = tgt + errors += _edit_distance(list(pred_tokens), list(tgt_tokens)) + total += len(tgt_tokens) + return errors, total + + +def _cer_compute(errors: Tensor, total: Tensor) -> Tensor: + """Compute the Character error rate. + + Args: + errors: Number of edit operations to get from the reference to the prediction, summed over all samples + total: Number of characters over all references + + Returns: + Character error rate score + + """ + return errors / total + + +def char_error_rate(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Compute Character Error Rate used for performance of an automatic speech recognition system. + + This value indicates the percentage of characters that were incorrectly predicted. The lower the value, the better + the performance of the ASR system with a CER of 0 being a perfect score. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Character error rate score + + Examples: + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> char_error_rate(preds=preds, target=target) + tensor(0.3415) + + """ + errors, total = _cer_update(preds, target) + return _cer_compute(errors, total) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/chrf.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/chrf.py new file mode 100644 index 0000000000000000000000000000000000000000..29d97a10c2ce524a34d125e3e898758b456948f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/chrf.py @@ -0,0 +1,638 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# Copyright 2017 Maja Popovic +# The code is derived from https://github.com/m-popovic/chrF/blob/6d3c384/chrF%2B%2B.py +# The original author and copyright holder have agreed to relicense the derived code under the Apache License, +# Version 2.0 (the "License") +# Reference to the approval: https://github.com/Lightning-AI/torchmetrics/pull/2701#issuecomment-2316891785 + +from collections import defaultdict +from collections.abc import Sequence +from itertools import chain +from typing import List, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.helper import _validate_inputs + +_EPS_SMOOTHING = tensor(1e-16) +# Taken from https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py +_PUNCTUATIONS = set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") + + +def _prepare_n_grams_dicts( + n_char_order: int, n_word_order: int +) -> tuple[ + dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor] +]: + """Prepare dictionaries with default zero values for total ref, hypothesis and matching character and word n-grams. + + Args: + n_char_order: A character n-gram order. + n_word_order: A word n-gram order. + + Return: + Dictionaries with default zero values for total reference, hypothesis and matching character and word + n-grams. + + """ + total_preds_char_n_grams: dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_char_order)} + total_preds_word_n_grams: dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_word_order)} + total_target_char_n_grams: dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_char_order)} + total_target_word_n_grams: dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_word_order)} + total_matching_char_n_grams: dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_char_order)} + total_matching_word_n_grams: dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_word_order)} + + return ( + total_preds_char_n_grams, + total_preds_word_n_grams, + total_target_char_n_grams, + total_target_word_n_grams, + total_matching_char_n_grams, + total_matching_word_n_grams, + ) + + +def _get_characters(sentence: str, whitespace: bool) -> list[str]: + """Split sentence into individual characters. + + Args: + sentence: An input sentence to split. + whitespace: An indication whether to keep whitespaces during character n-gram extraction. + + Return: + A list of separated characters. + + """ + if whitespace: + return list(sentence) + return list(sentence.strip().replace(" ", "")) + + +def _separate_word_and_punctuation(word: str) -> list[str]: + """Separates out punctuation from beginning and end of words for chrF. + + Adapted from https://github.com/m-popovic/chrF and + https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py. + + Args: + word: An input word to be separated from a punctuation if present. + + Return: + A list of a single word or a separated word and punctuation. + + """ + if len(word) == 1: + return [word] + + if word[-1] in _PUNCTUATIONS: + return [word[:-1], word[-1]] + if word[0] in _PUNCTUATIONS: + return [word[0], word[1:]] + return [word] + + +def _get_words_and_punctuation(sentence: str) -> list[str]: + """Separates out punctuation from beginning and end of words for chrF for all words in the sentence. + + Args: + sentence: An input sentence to split + + Return: + An aggregated list of separated words and punctuation. + + """ + return list(chain.from_iterable(_separate_word_and_punctuation(word) for word in sentence.strip().split())) + + +def _ngram_counts(char_or_word_list: list[str], n_gram_order: int) -> dict[int, dict[tuple[str, ...], Tensor]]: + """Calculate n-gram counts. + + Args: + char_or_word_list: A list of characters of words + n_gram_order: The largest number of n-gram. + + Return: + A dictionary of dictionaries with a counts of given n-grams. + + """ + ngrams: dict[int, dict[tuple[str, ...], Tensor]] = defaultdict(lambda: defaultdict(lambda: tensor(0.0))) + for n in range(1, n_gram_order + 1): + for ngram in (tuple(char_or_word_list[i : i + n]) for i in range(len(char_or_word_list) - n + 1)): + ngrams[n][ngram] += tensor(1) + return ngrams + + +def _get_n_grams_counts_and_total_ngrams( + sentence: str, n_char_order: int, n_word_order: int, lowercase: bool, whitespace: bool +) -> tuple[ + dict[int, dict[tuple[str, ...], Tensor]], + dict[int, dict[tuple[str, ...], Tensor]], + dict[int, Tensor], + dict[int, Tensor], +]: + """Get n-grams and total n-grams. + + Args: + sentence: An input sentence + n_char_order: A character n-gram order. + n_word_order: A word n-gram order. + lowercase: An indication whether to enable case-insensitivity. + whitespace: An indication whether to keep whitespaces during character n-gram extraction. + + Return: + char_n_grams_counts: A dictionary of dictionaries with sentence character n-grams. + word_n_grams_counts: A dictionary of dictionaries with sentence word n-grams. + total_char_n_grams: A dictionary containing a total number of sentence character n-grams. + total_word_n_grams: A dictionary containing a total number of sentence word n-grams. + + """ + + def _char_and_word_ngrams_counts( + sentence: str, n_char_order: int, n_word_order: int, lowercase: bool + ) -> tuple[dict[int, dict[tuple[str, ...], Tensor]], dict[int, dict[tuple[str, ...], Tensor]]]: + """Get a dictionary of dictionaries with a counts of given n-grams.""" + if lowercase: + sentence = sentence.lower() + char_n_grams_counts = _ngram_counts(_get_characters(sentence, whitespace), n_char_order) + word_n_grams_counts = _ngram_counts(_get_words_and_punctuation(sentence), n_word_order) + return char_n_grams_counts, word_n_grams_counts + + def _get_total_ngrams(n_grams_counts: dict[int, dict[tuple[str, ...], Tensor]]) -> dict[int, Tensor]: + """Get total sum of n-grams over n-grams w.r.t n.""" + total_n_grams: dict[int, Tensor] = defaultdict(lambda: tensor(0.0)) + for n in n_grams_counts: + total_n_grams[n] = sum(n_grams_counts[n].values()).detach().clone() # type: ignore + return total_n_grams + + char_n_grams_counts, word_n_grams_counts = _char_and_word_ngrams_counts( + sentence, n_char_order, n_word_order, lowercase + ) + total_char_n_grams = _get_total_ngrams(char_n_grams_counts) + total_word_n_grams = _get_total_ngrams(word_n_grams_counts) + + return char_n_grams_counts, word_n_grams_counts, total_char_n_grams, total_word_n_grams + + +def _get_ngram_matches( + hyp_n_grams_counts: dict[int, dict[tuple[str, ...], Tensor]], + ref_n_grams_counts: dict[int, dict[tuple[str, ...], Tensor]], +) -> dict[int, Tensor]: + """Get a number of n-gram matches between reference and hypothesis n-grams. + + Args: + hyp_n_grams_counts: n-grams counts for hypothesis + ref_n_grams_counts: n-grams counts for reference + + Return: + matching_n_grams + + """ + matching_n_grams: dict[int, Tensor] = defaultdict(lambda: tensor(0.0)) + for n in hyp_n_grams_counts: + min_n_grams = [ + torch.min(ref_n_grams_counts[n][n_gram], hyp_n_grams_counts[n][n_gram]) for n_gram in hyp_n_grams_counts[n] + ] + matching_n_grams[n] = sum(min_n_grams).detach().clone() # type: ignore + return matching_n_grams + + +def _sum_over_dicts(total_n_grams: dict[int, Tensor], n_grams: dict[int, Tensor]) -> dict[int, Tensor]: + """Aggregate total n-grams to keep corpus-level statistics. + + Args: + total_n_grams: A dictionary containing a total corpus-level number of n-grams. + n_grams: A dictionary containing a sentence-level number of n-grams. + + Return: + A dictionary containing a total corpus-level number of n-grams. + + """ + for n in n_grams: + total_n_grams[n] += n_grams[n] + return total_n_grams + + +def _calculate_fscore( + matching_char_n_grams: dict[int, Tensor], + matching_word_n_grams: dict[int, Tensor], + hyp_char_n_grams: dict[int, Tensor], + hyp_word_n_grams: dict[int, Tensor], + ref_char_n_grams: dict[int, Tensor], + ref_word_n_grams: dict[int, Tensor], + n_order: float, + beta: float, +) -> Tensor: + """Calculate sentence-level chrF/chrF++ score. + + For given hypothesis and reference statistics (either sentence-level or corpus-level) + the chrF/chrF++ score is returned. + + Args: + matching_char_n_grams: + A total number of matching character n-grams between the best matching reference and hypothesis. + matching_word_n_grams: + A total number of matching word n-grams between the best matching reference and hypothesis. + hyp_char_n_grams: A total number of hypothesis character n-grams. + hyp_word_n_grams: A total number of hypothesis word n-grams. + ref_char_n_grams: A total number of reference character n-grams. + ref_word_n_grams: A total number of reference word n-grams. + n_order: A sum of character and word n-gram order. + beta: A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal. + + Return: + A chrF/chrF++ score. This function is universal both for sentence-level and corpus-level calculation. + + """ + + def _get_n_gram_fscore( + matching_n_grams: dict[int, Tensor], ref_n_grams: dict[int, Tensor], hyp_n_grams: dict[int, Tensor], beta: float + ) -> dict[int, Tensor]: + """Get n-gram level f-score.""" + precision: dict[int, Tensor] = { + n: matching_n_grams[n] / hyp_n_grams[n] if hyp_n_grams[n] > 0 else tensor(0.0) for n in matching_n_grams + } + recall: dict[int, Tensor] = { + n: matching_n_grams[n] / ref_n_grams[n] if ref_n_grams[n] > 0 else tensor(0.0) for n in matching_n_grams + } + denominator: dict[int, Tensor] = { + n: torch.max(beta**2 * precision[n] + recall[n], _EPS_SMOOTHING) for n in matching_n_grams + } + f_score: dict[int, Tensor] = { + n: (1 + beta**2) * precision[n] * recall[n] / denominator[n] for n in matching_n_grams + } + + return f_score + + char_n_gram_f_score = _get_n_gram_fscore(matching_char_n_grams, ref_char_n_grams, hyp_char_n_grams, beta) + word_n_gram_f_score = _get_n_gram_fscore(matching_word_n_grams, ref_word_n_grams, hyp_word_n_grams, beta) + + return (sum(char_n_gram_f_score.values()) + sum(word_n_gram_f_score.values())) / tensor(n_order) + + +def _calculate_sentence_level_chrf_score( + targets: list[str], + pred_char_n_grams_counts: dict[int, dict[tuple[str, ...], Tensor]], + pred_word_n_grams_counts: dict[int, dict[tuple[str, ...], Tensor]], + pred_char_n_grams: dict[int, Tensor], + pred_word_n_grams: dict[int, Tensor], + n_char_order: int, + n_word_order: int, + n_order: float, + beta: float, + lowercase: bool, + whitespace: bool, +) -> tuple[Tensor, dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor]]: + """Calculate the best sentence-level chrF/chrF++ score. + + For a given pre-processed hypothesis, all references are evaluated and score and statistics + for the best matching reference is returned. + + Args: + targets: An iterable of references. + pred_char_n_grams_counts: A dictionary of dictionaries with hypothesis character n-grams. + pred_word_n_grams_counts: A dictionary of dictionaries with hypothesis word n-grams. + pred_char_n_grams: A total number of hypothesis character n-grams. + pred_word_n_grams: A total number of hypothesis word n-grams. + n_char_order: A character n-gram order. + n_word_order: A word n-gram order. + n_order: A sum of character and word n-gram order. + beta: A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal. + lowercase: An indication whether to enable case-insensitivity. + whitespace: An indication whether to keep whitespaces during character n-gram extraction. + + Return: + Return chrF/chrF++ score and statistics for the best matching hypothesis and reference. + + f_score: A sentence-level chrF/chrF++ score. + matching_char_n_grams: + A total number of matching character n-grams between the best matching reference and hypothesis. + matching_word_n_grams: + A total number of matching word n-grams between the best matching reference and hypothesis. + target_char_n_grams: A total number of reference character n-grams. + target_word_n_grams: A total number of reference word n-grams. + + """ + best_f_score = tensor(0.0) + best_matching_char_n_grams: dict[int, Tensor] = defaultdict(lambda: tensor(0.0)) + best_matching_word_n_grams: dict[int, Tensor] = defaultdict(lambda: tensor(0.0)) + best_target_char_n_grams: dict[int, Tensor] = defaultdict(lambda: tensor(0.0)) + best_target_word_n_grams: dict[int, Tensor] = defaultdict(lambda: tensor(0.0)) + + for target in targets: + ( + target_char_n_grams_counts, + target_word_n_grams_counts, + target_char_n_grams, + target_word_n_grams, + ) = _get_n_grams_counts_and_total_ngrams(target, n_char_order, n_word_order, lowercase, whitespace) + matching_char_n_grams = _get_ngram_matches(target_char_n_grams_counts, pred_char_n_grams_counts) + matching_word_n_grams = _get_ngram_matches(target_word_n_grams_counts, pred_word_n_grams_counts) + + f_score = _calculate_fscore( + matching_char_n_grams, + matching_word_n_grams, + pred_char_n_grams, + pred_word_n_grams, + target_char_n_grams, + target_word_n_grams, + n_order, + beta, + ) + + if f_score > best_f_score: + best_f_score = f_score + best_matching_char_n_grams = matching_char_n_grams + best_matching_word_n_grams = matching_word_n_grams + best_target_char_n_grams = target_char_n_grams + best_target_word_n_grams = target_word_n_grams + + return ( + best_f_score, + best_matching_char_n_grams, + best_matching_word_n_grams, + best_target_char_n_grams, + best_target_word_n_grams, + ) + + +def _chrf_score_update( + preds: Union[str, Sequence[str]], + target: Union[Sequence[str], Sequence[Sequence[str]]], + total_preds_char_n_grams: dict[int, Tensor], + total_preds_word_n_grams: dict[int, Tensor], + total_target_char_n_grams: dict[int, Tensor], + total_target_word_n_grams: dict[int, Tensor], + total_matching_char_n_grams: dict[int, Tensor], + total_matching_word_n_grams: dict[int, Tensor], + n_char_order: int, + n_word_order: int, + n_order: float, + beta: float, + lowercase: bool, + whitespace: bool, + sentence_chrf_score: Optional[List[Tensor]] = None, +) -> tuple[ + dict[int, Tensor], + dict[int, Tensor], + dict[int, Tensor], + dict[int, Tensor], + dict[int, Tensor], + dict[int, Tensor], + Optional[List[Tensor]], +]: + """Update function for chrf score. + + Args: + preds: An iterable of hypothesis corpus. + target: An iterable of iterables of reference corpus. + total_preds_char_n_grams: A dictionary containing a total number of hypothesis character n-grams. + total_preds_word_n_grams: A dictionary containing a total number of hypothesis word n-grams. + total_target_char_n_grams: A dictionary containing a total number of reference character n-grams. + total_target_word_n_grams: A dictionary containing a total number of reference word n-grams. + total_matching_char_n_grams: + A dictionary containing a total number of matching character n-grams between references and hypotheses. + total_matching_word_n_grams: + A dictionary containing a total number of total matching word n-grams between references and hypotheses. + n_char_order: A character n-gram order. + n_word_order: A word n-gram order. + n_order: Sum of character and word n-gram order. + beta: A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal. + lowercase: An indication whether to enable case-insensitivity. + whitespace: An indication whether to keep whitespaces during character n-gram extraction. + sentence_chrf_score: A list of sentence-level chrF/chrF++ scores. + + Return: + total_target_char_n_grams: number of reference character n-grams. + total_target_word_n_grams: number of reference word n-grams. + total_preds_char_n_grams: number of hypothesis character n-grams. + total_preds_word_n_grams: number of hypothesis word n-grams. + total_matching_char_n_grams: number of matching character n-grams between references and hypotheses. + total_matching_word_n_grams: number of total matching word n-grams between references and hypotheses. + sentence_chrf_score: A list of sentence-level chrF/chrF++ scores. + + Raises: + ValueError: + If length of ``preds`` and ``target`` differs. + + """ + target_corpus, preds = _validate_inputs(target, preds) + + for pred, targets in zip(preds, target_corpus): + ( + pred_char_n_grams_counts, + pred_word_n_grams_counts, + pred_char_n_grams, + pred_word_n_grams, + ) = _get_n_grams_counts_and_total_ngrams(pred, n_char_order, n_word_order, lowercase, whitespace) + total_preds_char_n_grams = _sum_over_dicts(total_preds_char_n_grams, pred_char_n_grams) + total_preds_word_n_grams = _sum_over_dicts(total_preds_word_n_grams, pred_word_n_grams) + + ( + sentence_level_f_score, + matching_char_n_grams, + matching_word_n_grams, + target_char_n_grams, + target_word_n_grams, + ) = _calculate_sentence_level_chrf_score( + targets, # type: ignore + pred_char_n_grams_counts, + pred_word_n_grams_counts, + pred_char_n_grams, + pred_word_n_grams, + n_char_order, + n_word_order, + n_order, + beta, + lowercase, + whitespace, + ) + + if sentence_chrf_score is not None: + sentence_chrf_score.append(sentence_level_f_score.unsqueeze(0)) + + total_target_char_n_grams = _sum_over_dicts(total_target_char_n_grams, target_char_n_grams) + total_target_word_n_grams = _sum_over_dicts(total_target_word_n_grams, target_word_n_grams) + total_matching_char_n_grams = _sum_over_dicts(total_matching_char_n_grams, matching_char_n_grams) + total_matching_word_n_grams = _sum_over_dicts(total_matching_word_n_grams, matching_word_n_grams) + + return ( + total_preds_char_n_grams, + total_preds_word_n_grams, + total_target_char_n_grams, + total_target_word_n_grams, + total_matching_char_n_grams, + total_matching_word_n_grams, + sentence_chrf_score, + ) + + +def _chrf_score_compute( + total_preds_char_n_grams: dict[int, Tensor], + total_preds_word_n_grams: dict[int, Tensor], + total_target_char_n_grams: dict[int, Tensor], + total_target_word_n_grams: dict[int, Tensor], + total_matching_char_n_grams: dict[int, Tensor], + total_matching_word_n_grams: dict[int, Tensor], + n_order: float, + beta: float, +) -> Tensor: + """Compute chrF/chrF++ score based on pre-computed target, prediction and matching character and word n-grams. + + Args: + total_preds_char_n_grams: number of hypothesis character n-grams. + total_preds_word_n_grams: number of hypothesis word n-grams. + total_target_char_n_grams: number of reference character n-grams. + total_target_word_n_grams: number of reference word n-grams. + total_matching_char_n_grams: number of matching character n-grams between references and hypotheses. + total_matching_word_n_grams: number of total matching word n-grams between references and hypotheses. + n_order: A sum of character and word n-gram order. + beta: + A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal. + + Return: + A corpus-level chrF/chrF++ score. + + """ + return _calculate_fscore( + total_matching_char_n_grams, + total_matching_word_n_grams, + total_preds_char_n_grams, + total_preds_word_n_grams, + total_target_char_n_grams, + total_target_word_n_grams, + n_order, + beta, + ) + + +def chrf_score( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + n_char_order: int = 6, + n_word_order: int = 2, + beta: float = 2.0, + lowercase: bool = False, + whitespace: bool = False, + return_sentence_level_score: bool = False, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Calculate `chrF score`_ of machine translated text with one or more references. + + This implementation supports both chrF score computation introduced in [1] and chrF++ score introduced in + `chrF++ score`_. This implementation follows the implementations from https://github.com/m-popovic/chrF and + https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py. + + Args: + preds: An iterable of hypothesis corpus. + target: An iterable of iterables of reference corpus. + n_char_order: + A character n-gram order. If `n_char_order=6`, the metrics refers to the official chrF/chrF++. + n_word_order: + A word n-gram order. If `n_word_order=2`, the metric refers to the official chrF++. If `n_word_order=0`, the + metric is equivalent to the original chrF. + beta: + A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal. + lowercase: An indication whether to enable case-insensitivity. + whitespace: An indication whether to keep whitespaces during character n-gram extraction. + return_sentence_level_score: An indication whether a sentence-level chrF/chrF++ score to be returned. + + Return: + A corpus-level chrF/chrF++ score. + (Optionally) A list of sentence-level chrF/chrF++ scores if `return_sentence_level_score=True`. + + Raises: + ValueError: + If ``n_char_order`` is not an integer greater than or equal to 1. + ValueError: + If ``n_word_order`` is not an integer greater than or equal to 0. + ValueError: + If ``beta`` is smaller than 0. + + Example: + >>> from torchmetrics.functional.text import chrf_score + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> chrf_score(preds, target) + tensor(0.8640) + + References: + [1] chrF: character n-gram F-score for automatic MT evaluation by Maja Popović `chrF score`_ + + [2] chrF++: words helping character n-grams by Maja Popović `chrF++ score`_ + + """ + if not isinstance(n_char_order, int) or n_char_order < 1: + raise ValueError("Expected argument `n_char_order` to be an integer greater than or equal to 1.") + if not isinstance(n_word_order, int) or n_word_order < 0: + raise ValueError("Expected argument `n_word_order` to be an integer greater than or equal to 0.") + if beta < 0: + raise ValueError("Expected argument `beta` to be greater than 0.") + + n_order = float(n_char_order + n_word_order) + + ( + total_preds_char_n_grams, + total_preds_word_n_grams, + total_target_char_n_grams, + total_target_word_n_grams, + total_matching_char_n_grams, + total_matching_word_n_grams, + ) = _prepare_n_grams_dicts(n_char_order, n_word_order) + + sentence_chrf_score: Optional[List[Tensor]] = [] if return_sentence_level_score else None + + ( + total_preds_char_n_grams, + total_preds_word_n_grams, + total_target_char_n_grams, + total_target_word_n_grams, + total_matching_char_n_grams, + total_matching_word_n_grams, + sentence_chrf_score, + ) = _chrf_score_update( + preds, + target, + total_preds_char_n_grams, + total_preds_word_n_grams, + total_target_char_n_grams, + total_target_word_n_grams, + total_matching_char_n_grams, + total_matching_word_n_grams, + n_char_order, + n_word_order, + n_order, + beta, + lowercase, + whitespace, + sentence_chrf_score, + ) + + chrf_f_score = _chrf_score_compute( + total_preds_char_n_grams, + total_preds_word_n_grams, + total_target_char_n_grams, + total_target_word_n_grams, + total_matching_char_n_grams, + total_matching_word_n_grams, + n_order, + beta, + ) + + if sentence_chrf_score: + return chrf_f_score, torch.cat(sentence_chrf_score) + return chrf_f_score diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/edit.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/edit.py new file mode 100644 index 0000000000000000000000000000000000000000..5660f45e02549facd7a5460b0d3cc56d13693965 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/edit.py @@ -0,0 +1,120 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Literal, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.text.helper import _LevenshteinEditDistance as _LE_distance + + +def _edit_distance_update( + preds: Union[str, Sequence[str]], + target: Union[str, Sequence[str]], + substitution_cost: int = 1, +) -> Tensor: + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + if not all(isinstance(x, str) for x in preds): + raise ValueError(f"Expected all values in argument `preds` to be string type, but got {preds}") + if not all(isinstance(x, str) for x in target): + raise ValueError(f"Expected all values in argument `target` to be string type, but got {target}") + if len(preds) != len(target): + raise ValueError( + f"Expected argument `preds` and `target` to have same length, but got {len(preds)} and {len(target)}" + ) + + distance = [ + _LE_distance(t, op_substitute=substitution_cost)(p)[0] # type: ignore[arg-type] + for p, t in zip(preds, target) + ] + return torch.tensor(distance, dtype=torch.int) + + +def _edit_distance_compute( + edit_scores: Tensor, + num_elements: Union[Tensor, int], + reduction: Optional[Literal["mean", "sum", "none"]] = "mean", +) -> Tensor: + """Compute final edit distance reduced over the batch.""" + if edit_scores.numel() == 0: + return torch.tensor(0, dtype=torch.int32) + if reduction == "mean": + return edit_scores.sum() / num_elements + if reduction == "sum": + return edit_scores.sum() + if reduction is None or reduction == "none": + return edit_scores + raise ValueError("Expected argument `reduction` to either be 'sum', 'mean', 'none' or None") + + +def edit_distance( + preds: Union[str, Sequence[str]], + target: Union[str, Sequence[str]], + substitution_cost: int = 1, + reduction: Optional[Literal["mean", "sum", "none"]] = "mean", +) -> Tensor: + """Calculates the Levenshtein edit distance between two sequences. + + The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform the + predicted text into the reference text. The lower the distance, the more accurate the model is considered to be. + + Implementation is similar to `nltk.edit_distance `_. + + Args: + preds: An iterable of predicted texts (strings). + target: An iterable of reference texts (strings). + substitution_cost: The cost of substituting one character for another. + reduction: a method to reduce metric score over samples. + + - ``'mean'``: takes the mean over samples + - ``'sum'``: takes the sum over samples + - ``None`` or ``'none'``: return the score per sample + + Raises: + ValueError: + If ``preds`` and ``target`` do not have the same length. + ValueError: + If ``preds`` or ``target`` contain non-string values. + + Example:: + Basic example with two strings. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits: + + >>> from torchmetrics.functional.text import edit_distance + >>> edit_distance(["rain"], ["shine"]) + tensor(3.) + + Example:: + Basic example with two strings and substitution cost of 2. Going from “rain” -> “sain” -> “shin” -> “shine” + takes 3 edits, where two of them are substitutions: + + >>> from torchmetrics.functional.text import edit_distance + >>> edit_distance(["rain"], ["shine"], substitution_cost=2) + tensor(5.) + + Example:: + Multiple strings example: + + >>> from torchmetrics.functional.text import edit_distance + >>> edit_distance(["rain", "lnaguaeg"], ["shine", "language"], reduction=None) + tensor([3, 4], dtype=torch.int32) + >>> edit_distance(["rain", "lnaguaeg"], ["shine", "language"], reduction="mean") + tensor(3.5000) + + """ + distance = _edit_distance_update(preds, target, substitution_cost) + return _edit_distance_compute(distance, num_elements=distance.numel(), reduction=reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/eed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/eed.py new file mode 100644 index 0000000000000000000000000000000000000000..20bc367d8f06023e49d6ec48d3625d0bb466408f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/eed.py @@ -0,0 +1,415 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# referenced from +# Library Name: torchtext +# Authors: torchtext authors +# Date: 2021-12-07 +# Link: + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# The RWTH Extended Edit Distance (EED) License + +# Copyright (c) 2019, RWTH. +# All rights reserved. + +# This license is derived from the Q Public License v1.0 and the Qt Non-Commercial License v1.0 which are both Copyright +# by Trolltech AS, Norway. The aim of this license is to lay down the conditions enabling you to use, modify and +# circulate the SOFTWARE, use of third-party application programs based on the Software and publication of results +# obtained through the use of modified and unmodified versions of the SOFTWARE. However, RWTH remain the authors of the +# SOFTWARE and so retain property rights and the use of all ancillary rights. The SOFTWARE is defined as all successive +# versions of EED software and their documentation that have been developed by RWTH. +# +# When you access and use the SOFTWARE, you are presumed to be aware of and to have accepted all the rights and +# obligations of the present license: +# +# 1. You are granted the non-exclusive rights set forth in this license provided you agree to and comply with any all +# conditions in this license. Whole or partial distribution of the Software, or software items that link with the +# Software, in any form signifies acceptance of this license for non-commercial use only. +# 2. You may copy and distribute the Software in unmodified form provided that the entire package, including - but not +# restricted to - copyright, trademark notices and disclaimers, as released by the initial developer of the +# Software, is distributed. +# 3. You may make modifications to the Software and distribute your modifications, in a form that is separate from the +# Software, such as patches. The following restrictions apply to modifications: +# a. Modifications must not alter or remove any copyright notices in the Software. +# b When modifications to the Software are released under this license, a non-exclusive royalty-free right is +# granted to the initial developer of the Software to distribute your modification in future versions of the +# Software provided such versions remain available under these terms in addition to any other license(s) of the +# initial developer. +# 4. You may distribute machine-executable forms of the Software or machine-executable forms of modified versions of +# the Software, provided that you meet these restrictions: +# a. You must include this license document in the distribution. +# b. You must ensure that all recipients of the machine-executable forms are also able to receive the complete +# machine-readable source code to the distributed Software, including all modifications, without any charge +# beyond the costs of data transfer, and place prominent notices in the distribution explaining this. +# c. You must ensure that all modifications included in the machine-executable forms are available under the terms +# of this license. +# 5. You may use the original or modified versions of the Software to compile, link and run application programs +# legally developed by you or by others. +# 6. You may develop application programs, reusable components and other software items, in a non-commercial setting, +# that link with the original or modified versions of the Software. These items, when distributed, are subject to +# the following requirements: +# a. You must ensure that all recipients of machine-executable forms of these items are also able to receive and use +# the complete machine-readable source code to the items without any charge beyond the costs of data transfer. +# b. You must explicitly license all recipients of your items to use and re-distribute original and modified +# versions of the items in both machine-executable and source code forms. The recipients must be able to do so +# without any charges whatsoever, and they must be able to re-distribute to anyone they choose. +# c. If an application program gives you access to functionality of the Software for development of application +# programs, reusable components or other software components (e.g. an application that is a scripting wrapper), +# usage of the application program is considered to be usage of the Software and is thus bound by this license. +# d. If the items are not available to the general public, and the initial developer of the Software requests a copy +# of the items, then you must supply one. +# 7. Users must cite the authors of the Software upon publication of results obtained through the use of original or +# modified versions of the Software by referring to the following publication: +# P. Stanchev, W. Wang, and H. Ney, “EED: Extended Edit Distance Measure for Machine Translation”, submitted to WMT +# 2019. +# 8. In no event shall the initial developers or copyright holders be liable for any damages whatsoever, including - +# but not restricted to - lost revenue or profits or other direct, indirect, special, incidental or consequential +# damages, even if they have been advised of the possibility of such damages, except to the extent invariable law, +# if any, provides otherwise. +# 9. You assume all risks concerning the quality or the effects of the SOFTWARE and its use. If the SOFTWARE is +# defective, you will bear the costs of all required services, corrections or repairs. +# 10. This license has the binding value of a contract. +# 11. The present license and its effects are subject to German law and the competent German Courts. +# +# The Software and this license document are provided "AS IS" with NO EXPLICIT OR IMPLICIT WARRANTY OF ANY KIND, +# INCLUDING WARRANTY OF DESIGN, ADAPTION, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + +import re +import unicodedata +from collections.abc import Sequence +from math import inf +from typing import List, Optional, Union + +from torch import Tensor, stack, tensor +from typing_extensions import Literal + +from torchmetrics.functional.text.helper import _validate_inputs + + +def _distance_between_words(preds_word: str, target_word: str) -> int: + """Distance measure used for substitutions/identity operation. + + Code adapted from https://github.com/rwth-i6/ExtendedEditDistance/blob/master/EED.py. + + Args: + preds_word: hypothesis word string + target_word: reference word string + + Return: + 0 for match, 1 for no match + + """ + return int(preds_word != target_word) + + +def _eed_function( + hyp: str, + ref: str, + alpha: float = 2.0, + rho: float = 0.3, + deletion: float = 0.2, + insertion: float = 1.0, +) -> float: + """Compute extended edit distance score for two lists of strings: hyp and ref. + + Code adapted from: https://github.com/rwth-i6/ExtendedEditDistance/blob/master/EED.py. + + Args: + hyp: A hypothesis string + ref: A reference string + alpha: optimal jump penalty, penalty for jumps between characters + rho: coverage cost, penalty for repetition of characters + deletion: penalty for deletion of character + insertion: penalty for insertion or substitution of character + + Return: + Extended edit distance score as float + """ + number_of_visits = [-1] * (len(hyp) + 1) + + # row[i] stores cost of cheapest path from (0,0) to (i,l) in CDER alignment grid. + row = [1.0] * (len(hyp) + 1) + + row[0] = 0.0 # CDER initialisation 0,0 = 0.0, rest 1.0 + next_row = [inf] * (len(hyp) + 1) + + for w in range(1, len(ref) + 1): + for i in range(len(hyp) + 1): + if i > 0: + next_row[i] = min( + next_row[i - 1] + deletion, + row[i - 1] + _distance_between_words(hyp[i - 1], ref[w - 1]), + row[i] + insertion, + ) + else: + next_row[i] = row[i] + 1.0 + + min_index = next_row.index(min(next_row)) + number_of_visits[min_index] += 1 + + # Long Jumps + if ref[w - 1] == " ": + jump = alpha + next_row[min_index] + next_row = [min(x, jump) for x in next_row] + + row = next_row + next_row = [inf] * (len(hyp) + 1) + + coverage = rho * sum(x if x >= 0 else 1 for x in number_of_visits) + + return min(1, (row[-1] + coverage) / (float(len(ref)) + coverage)) + + +def _preprocess_en(sentence: str) -> str: + """Preprocess english sentences. + + Copied from https://github.com/rwth-i6/ExtendedEditDistance/blob/master/util.py. + + Raises: + ValueError: If input sentence is not of a type `str`. + + """ + if not isinstance(sentence, str): + raise ValueError(f"Only strings allowed during preprocessing step, found {type(sentence)} instead") + + sentence = sentence.rstrip() # trailing space, tab, or newline + + # Add space before interpunctions + rules_interpunction = [ + (".", " ."), + ("!", " !"), + ("?", " ?"), + (",", " ,"), + ] + for pattern, replacement in rules_interpunction: + sentence = sentence.replace(pattern, replacement) + + rules_re = [ + (r"\s+", r" "), # get rid of extra spaces + (r"(\d) ([.,]) (\d)", r"\1\2\3"), # 0 . 1 -> 0.1 + (r"(Dr|Jr|Prof|Rev|Gen|Mr|Mt|Mrs|Ms) .", r"\1."), # Mr . -> Mr. + ] + for pattern, replacement in rules_re: + sentence = re.sub(pattern, replacement, sentence) + + # Add space between abbreviations + rules_interpunction = [ + ("e . g .", "e.g."), + ("i . e .", "i.e."), + ("U . S .", "U.S."), + ] + for pattern, replacement in rules_interpunction: + sentence = sentence.replace(pattern, replacement) + + # add space to beginning and end of string + return " " + sentence + " " + + +def _preprocess_ja(sentence: str) -> str: + """Preprocess japanese sentences. + + Copy from https://github.com/rwth-i6/ExtendedEditDistance/blob/master/util.py. + + Raises: + ValueError: If input sentence is not of a type `str`. + + """ + if not isinstance(sentence, str): + raise ValueError(f"Only strings allowed during preprocessing step, found {type(sentence)} instead") + + sentence = sentence.rstrip() # trailing space, tab, newline + # characters which look identical actually are identical + return unicodedata.normalize("NFKC", sentence) + + +def _eed_compute(sentence_level_scores: List[Tensor]) -> Tensor: + """Reduction for extended edit distance. + + Args: + sentence_level_scores: list of sentence-level scores as floats + + Return: + average of scores as a tensor + + """ + if len(sentence_level_scores) == 0: + return tensor(0.0) + + return sum(sentence_level_scores) / tensor(len(sentence_level_scores)) + + +def _preprocess_sentences( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + language: Literal["en", "ja"], +) -> tuple[Union[str, Sequence[str]], Sequence[Union[str, Sequence[str]]]]: + """Preprocess strings according to language requirements. + + Args: + preds: An iterable of hypothesis corpus. + target: An iterable of iterables of reference corpus. + language: Language used in sentences. Only supports English (en) and Japanese (ja) for now. Defaults to en + + Return: + Tuple of lists that contain the cleaned strings for target and preds + + Raises: + ValueError: If a different language than ``'en'`` or ``'ja'`` is used + ValueError: If length of target not equal to length of preds + ValueError: If objects in reference and hypothesis corpus are not strings + + """ + # sanity checks + target, preds = _validate_inputs(hypothesis_corpus=preds, ref_corpus=target) + + # preprocess string + if language == "en": + preprocess_function = _preprocess_en + elif language == "ja": + preprocess_function = _preprocess_ja + else: + raise ValueError(f"Expected argument `language` to either be `en` or `ja` but got {language}") + + preds = [preprocess_function(pred) for pred in preds] + target = [[preprocess_function(ref) for ref in reference] for reference in target] + + return preds, target + + +def _compute_sentence_statistics( + preds_word: str, + target_words: Union[str, Sequence[str]], + alpha: float = 2.0, + rho: float = 0.3, + deletion: float = 0.2, + insertion: float = 1.0, +) -> Tensor: + """Compute scores for ExtendedEditDistance. + + Args: + target_words: An iterable of reference words + preds_word: A hypothesis word + alpha: An optimal jump penalty, penalty for jumps between characters + rho: coverage cost, penalty for repetition of characters + deletion: penalty for deletion of character + insertion: penalty for insertion or substitution of character + + Return: + best_score: best (lowest) sentence-level score as a Tensor + + """ + best_score = inf + + for reference in target_words: + score = _eed_function(preds_word, reference, alpha, rho, deletion, insertion) + if score < best_score: + best_score = score + + return tensor(best_score) + + +def _eed_update( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + language: Literal["en", "ja"] = "en", + alpha: float = 2.0, + rho: float = 0.3, + deletion: float = 0.2, + insertion: float = 1.0, + sentence_eed: Optional[List[Tensor]] = None, +) -> List[Tensor]: + """Compute scores for ExtendedEditDistance. + + Args: + preds: An iterable of hypothesis corpus + target: An iterable of iterables of reference corpus + language: Language used in sentences. Only supports English (en) and Japanese (ja) for now. Defaults to en + alpha: optimal jump penalty, penalty for jumps between characters + rho: coverage cost, penalty for repetition of characters + deletion: penalty for deletion of character + insertion: penalty for insertion or substitution of character + sentence_eed: list of sentence-level scores + + Return: + individual sentence scores as a list of Tensors + + """ + preds, target = _preprocess_sentences(preds, target, language) + + if sentence_eed is None: + sentence_eed = [] + + # return tensor(0.0) if target or preds is empty + if 0 in (len(preds), len(target[0])): + return sentence_eed + + for hypothesis, target_words in zip(preds, target): + score = _compute_sentence_statistics(hypothesis, target_words, alpha, rho, deletion, insertion) + sentence_eed.append(score) + + return sentence_eed + + +def extended_edit_distance( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + language: Literal["en", "ja"] = "en", + return_sentence_level_score: bool = False, + alpha: float = 2.0, + rho: float = 0.3, + deletion: float = 0.2, + insertion: float = 1.0, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Compute extended edit distance score (`ExtendedEditDistance`_) [1] for strings or list of strings. + + The metric utilises the Levenshtein distance and extends it by adding a jump operation. + + Args: + preds: An iterable of hypothesis corpus. + target: An iterable of iterables of reference corpus. + language: Language used in sentences. Only supports English (en) and Japanese (ja) for now. Defaults to en + return_sentence_level_score: An indication of whether sentence-level EED score is to be returned. + alpha: optimal jump penalty, penalty for jumps between characters + rho: coverage cost, penalty for repetition of characters + deletion: penalty for deletion of character + insertion: penalty for insertion or substitution of character + + Return: + Extended edit distance score as a tensor + + Example: + >>> from torchmetrics.functional.text import extended_edit_distance + >>> preds = ["this is the prediction", "here is an other sample"] + >>> target = ["this is the reference", "here is another one"] + >>> extended_edit_distance(preds=preds, target=target) + tensor(0.3078) + + References: + [1] P. Stanchev, W. Wang, and H. Ney, “EED: Extended Edit Distance Measure for Machine Translation”, + submitted to WMT 2019. `ExtendedEditDistance`_ + + """ + # input validation for parameters + for param_name, param in zip(["alpha", "rho", "deletion", "insertion"], [alpha, rho, deletion, insertion]): + if not isinstance(param, float) or (isinstance(param, float) and param < 0): + raise ValueError(f"Parameter `{param_name}` is expected to be a non-negative float.") + + sentence_level_scores = _eed_update(preds, target, language, alpha, rho, deletion, insertion) + + average = _eed_compute(sentence_level_scores) + + if return_sentence_level_score: + return average, stack(sentence_level_scores) + return average diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/helper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..a61f06232abeccf45d76aa4d89bf77edcbea8d15 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/helper.py @@ -0,0 +1,427 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# Copyright 2020 Memsource +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from collections.abc import Sequence +from enum import Enum, unique +from typing import Union + +# Tercom-inspired limits +_BEAM_WIDTH = 25 + +# Sacrebleu-inspired limits +_MAX_CACHE_SIZE = 10000 +_INT_INFINITY = int(1e16) + + +@unique +class _EditOperations(str, Enum): + """Enumerations for the Levenhstein edit operations.""" + + OP_INSERT = "insert" + OP_DELETE = "delete" + OP_SUBSTITUTE = "substitute" + OP_NOTHING = "nothing" + OP_UNDEFINED = "undefined" + + +class _LevenshteinEditDistance: + """A convenience class for calculating the Levenshtein edit distance. + + Class will cache some intermediate values to hasten the calculation. The implementation follows the implementation + from https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/lib_ter.py, + where the most of this implementation is adapted and copied from. + + Args: + reference_tokens: list of reference tokens + op_insert: cost of insertion operation + op_delete: cost of deletion operation + op_substitute: cost of substitution operation + + """ + + def __init__( + self, reference_tokens: list[str], op_insert: int = 1, op_delete: int = 1, op_substitute: int = 1 + ) -> None: + self.reference_tokens = reference_tokens + self.reference_len = len(reference_tokens) + + self.cache: dict[str, tuple[int, str]] = {} + self.cache_size = 0 + + self.op_insert = op_insert + self.op_delete = op_delete + self.op_substitute = op_substitute + self.op_nothing = 0 + self.op_undefined = _INT_INFINITY + + def __call__(self, prediction_tokens: list[str]) -> tuple[int, tuple[_EditOperations, ...]]: + """Calculate edit distance between self._words_ref and the hypothesis. Uses cache to skip some computations. + + Args: + prediction_tokens: A tokenized predicted sentence. + + Return: + A tuple of a calculated edit distance and a trace of executed operations. + + """ + # Use cached edit distance for already computed words + start_position, cached_edit_distance = self._find_cache(prediction_tokens) + # Calculate the rest of the edit distance matrix + edit_distance_int, edit_distance, trace = self._levenshtein_edit_distance( + prediction_tokens, start_position, cached_edit_distance + ) + # Update our cache with the newly calculated rows + self._add_cache(prediction_tokens, edit_distance) + + return edit_distance_int, trace + + def _levenshtein_edit_distance( + self, + prediction_tokens: list[str], + prediction_start: int, + cache: list[list[tuple[int, _EditOperations]]], + ) -> tuple[int, list[list[tuple[int, _EditOperations]]], tuple[_EditOperations, ...]]: + """Dynamic programming algorithm to compute the Levenhstein edit distance. + + Args: + prediction_tokens: A tokenized predicted sentence. + prediction_start: An index where a predicted sentence to be considered from. + cache: A cached Levenshtein edit distance. + + Returns: + Edit distance between the predicted sentence and the reference sentence + + """ + prediction_len = len(prediction_tokens) + + empty_rows: list[list[tuple[int, _EditOperations]]] = [ + list(self._get_empty_row(self.reference_len)) for _ in range(prediction_len - prediction_start) + ] + edit_distance: list[list[tuple[int, _EditOperations]]] = cache + empty_rows + length_ratio = self.reference_len / prediction_len if prediction_tokens else 1.0 + + # Ensure to not end up with zero overlaip with previous role + beam_width = math.ceil(length_ratio / 2 + _BEAM_WIDTH) if length_ratio / 2 > _BEAM_WIDTH else _BEAM_WIDTH + + # Calculate the Levenshtein distance + for i in range(prediction_start + 1, prediction_len + 1): + pseudo_diag = math.floor(i * length_ratio) + min_j = max(0, pseudo_diag - beam_width) + max_j = ( + self.reference_len + 1 if i == prediction_len else min(self.reference_len + 1, pseudo_diag + beam_width) + ) + + for j in range(min_j, max_j): + if j == 0: + edit_distance[i][j] = ( + edit_distance[i - 1][j][0] + self.op_delete, + _EditOperations.OP_DELETE, + ) + else: + if prediction_tokens[i - 1] == self.reference_tokens[j - 1]: + cost_substitute = self.op_nothing + operation_substitute = _EditOperations.OP_NOTHING + else: + cost_substitute = self.op_substitute + operation_substitute = _EditOperations.OP_SUBSTITUTE + + # Tercom prefers no-op/sub, then insertion, then deletion. But since we flip the trace and compute + # the alignment from the inverse, we need to swap order of insertion and deletion in the + # preference. + # Copied from: https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/ter.py. + operations = ( + (edit_distance[i - 1][j - 1][0] + cost_substitute, operation_substitute), + (edit_distance[i - 1][j][0] + self.op_delete, _EditOperations.OP_DELETE), + (edit_distance[i][j - 1][0] + self.op_insert, _EditOperations.OP_INSERT), + ) + + for operation_cost, operation_name in operations: + if edit_distance[i][j][0] > operation_cost: + edit_distance[i][j] = operation_cost, operation_name + + trace = self._get_trace(prediction_len, edit_distance) + + return edit_distance[-1][-1][0], edit_distance[len(cache) :], trace + + def _get_trace( + self, prediction_len: int, edit_distance: list[list[tuple[int, _EditOperations]]] + ) -> tuple[_EditOperations, ...]: + """Get a trace of executed operations from the edit distance matrix. + + Args: + prediction_len: A length of a tokenized predicted sentence. + edit_distance: + A matrix of the Levenshtedin edit distance. The element part of the matrix is a tuple of an edit + operation cost and an edit operation itself. + + Return: + A trace of executed operations returned as a tuple of `_EDIT_OPERATIONS` enumerates. + + Raises: + ValueError: + If an unknown operation has been applied. + + """ + trace: tuple[_EditOperations, ...] = () + i = prediction_len + j = self.reference_len + + while i > 0 or j > 0: + operation = edit_distance[i][j][1] + trace = (operation, *trace) + if operation in (_EditOperations.OP_SUBSTITUTE, _EditOperations.OP_NOTHING): + i -= 1 + j -= 1 + elif operation == _EditOperations.OP_INSERT: + j -= 1 + elif operation == _EditOperations.OP_DELETE: + i -= 1 + else: + raise ValueError(f"Unknown operation {operation!r}") + + return trace + + def _add_cache(self, prediction_tokens: list[str], edit_distance: list[list[tuple[int, _EditOperations]]]) -> None: + """Add newly computed rows to cache. + + Since edit distance is only calculated on the hypothesis suffix that was not in cache, the number of rows in + `edit_distance` matrx may be shorter than hypothesis length. In that case we skip over these initial words. + + Args: + prediction_tokens: A tokenized predicted sentence. + edit_distance: + A matrix of the Levenshtedin edit distance. The element part of the matrix is a tuple of an edit + operation cost and an edit operation itself. + + """ + if self.cache_size >= _MAX_CACHE_SIZE: + return + + node = self.cache + + # how many initial words to skip + skip_num = len(prediction_tokens) - len(edit_distance) + + # Jump through the cache to the current position + for i in range(skip_num): + node = node[prediction_tokens[i]][0] # type: ignore + + # Update cache with newly computed rows + for word, row in zip(prediction_tokens[skip_num:], edit_distance): + if word not in node: + node[word] = ({}, tuple(row)) # type: ignore + self.cache_size += 1 + value = node[word] + node = value[0] # type: ignore + + def _find_cache(self, prediction_tokens: list[str]) -> tuple[int, list[list[tuple[int, _EditOperations]]]]: + """Find the already calculated rows of the Levenshtein edit distance metric. + + Args: + prediction_tokens: A tokenized predicted sentence. + + Return: + A tuple of a start hypothesis position and `edit_distance` matrix. + + prediction_start: An index where a predicted sentence to be considered from. + edit_distance: + A matrix of the cached Levenshtedin edit distance. The element part of the matrix is a tuple of an edit + operation cost and an edit operation itself. + + """ + node = self.cache + start_position = 0 + edit_distance: list[list[tuple[int, _EditOperations]]] = [self._get_initial_row(self.reference_len)] + for word in prediction_tokens: + if word in node: + start_position += 1 + node, row = node[word] # type: ignore + edit_distance.append(row) # type: ignore + else: + break + + return start_position, edit_distance + + def _get_empty_row(self, length: int) -> list[tuple[int, _EditOperations]]: + """Precomputed empty matrix row for Levenhstein edit distance. + + Args: + length: A length of a tokenized sentence. + + Return: + A list of tuples containing infinite edit operation costs and yet undefined edit operations. + + """ + return [(int(self.op_undefined), _EditOperations.OP_UNDEFINED)] * (length + 1) + + def _get_initial_row(self, length: int) -> list[tuple[int, _EditOperations]]: + """First row corresponds to insertion operations of the reference, so 1 edit operation per reference word. + + Args: + length: A length of a tokenized sentence. + + Return: + A list of tuples containing edit operation costs of insert and insert edit operations. + + """ + return [(i * self.op_insert, _EditOperations.OP_INSERT) for i in range(length + 1)] + + +def _validate_inputs( + ref_corpus: Union[Sequence[str], Sequence[Sequence[str]]], + hypothesis_corpus: Union[str, Sequence[str]], +) -> tuple[Sequence[Sequence[str]], Sequence[str]]: + """Check and update (if needed) the format of reference and hypothesis corpora for various text evaluation metrics. + + Args: + ref_corpus: An iterable of iterables of reference corpus. + hypothesis_corpus: An iterable of hypothesis corpus. + + Return: + ref_corpus: An iterable of iterables of reference corpus. + hypothesis_corpus: An iterable of hypothesis corpus. + + Raises: + ValueError: + If length of `ref_corpus` and `hypothesis_corpus` differs. + + """ + if isinstance(hypothesis_corpus, str): + hypothesis_corpus = [hypothesis_corpus] + + # Ensure reference corpus is properly of a type Sequence[Sequence[str]] + if all(isinstance(ref, str) for ref in ref_corpus): + ref_corpus = [ref_corpus] if len(hypothesis_corpus) == 1 else [[ref] for ref in ref_corpus] # type: ignore + + if hypothesis_corpus and all(ref for ref in ref_corpus) and len(ref_corpus) != len(hypothesis_corpus): + raise ValueError(f"Corpus has different size {len(ref_corpus)} != {len(hypothesis_corpus)}") + + return ref_corpus, hypothesis_corpus + + +def _edit_distance(prediction_tokens: list[str], reference_tokens: list[str]) -> int: + """Dynamic programming algorithm to compute the edit distance. + + Args: + prediction_tokens: A tokenized predicted sentence + reference_tokens: A tokenized reference sentence + Returns: + Edit distance between the predicted sentence and the reference sentence + + """ + dp = [[0] * (len(reference_tokens) + 1) for _ in range(len(prediction_tokens) + 1)] + for i in range(len(prediction_tokens) + 1): + dp[i][0] = i + for j in range(len(reference_tokens) + 1): + dp[0][j] = j + for i in range(1, len(prediction_tokens) + 1): + for j in range(1, len(reference_tokens) + 1): + if prediction_tokens[i - 1] == reference_tokens[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + else: + dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1 + return dp[-1][-1] + + +def _flip_trace(trace: tuple[_EditOperations, ...]) -> tuple[_EditOperations, ...]: + """Flip the trace of edit operations. + + Instead of rewriting a->b, get a recipe for rewriting b->a. Simply flips insertions and deletions. + + Args: + trace: A tuple of edit operations. + + Return: + inverted_trace: + A tuple of inverted edit operations. + + """ + _flip_operations: dict[_EditOperations, _EditOperations] = { + _EditOperations.OP_INSERT: _EditOperations.OP_DELETE, + _EditOperations.OP_DELETE: _EditOperations.OP_INSERT, + } + + def _replace_operation_or_retain( + operation: _EditOperations, _flip_operations: dict[_EditOperations, _EditOperations] + ) -> _EditOperations: + if operation in _flip_operations: + return _flip_operations.get(operation) # type: ignore + return operation + + return tuple(_replace_operation_or_retain(operation, _flip_operations) for operation in trace) + + +def _trace_to_alignment(trace: tuple[_EditOperations, ...]) -> tuple[dict[int, int], list[int], list[int]]: + """Transform trace of edit operations into an alignment of the sequences. + + Args: + trace: A trace of edit operations as a tuple of `_EDIT_OPERATIONS` enumerates. + + Return: + alignments: A dictionary mapping aligned positions between a reference and a hypothesis. + reference_errors: A list of error positions in a reference. + hypothesis_errors: A list of error positions in a hypothesis. + + Raises: + ValueError: + If an unknown operation is + + """ + reference_position = hypothesis_position = -1 + reference_errors: list[int] = [] + hypothesis_errors: list[int] = [] + alignments: dict[int, int] = {} + + # we are rewriting a into b + for operation in trace: + if operation == _EditOperations.OP_NOTHING: + hypothesis_position += 1 + reference_position += 1 + alignments[reference_position] = hypothesis_position + reference_errors.append(0) + hypothesis_errors.append(0) + elif operation == _EditOperations.OP_SUBSTITUTE: + hypothesis_position += 1 + reference_position += 1 + alignments[reference_position] = hypothesis_position + reference_errors.append(1) + hypothesis_errors.append(1) + elif operation == _EditOperations.OP_INSERT: + hypothesis_position += 1 + hypothesis_errors.append(1) + elif operation == _EditOperations.OP_DELETE: + reference_position += 1 + alignments[reference_position] = hypothesis_position + reference_errors.append(1) + else: + raise ValueError(f"Unknown operation {operation!r}.") + + return alignments, reference_errors, hypothesis_errors diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/helper_embedding_metric.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/helper_embedding_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..19c77f767dfff4c4a27a8badc2f59afb224b77ca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/helper_embedding_metric.py @@ -0,0 +1,302 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math +import os +from collections import Counter, defaultdict +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +import torch +from torch import Tensor +from torch.utils.data import DataLoader, Dataset + +from torchmetrics.utilities.data import _cumsum +from torchmetrics.utilities.imports import _TQDM_AVAILABLE, _TRANSFORMERS_GREATER_EQUAL_4_4 + +if TYPE_CHECKING: + if _TQDM_AVAILABLE: + import tqdm + if _TRANSFORMERS_GREATER_EQUAL_4_4: + from transformers import PreTrainedModel, PreTrainedTokenizerBase + + +def _process_attention_mask_for_special_tokens(attention_mask: Tensor) -> Tensor: + """Process attention mask to be zero for special [CLS] and [SEP] tokens as they're not included in BERT score. + + Args: + attention_mask: An attention mask to be returned, for example, by a `transformers` tokenizer. + + Return: + A processed attention mask. + + """ + # Make attention_mask zero for [CLS] token + attention_mask[:, 0] = 0 + # Make attention_mask zero for [SEP] token + sep_token_position = _cumsum((attention_mask - 0.1), dim=-1).argmax(-1) + attention_mask[torch.arange(attention_mask.size(0)).long(), sep_token_position] = 0 + return attention_mask + + +def _input_data_collator( + batch: dict[str, Tensor], device: Optional[Union[str, torch.device]] = None +) -> dict[str, Tensor]: + """Trim model inputs. + + This function trims the model inputs to the longest sequence within the batch and put the input on the proper + device. + + """ + max_len = int(batch["attention_mask"].sum(1).max().item()) + input_ids = batch["input_ids"][:, :max_len].to(device) + attention_mask = batch["attention_mask"][:, :max_len].to(device) + batch.update({"input_ids": input_ids, "attention_mask": attention_mask}) + return batch + + +def _output_data_collator(model_output: Tensor, attention_mask: Tensor, target_len: int) -> tuple[Tensor, Tensor]: + """Pad the model output and attention mask to the target length.""" + zeros_shape = list(model_output.shape) + zeros_shape[2] = target_len - zeros_shape[2] + model_output = torch.cat( + [model_output, torch.zeros(zeros_shape, dtype=model_output.dtype).to(model_output.device)], dim=2 + ) + zeros = torch.zeros(zeros_shape[0], zeros_shape[2], dtype=attention_mask.dtype).to(attention_mask.device) + attention_mask = torch.cat([attention_mask, zeros], dim=1) + return model_output, attention_mask + + +def _sort_data_according_length(input_ids: Tensor, attention_mask: Tensor) -> tuple[Tensor, Tensor, Tensor]: + """Sort tokenized sentence from the shortest to the longest one.""" + sorted_indices = attention_mask.sum(1).argsort() + input_ids = input_ids[sorted_indices] + attention_mask = attention_mask[sorted_indices] + return input_ids, attention_mask, sorted_indices + + +def _preprocess_text( + text: list[str], + tokenizer: Any, + max_length: int = 512, + truncation: bool = True, + sort_according_length: bool = True, + own_tokenizer: bool = False, +) -> tuple[dict[str, Tensor], Optional[Tensor]]: + """Text pre-processing function using `transformers` `AutoTokenizer` instance. + + Args: + text: + An iterable of sentences. + tokenizer: + Either `AutoTokenizer` instance from `transformers` package, or a user's own tokenizer. + max_length: + A maximum sequence length. + truncation: + An indication of whether tokenized sequences should be padded only to the length of the longest sequence. + sort_according_length: + An indication of whether tokenized sequences should be sorted from shortest to longest. This is appropriate + to do for leveraging dynamic padding during embedding calculation and thereby to hasten inference. + own_tokenizer: + An indication of whether a non-default user's own tokenizer is used. + + Return: + A dictionary of tokenized sentences including input_ids and attention_mask. + + Raises: + BaseException: + If a tokenization with a user's own tokenizer is not successful. + + """ + if not own_tokenizer: + tokenized_data = tokenizer( + text, padding="max_length", max_length=max_length, truncation=truncation, return_tensors="pt" + ) + else: + try: + tokenized_data = tokenizer(text, max_length) + except BaseException as ex: + raise RuntimeError(f"Tokenization was not successful: {ex}") from ex + + if sort_according_length: + input_ids, attention_mask, sorting_indices = _sort_data_according_length( + tokenized_data["input_ids"], tokenized_data["attention_mask"] + ) + input_dict = {"input_ids": input_ids, "attention_mask": attention_mask} + else: + input_dict = {"input_ids": tokenized_data["input_ids"], "attention_mask": tokenized_data["attention_mask"]} + sorting_indices = None + + return input_dict, sorting_indices + + +def _get_progress_bar(dataloader: DataLoader, verbose: bool = False) -> Union[DataLoader, "tqdm.auto.tqdm"]: + """Wrap dataloader in progressbar if asked for. + + Function will return either the dataloader itself when `verbose = False`, or it wraps the dataloader with + `tqdm.auto.tqdm`, when `verbose = True` to display a progress bar during the embeddings calculation. + + """ + import tqdm + + return tqdm.auto.tqdm(dataloader) if verbose else dataloader + + +def _check_shape_of_model_output(output: Tensor, input_ids: Tensor) -> None: + """Check if the shape of the user's own model output.""" + bs, seq_len = input_ids.shape[:2] + invalid_out_shape = len(output.shape) != 3 or output.shape[0] != bs or output.shape[1] != seq_len + if invalid_out_shape: + raise ValueError( + "The model output must be `Tensor` of a shape `[batch_size, seq_len, model_dim]` " + f"i.e. [{bs}, {seq_len}. , `model_dim`], but got {output.shape}." + ) + + +def _load_tokenizer_and_model( + model_name_or_path: Union[str, os.PathLike], device: Optional[Union[str, torch.device]] = None +) -> tuple["PreTrainedTokenizerBase", "PreTrainedModel"]: + """Load HuggingFace `transformers`' tokenizer and model. This function also handle a device placement. + + Args: + model_name_or_path: + A name or a model path used to load `transformers` pretrained model. + device: + A device to be used for calculation. + + Return: + Initialized `transformers`' tokenizer and model. + + """ + from transformers import AutoModelForMaskedLM, AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) + model = AutoModelForMaskedLM.from_pretrained(model_name_or_path) + model.eval() + model.to(device) + return tokenizer, model + + +class TextDataset(Dataset): + """PyTorch dataset class for storing tokenized sentences and other properties used for BERT score calculation.""" + + def __init__( + self, + text: list[str], + tokenizer: Any, + max_length: int = 512, + preprocess_text_fn: Callable[ + [list[str], Any, int, bool], Union[dict[str, Tensor], tuple[dict[str, Tensor], Optional[Tensor]]] + ] = _preprocess_text, + idf: bool = False, + tokens_idf: Optional[dict[int, float]] = None, + truncation: bool = False, + ) -> None: + """Initialize text dataset class. + + Args: + text: An iterable of sentences. + tokenizer: `AutoTokenizer` instance from `transformers` package. + max_length: A maximum sequence length. + preprocess_text_fn: A function used for processing the input sentences. + idf: An indication of whether calculate token inverse document frequencies to weight the model embeddings. + tokens_idf: Inverse document frequencies (these should be calculated on reference sentences). + truncation: An indication of whether tokenized sequences should be padded only to the length of the longest + + """ + _text = preprocess_text_fn(text, tokenizer, max_length, truncation) + if isinstance(_text, tuple): + self.text, self.sorting_indices = _text + else: + self.text = _text + self.max_length = self.text["input_ids"].shape[1] + self.num_sentences = len(text) + self.idf = idf + self.tokens_idf = {} + if idf: + self.tokens_idf = tokens_idf if tokens_idf is not None else self._get_tokens_idf() + + def __getitem__(self, idx: int) -> dict[str, Tensor]: + """Get the input ids and attention mask belonging to a specific datapoint.""" + input_ids = self.text["input_ids"][idx, :] + attention_mask = self.text["attention_mask"][idx, :] + inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask} + if self.idf: + input_ids_idf = torch.tensor([self.tokens_idf[input_idx] for input_idx in input_ids.tolist()]) + inputs_dict["input_ids_idf"] = input_ids_idf + return inputs_dict + + def __len__(self) -> int: + """Return the number of sentences in the dataset.""" + return self.num_sentences + + def _get_tokens_idf(self) -> dict[int, float]: + """Calculate token inverse document frequencies. + + Return: + A python dictionary containing inverse document frequencies for token ids. + + """ + token_counter: Counter = Counter() + for tokens in map(self._set_of_tokens, self.text["input_ids"]): + token_counter.update(tokens) + + tokens_idf: dict[int, float] = defaultdict(self._get_tokens_idf_default_value) + tokens_idf.update({ + idx: math.log((self.num_sentences + 1) / (occurrence + 1)) for idx, occurrence in token_counter.items() + }) + return tokens_idf + + def _get_tokens_idf_default_value(self) -> float: + """Ensure `defaultdict` can be pickled.""" + return math.log((self.num_sentences + 1) / 1) + + @staticmethod + def _set_of_tokens(input_ids: Tensor) -> set: + """Return set of tokens from the `input_ids` :class:`~torch.Tensor`.""" + return set(input_ids.tolist()) + + +class TokenizedDataset(TextDataset): + """The child class of `TextDataset` class used with already tokenized data.""" + + def __init__( + self, + input_ids: Tensor, + attention_mask: Tensor, + idf: bool = False, + tokens_idf: Optional[dict[int, float]] = None, + ) -> None: + """Initialize the dataset class. + + Args: + input_ids: Input indexes + attention_mask: Attention mask + idf: + An indication of whether calculate token inverse document frequencies to weight the model embeddings. + tokens_idf: Inverse document frequencies (these should be calculated on reference sentences). + + """ + text = dict( + zip( + ["input_ids", "attention_mask", "sorting_indices"], + _sort_data_according_length(input_ids, attention_mask), + ) + ) + self.sorting_indices = text.pop("sorting_indices") + self.text = _input_data_collator(text) + self.num_sentences = len(self.text["input_ids"]) + self.max_length = self.text["input_ids"].shape[1] + self.idf = idf + self.tokens_idf = {} + if idf: + self.tokens_idf = tokens_idf if tokens_idf is not None else self._get_tokens_idf() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/infolm.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/infolm.py new file mode 100644 index 0000000000000000000000000000000000000000..94452f4886e48c5eb36da48beb97b2442ccdc5f3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/infolm.py @@ -0,0 +1,658 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +from collections.abc import Sequence +from enum import unique +from typing import TYPE_CHECKING, List, Optional, Union + +import torch +from torch import Tensor +from torch.nn import functional as F # noqa: N812 +from torch.utils.data import DataLoader +from typing_extensions import Literal + +from torchmetrics.functional.text.helper_embedding_metric import ( + TokenizedDataset, + _get_progress_bar, + _input_data_collator, + _load_tokenizer_and_model, +) +from torchmetrics.utilities.enums import EnumStr +from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_4 + +if TYPE_CHECKING and _TRANSFORMERS_GREATER_EQUAL_4_4: + from transformers import PreTrainedModel, PreTrainedTokenizerBase + +if not _TRANSFORMERS_GREATER_EQUAL_4_4: + __doctest_skip__ = ["infolm"] + + +_ALLOWED_INFORMATION_MEASURE_LITERAL = Literal[ + "kl_divergence", + "alpha_divergence", + "beta_divergence", + "ab_divergence", + "renyi_divergence", + "l1_distance", + "l2_distance", + "l_infinity_distance", + "fisher_rao_distance", +] + + +@unique +class _IMEnum(EnumStr): + """A helper Enum class for storing the information measure.""" + + @staticmethod + def _name() -> str: + return "Information measure" + + KL_DIVERGENCE = "kl_divergence" + ALPHA_DIVERGENCE = "alpha_divergence" + BETA_DIVERGENCE = "beta_divergence" + AB_DIVERGENCE = "ab_divergence" + RENYI_DIVERGENCE = "renyi_divergence" + L1_DISTANCE = "l1_distance" + L2_DISTANCE = "l2_distance" + L_INFINITY_DISTANCE = "l_infinity_distance" + FISHER_RAO_DISTANCE = "fisher_rao_distance" + + +class _InformationMeasure: + """A wrapper class used for the calculation of different information measures. + + This metric can be used to measure the information between the discrete reference distributions of predicted and + reference sentences. The class also handles input validation for `alpha` and `beta` parameters. + + Args: + information_measure: + A name of information measure to be used. Please use one of: ['kl_divergence', 'alpha_divergence', + 'beta_divergence', 'ab_divergence', 'renyi_divergence', 'l1_distance', 'l2_distance', 'l_infinity_distance', + 'fisher_rao_distance'] + alpha: + Alpha parameter of the divergence used for alpha, AB and Rényi divergence measures. + beta: + Beta parameter of the divergence used for beta and AB divergence measures. + + Raises: + ValueError: + If information measure is one from alpha, AB or Rényi divergence and parameter `alpha` is `None`. + ValueError: + If information measure is one from beta or divergence and parameter `beta` is `None`. + ValueError: + If information measure is alpha divergence and parameter `alpha` equals 0 or 1. + ValueError: + If information measure is beta divergence and parameter `beta` equals 0 or -1. + ValueError: + If information measure is AB divergence and parameter `alpha`, `beta` or `alpha + beta` equal 0. + ValueError: + If information measure is Rényi divergence and parameter `alpha` equals 1. + + """ + + def __init__( + self, + information_measure: _ALLOWED_INFORMATION_MEASURE_LITERAL, + alpha: Optional[float] = None, + beta: Optional[float] = None, + ) -> None: + self.information_measure = _IMEnum.from_str(information_measure) + _bad_measures = (_IMEnum.ALPHA_DIVERGENCE, _IMEnum.AB_DIVERGENCE, _IMEnum.RENYI_DIVERGENCE) + if self.information_measure in _bad_measures and not isinstance(alpha, float): + raise ValueError(f"Parameter `alpha` is expected to be defined for {information_measure}.") + if self.information_measure in [_IMEnum.BETA_DIVERGENCE, _IMEnum.AB_DIVERGENCE] and not isinstance(beta, float): + raise ValueError(f"Parameter `beta` is expected to be defined for {information_measure}.") + if self.information_measure == _IMEnum.ALPHA_DIVERGENCE and (not isinstance(alpha, float) or alpha in [0, 1]): + raise ValueError( + f"Parameter `alpha` is expected to be float differened from 0 and 1 for {information_measure}." + ) + if self.information_measure == _IMEnum.BETA_DIVERGENCE and (not isinstance(beta, float) or beta in [0, -1]): + raise ValueError( + f"Parameter `beta` is expected to be float differened from 0 and -1 for {information_measure}." + ) + if self.information_measure == _IMEnum.AB_DIVERGENCE and ( + alpha is None + or beta is None + or (any(not isinstance(p, float) for p in [alpha, beta]) or 0 in [alpha, beta, alpha + beta]) + ): + raise ValueError( + "Parameters `alpha`, `beta` and their sum are expected to be differened from 0 for " + f"{information_measure}." + ) + if self.information_measure == _IMEnum.RENYI_DIVERGENCE and (not isinstance(alpha, float) or alpha == 1): + raise ValueError(f"Parameter `alpha` is expected to be float differened from 1 for {information_measure}.") + + # We ensure self.alpha and self.beta to be different from None to ensure mypy compliance + self.alpha = alpha or 0 + self.beta = beta or 0 + + def __call__(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + information_measure_function = getattr(self, f"_calculate_{self.information_measure.value}") + return torch.nan_to_num(information_measure_function(preds_distribution, target_distribution)) + + @staticmethod + def _calculate_kl_divergence(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate Kullback-Leibler divergence between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + Kullback-Leibler divergence between discrete distributions of predicted and reference sentences. + + """ + return torch.sum(target_distribution * torch.log(preds_distribution / target_distribution), dim=-1) + + def _calculate_alpha_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate alpha divergence between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + Alpha divergence between discrete distributions of predicted and reference sentences. + + """ + _alpha_denom = self.alpha * (self.alpha - 1) + return ( + 1 - torch.sum(target_distribution**self.alpha * preds_distribution ** (1 - self.alpha), dim=-1) + ) / _alpha_denom + + def _calculate_ab_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate AB divergence between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + AB divergence between discrete distributions of predicted and reference sentences. + + """ + a = torch.log(torch.sum(target_distribution ** (self.beta + self.alpha), dim=-1)) + a /= self.beta * (self.beta + self.alpha) + b = torch.log(torch.sum(preds_distribution ** (self.beta + self.alpha), dim=-1)) + b /= self.alpha * (self.beta + self.alpha) + c = torch.log(torch.sum(target_distribution**self.alpha * preds_distribution**self.beta, dim=-1)) + c /= self.alpha * self.beta + + return a + b - c + + def _calculate_beta_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate beta divergence between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + Beta divergence between discrete distributions of predicted and reference sentences. + + """ + self.alpha = 1.0 + return self._calculate_ab_divergence(preds_distribution, target_distribution) + + def _calculate_renyi_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate Rényi divergence between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + Rényi divergence between discrete distributions of predicted and reference sentences. + + """ + return ( + torch.log(torch.sum(target_distribution**self.alpha * preds_distribution ** (1 - self.alpha), dim=-1)) + ) / (self.alpha - 1) + + @staticmethod + def _calculate_l1_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate L1 distance between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + L1 distance between discrete distributions of predicted and reference sentences. + + """ + return torch.norm(target_distribution - preds_distribution, p=1, dim=-1) + + @staticmethod + def _calculate_l2_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate L2 distance between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + L2 distance between discrete distributions of predicted and reference sentences. + + """ + return torch.norm(target_distribution - preds_distribution, p=2, dim=-1) + + @staticmethod + def _calculate_l_infinity_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate L-infinity distance between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + L-infinity distance between discrete distributions of predicted and reference sentences. + + """ + return torch.norm(target_distribution - preds_distribution, p=float("inf"), dim=-1) + + @staticmethod + def _calculate_fisher_rao_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor: + """Calculate Fisher-Rao distance between discrete distributions of predicted and reference sentences. + + Args: + preds_distribution: + Discrete reference distribution of predicted sentences over the vocabulary. + target_distribution: + Discrete reference distribution of reference sentences over the vocabulary. + + Return: + Fisher-Rao distance between discrete distributions of predicted and reference sentences. + + """ + return 2 * torch.acos(torch.clamp(torch.sqrt(preds_distribution * target_distribution).sum(-1), 0, 1)) + + +def _get_dataloader( + input_ids: Tensor, attention_mask: Tensor, idf: bool, batch_size: int, num_workers: int +) -> DataLoader: + """Prepare dataloader. + + Args: + input_ids: + Indices of input sequence tokens in the vocabulary. + attention_mask: + Mask to avoid performing attention on padding token indices. + idf: + A bool indicating whether normalization using inverse document frequencies should be used. + batch_size: + A batch size used for model processing. + num_workers: + A number of workers to use for a dataloader. + + Return: + An instance of ``torch.utils.data.DataLoader`` used for iterating over examples. + + """ + dataset = TokenizedDataset(input_ids, attention_mask, idf) + return DataLoader(dataset, batch_size=batch_size, num_workers=num_workers) + + +def _get_special_tokens_map(tokenizer: "PreTrainedTokenizerBase") -> dict[str, int]: + """Build a dictionary of model/tokenizer special tokens. + + Args: + tokenizer: + Initialized tokenizer from HuggingFace's `transformers package. + + Return: + A dictionary containing: mask_token_id, pad_token_id, sep_token_id and cls_token_id. + + """ + return { + "mask_token_id": tokenizer.mask_token_id, + "pad_token_id": tokenizer.pad_token_id, + "sep_token_id": tokenizer.sep_token_id, + "cls_token_id": tokenizer.cls_token_id, + } + + +def _get_token_mask(input_ids: Tensor, pad_token_id: int, sep_token_id: int, cls_token_id: int) -> Tensor: + """Generate a token mask for differentiating all special tokens in the input batch. + + There are 0s for special tokens and 1s otherwise. + + Args: + input_ids: + Indices of input sequence tokens in the vocabulary. + pad_token_id: + An id of ```` tokens that are used to make arrays of tokens the same size for batching purpose + cls_token_id: + An id of ```` token that represents the class of the input. (It might be ```` token for some + models.) + sep_token_id: + An id of ```` token that separates two different sentences in the same input. (It might be ```` + token for some models.) + + Return: + Tensor mask of 0s and 1s that masks all special tokens in the ``input_ids`` tensor. + + """ + token_mask = input_ids.eq(pad_token_id) | input_ids.eq(sep_token_id) | input_ids.eq(cls_token_id) + return ~token_mask + + +def _get_batch_distribution( + model: "PreTrainedModel", + batch: dict[str, Tensor], + temperature: float, + idf: bool, + special_tokens_map: dict[str, int], +) -> Tensor: + """Calculate a discrete probability distribution for a batch of examples. See `InfoLM`_ for details. + + Args: + model: + Initialized model from HuggingFace's `transformers package. + batch: + An input batch dictionary containing ``input_ids`` and ``attention_mask``. + temperature: + A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper. + max_length: + A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed. + idf: + An indication of whether normalization using inverse document frequencies should be used. + special_tokens_map: + A dictionary mapping tokenizer special tokens into the corresponding integer values. + + Return: + A discrete probability distribution. + + """ + seq_len = batch["input_ids"].shape[1] + prob_distribution_batch_list: List[Tensor] = [] + token_mask = _get_token_mask( + batch["input_ids"], + special_tokens_map["pad_token_id"], + special_tokens_map["sep_token_id"], + special_tokens_map["cls_token_id"], + ) + for mask_idx in range(seq_len): + input_ids = batch["input_ids"].clone() + input_ids[:, mask_idx] = special_tokens_map["mask_token_id"] + logits_distribution = model(input_ids, batch["attention_mask"]).logits + # [batch_size, seq_len, vocab_size] -> [batch_size, vocab_size] + logits_distribution = logits_distribution[:, mask_idx, :] + prob_distribution = F.softmax(logits_distribution / temperature, dim=-1) + if idf: + prob_distribution *= batch["input_ids_idf"][:, mask_idx].unsqueeze(1).to(prob_distribution.device) + prob_distribution_batch_list.append(prob_distribution.unsqueeze(1).cpu()) # [batch_size, 1, vocab_size] + # Clean from memory + del input_ids, logits_distribution, prob_distribution + + prob_distribution_batch = torch.cat(prob_distribution_batch_list, dim=1) # [batch_size, seq_len, vocab_size] + prob_distribution_batch = torch.einsum("bsv, bs -> bsv", prob_distribution_batch.to(token_mask.device), token_mask) + if idf: + masked_input_ids_idf = token_mask * batch["input_ids_idf"].to(token_mask.device) + return prob_distribution_batch.sum(dim=1) / masked_input_ids_idf.sum(dim=1).unsqueeze(1) + + return prob_distribution_batch.sum(dim=1) / token_mask.sum(dim=1).unsqueeze(1) + + +@torch.no_grad() +def _get_data_distribution( + model: "PreTrainedModel", + dataloader: DataLoader, + temperature: float, + idf: bool, + special_tokens_map: dict[str, int], + verbose: bool, +) -> Tensor: + """Calculate a discrete probability distribution according to the methodology described in `InfoLM`_. + + Args: + model: + Initialized model from HuggingFace's `transformers package. + dataloader: + An instance of `torch.utils.data.DataLoader` used for iterating over examples. + temperature: + A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper. + max_length: + A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed. + idf: + An indication of whether normalization using inverse document frequencies should be used. + special_tokens_map: + A dictionary mapping tokenizer special tokens into the corresponding integer values. + verbose: + An indication of whether a progress bar to be displayed during the embeddings calculation. + + Return: + A discrete probability distribution. + + """ + device = model.device + prob_distribution: List[Tensor] = [] + + for batch in _get_progress_bar(dataloader, verbose): + batch = _input_data_collator(batch, device) + prob_distribution.append(_get_batch_distribution(model, batch, temperature, idf, special_tokens_map)) + + return torch.cat(prob_distribution, dim=0) + + +def _infolm_update( + preds: Union[str, Sequence[str]], + target: Union[str, Sequence[str]], + tokenizer: "PreTrainedTokenizerBase", + max_length: int, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + """Update the metric state by a tokenization of ``preds`` and ``target`` sentencens. + + Args: + preds: + An iterable of hypothesis corpus. + target: + An iterable of reference corpus. + tokenizer: + Initialized tokenizer from HuggingFace's `transformers package. + max_length: + A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed. + + Return: + Tokenizerd ``preds`` and ``target`` sentences represented with ``input_ids`` and ``attention_mask`` tensors. + + """ + # HuggingFace tokenizer expects an input to be of a type str or List[str] + if not isinstance(preds, (str, list)): + preds = list(preds) + if not isinstance(target, (str, list)): + target = list(target) + + preds_input = tokenizer(preds, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt") + target_input = tokenizer(target, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt") + + return preds_input.input_ids, preds_input.attention_mask, target_input.input_ids, target_input.attention_mask + + +def _infolm_compute( + model: "PreTrainedModel", + preds_dataloader: DataLoader, + target_dataloader: DataLoader, + temperature: float, + idf: bool, + information_measure_cls: _InformationMeasure, + special_tokens_map: dict[str, int], + verbose: bool = True, +) -> Tensor: + """Calculate selected information measure using the pre-trained language model. + + Args: + model: + Initialized model from HuggingFace's `transformers package. + preds_dataloader: + Loader iterating over tokenizer predicted sentences. + target_dataloader: + Loader iterating over tokenizer reference sentences. + temperature: + A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper. + idf: + An indication of whether normalization using inverse document frequencies should be used. + information_measure_cls: + Information measure class containing all parameters necessary for calculating information measure values + using ``preds_distribution`` and ``target_distribution``. + special_tokens_map: + A dictionary mapping tokenizer special tokens into the corresponding integer values. + verbose: + An indication of whether a progress bar to be displayed during the embeddings calculation. + + Return: + A corpus-level InfoLM score. + + """ + preds_distribution = _get_data_distribution(model, preds_dataloader, temperature, idf, special_tokens_map, verbose) + target_distribution = _get_data_distribution( + model, target_dataloader, temperature, idf, special_tokens_map, verbose + ) + # Sort preds and target sentences + preds_distribution = preds_distribution[preds_dataloader.dataset.sorting_indices] + target_distribution = target_distribution[target_dataloader.dataset.sorting_indices] + # Calculate information measure + return information_measure_cls(preds_distribution, target_distribution) + + +def infolm( + preds: Union[str, Sequence[str]], + target: Union[str, Sequence[str]], + model_name_or_path: Union[str, os.PathLike] = "bert-base-uncased", + temperature: float = 0.25, + information_measure: _ALLOWED_INFORMATION_MEASURE_LITERAL = "kl_divergence", + idf: bool = True, + alpha: Optional[float] = None, + beta: Optional[float] = None, + device: Optional[Union[str, torch.device]] = None, + max_length: Optional[int] = None, + batch_size: int = 64, + num_threads: int = 0, + verbose: bool = True, + return_sentence_level_score: bool = False, +) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Calculate `InfoLM`_ [1]. + + InfoML corresponds to distance/divergence between predicted and reference sentence discrete distribution using + one of the following information measures: + + - `KL divergence`_ + - `alpha divergence`_ + - `beta divergence`_ + - `AB divergence`_ + - `Rényi divergence`_ + - L1 distance + - L2 distance + - L-infinity distance + - `Fisher-Rao distance`_ + + `InfoLM`_ is a family of untrained embedding-based metrics which addresses some famous flaws of standard + string-based metrics thanks to the usage of pre-trained masked language models. This family of metrics is mainly + designed for summarization and data-to-text tasks. + + If you want to use IDF scaling over the whole dataset, please use the class metric. + + The implementation of this metric is fully based HuggingFace `transformers`' package. + + Args: + preds: + An iterable of hypothesis corpus. + target: + An iterable of reference corpus. + model_name_or_path: + A name or a model path used to load `transformers` pretrained model. + temperature: + A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper. + information_measure: + A name of information measure to be used. Please use one of: ['kl_divergence', 'alpha_divergence', + 'beta_divergence', 'ab_divergence', 'renyi_divergence', 'l1_distance', 'l2_distance', 'l_infinity_distance', + 'fisher_rao_distance'] + idf: + An indication of whether normalization using inverse document frequencies should be used. + alpha: + Alpha parameter of the divergence used for alpha, AB and Rényi divergence measures. + beta: + Beta parameter of the divergence used for beta and AB divergence measures. + device: + A device to be used for calculation. + max_length: + A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed. + batch_size: + A batch size used for model processing. + num_threads: + A number of threads to use for a dataloader. + verbose: + An indication of whether a progress bar to be displayed during the embeddings calculation. + return_sentence_level_score: + An indication whether a sentence-level InfoLM score to be returned. + + Returns: + A corpus-level InfoLM score. + (Optionally) A list of sentence-level InfoLM scores if `return_sentence_level_score=True`. + + Example: + >>> from torchmetrics.functional.text.infolm import infolm + >>> preds = ['he read the book because he was interested in world history'] + >>> target = ['he was interested in world history because he read the book'] + >>> infolm(preds, target, model_name_or_path='google/bert_uncased_L-2_H-128_A-2', idf=False) + tensor(-0.1784) + + References: + [1] InfoLM: A New Metric to Evaluate Summarization & Data2Text Generation by Pierre Colombo, Chloé Clavel and + Pablo Piantanida `InfoLM`_ + + """ + tokenizer, model = _load_tokenizer_and_model(model_name_or_path, device) + information_measure_cls = _InformationMeasure(information_measure, alpha, beta) + max_length = max_length or model.config.max_length + special_tokens_map = _get_special_tokens_map(tokenizer) + + preds_input_ids, preds_attention_mask, target_input_ids, target_attention_mask = _infolm_update( + preds, target, tokenizer, max_length + ) + preds_dataloader = _get_dataloader(preds_input_ids, preds_attention_mask, idf, batch_size, num_threads) + target_dataloader = _get_dataloader(target_input_ids, target_attention_mask, idf, batch_size, num_threads) + + info_lm_score = _infolm_compute( + model, + preds_dataloader, + target_dataloader, + temperature, + idf, + information_measure_cls, + special_tokens_map, + verbose, + ) + + if return_sentence_level_score: + return info_lm_score.mean(), info_lm_score + + return info_lm_score.mean() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/mer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/mer.py new file mode 100644 index 0000000000000000000000000000000000000000..46f30331b85df86b8a0e21a9a63a19f8515f59d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/mer.py @@ -0,0 +1,91 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.helper import _edit_distance + + +def _mer_update( + preds: Union[str, list[str]], + target: Union[str, list[str]], +) -> tuple[Tensor, Tensor]: + """Update the mer score with the current set of references and predictions. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Number of edit operations to get from the reference to the prediction, summed over all samples + Number of words overall references + + """ + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + errors = tensor(0, dtype=torch.float) + total = tensor(0, dtype=torch.float) + for pred, tgt in zip(preds, target): + pred_tokens = pred.split() + tgt_tokens = tgt.split() + errors += _edit_distance(pred_tokens, tgt_tokens) + total += max(len(tgt_tokens), len(pred_tokens)) + + return errors, total + + +def _mer_compute(errors: Tensor, total: Tensor) -> Tensor: + """Compute the match error rate. + + Args: + errors: Number of edit operations to get from the reference to the prediction, summed over all samples + total: Number of words overall references + + Returns: + Match error rate score + + """ + return errors / total + + +def match_error_rate(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Match error rate is a metric of the performance of an automatic speech recognition system. + + This value indicates the percentage of words that were incorrectly predicted and inserted. The lower the value, the + better the performance of the ASR system with a MatchErrorRate of 0 being a perfect score. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Match error rate score + + Examples: + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> match_error_rate(preds=preds, target=target) + tensor(0.4444) + + """ + errors, total = _mer_update( + preds, + target, + ) + return _mer_compute(errors, total) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/perplexity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/perplexity.py new file mode 100644 index 0000000000000000000000000000000000000000..5931b7b6944166c3f1278367845e8b198cbcead9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/perplexity.py @@ -0,0 +1,142 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional + +import torch +from torch import Tensor + + +def _check_shape_and_type_consistency(preds: Tensor, target: Tensor) -> None: + """Check shape and type consistency of input vectors. + + Args: + preds: + Logits or a unnormalized score assigned to each token in a sequence with shape [batch_size, seq_len, + vocab_size]. Scores will be normalized internally using softmax. + target: + Ground truth values with a shape [batch_size, seq_len]. + + Raises: + ValueError: + If ``preds`` tensor has no 3 dimensions. + ValueError: + If ``target`` tensor has no 2 dimensions. + ValueError: + If the first two dimensions of ``preds`` and ``target`` do not equal. + TypeError: + If ``preds`` dtype is not one of ``(torch.float16, torch.float32, torch.float64)`` + TypeError: + If ``target`` is not of a type LongTensor (torch.int64) + + """ + if len(preds.shape) != 3: + raise ValueError( + "Input tensor `preds` is expected to have 3 dimensions, [batch_size, seq_len, vocab_size]," + f" but got {len(preds.shape)}." + ) + if len(target.shape) != 2: + raise ValueError( + "Input tensor `target` is expected to have 2 dimensions, [batch_size, seq_len]," + f" but got {len(target.shape)}." + ) + if preds.shape[:2] != target.shape: + raise ValueError( + "Input tensors `preds` and `target` are expected to have equaling first two dimensions," + f" [batch_size, seq_len], but got {preds.shape[:2]} and {target.shape}." + ) + if not preds.is_floating_point(): + raise TypeError(f"Input tensor `preds` is expected to be of floating point type but got {preds.dtype}.") + if target.dtype != torch.int64: + raise TypeError(f"Input tensor `target` is expected to be of a type {torch.int64} but got {target.dtype}.") + + +def _perplexity_update(preds: Tensor, target: Tensor, ignore_index: Optional[int] = None) -> tuple[Tensor, Tensor]: + """Compute intermediate statistics for Perplexity. + + Args: + preds: + Logits or a unnormalized score assigned to each token in a sequence with shape [batch_size, seq_len, + vocab_size]. Scores will be normalized internally using softmax. + target: + Ground truth values with a shape [batch_size, seq_len]. + ignore_index: + Integer specifying a target class to ignore. If given, this class index does not contribute + to the returned score. + + Returns: + Log probabilities, summed over all samples + Number of samples + + """ + _check_shape_and_type_consistency(preds, target) + + probs = torch.nn.functional.softmax(preds.reshape(-1, preds.shape[-1]), dim=1) + target = target.reshape(-1) + + if ignore_index is not None: + mask = target.ne(ignore_index) + target = target.where(target != ignore_index, torch.tensor(0, device=target.device)) + else: + mask = torch.ones_like(target, dtype=torch.bool) + + probs = probs[torch.arange(target.numel()), target][mask] + total_log_probs = -probs.log().sum() + count = mask.sum() + + return total_log_probs, count + + +def _perplexity_compute(total: Tensor, count: Tensor) -> Tensor: + """Compute the Perplexity. + + Args: + total: Log probabilities, summed over all samples + count: Number of samples + Returns: + Perplexity + + """ + return torch.exp(total / count) + + +def perplexity(preds: Tensor, target: Tensor, ignore_index: Optional[int] = None) -> Tensor: + """Perplexity measures how well a language model predicts a text sample. + + This metric is calculated as the average number of bits per word a model needs to represent the sample. + + Args: + preds: + Logits or a unnormalized score assigned to each token in a sequence with shape [batch_size, seq_len, + vocab_size], which is the output of a language model. Scores will be normalized internally using softmax. + target: + Ground truth values with a shape [batch_size, seq_len]. + ignore_index: + Integer specifying a target class to ignore. If given, this class index does not contribute + to the returned score. + + Returns: + Perplexity value + + Examples: + >>> from torch import rand, randint + >>> preds = rand(2, 8, 5) + >>> target = randint(5, (2, 8)) + >>> target[0, 6:] = -100 + >>> perplexity(preds, target, ignore_index=-100) + tensor(5.8540) + + """ + total, count = _perplexity_update(preds, target, ignore_index) + return _perplexity_compute(total, count) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/rouge.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/rouge.py new file mode 100644 index 0000000000000000000000000000000000000000..305c6f7c4553044202a8d7d2459a97e679b016a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/rouge.py @@ -0,0 +1,513 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import re +from collections import Counter +from collections.abc import Sequence +from typing import Any, Callable, List, Optional, Union + +import torch +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.utilities.imports import _NLTK_AVAILABLE + +__doctest_requires__ = {("rouge_score", "_rouge_score_update"): ["nltk"]} + +ALLOWED_ROUGE_KEYS: dict[str, Union[int, str]] = { + "rouge1": 1, + "rouge2": 2, + "rouge3": 3, + "rouge4": 4, + "rouge5": 5, + "rouge6": 6, + "rouge7": 7, + "rouge8": 8, + "rouge9": 9, + "rougeL": "L", + "rougeLsum": "Lsum", +} +ALLOWED_ACCUMULATE_VALUES = ("avg", "best") + + +def _ensure_nltk_punkt_is_downloaded() -> None: + """Check whether `nltk` `punkt` is downloaded. + + If not, try to download if a machine is connected to the internet. + + """ + import nltk + + try: + nltk.data.find("tokenizers/punkt_tab") + except LookupError: + try: + nltk.download("punkt_tab", quiet=True, force=False, halt_on_error=False, raise_on_error=True) + except ValueError as err: + raise OSError( + "`nltk` resource `punkt` is not available on a disk and cannot be downloaded as a machine is not " + "connected to the internet." + ) from err + + +def _split_sentence(x: str) -> Sequence[str]: + """Split sentence to get rougeLsum scores matching published rougeL scores for BART and PEGASUS.""" + if not _NLTK_AVAILABLE: + raise ModuleNotFoundError("ROUGE-Lsum calculation requires that `nltk` is installed. Use `pip install nltk`.") + import nltk + + _ensure_nltk_punkt_is_downloaded() + + re.sub("", "", x) # remove pegasus newline char + return nltk.sent_tokenize(x) + + +def _compute_metrics(hits_or_lcs: int, pred_len: int, target_len: int) -> dict[str, Tensor]: + """Compute overall metrics. + + This function computes precision, recall and F1 score based on hits/lcs, the length of lists of tokenizer + predicted and target sentences. + + Args: + hits_or_lcs: A number of matches or a length of the longest common subsequence. + pred_len: A length of a tokenized predicted sentence. + target_len: A length of a tokenized target sentence. + + """ + precision = hits_or_lcs / pred_len + recall = hits_or_lcs / target_len + if precision == recall == 0.0: + return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)} + + fmeasure = 2 * precision * recall / (precision + recall) + return {"precision": tensor(precision), "recall": tensor(recall), "fmeasure": tensor(fmeasure)} + + +def _lcs( + pred_tokens: Sequence[str], target_tokens: Sequence[str], return_full_table: bool = False +) -> Union[int, Sequence[Sequence[int]]]: + """DP algorithm to compute the length of the longest common subsequence. + + Args: + pred_tokens: A tokenized predicted sentence. + target_tokens: A tokenized target sentence. + return_full_table: If the full table of logest common subsequence should be returned or just the largest + + """ + lcs = [[0] * (len(pred_tokens) + 1) for _ in range(len(target_tokens) + 1)] + for i in range(1, len(target_tokens) + 1): + for j in range(1, len(pred_tokens) + 1): + if target_tokens[i - 1] == pred_tokens[j - 1]: + lcs[i][j] = lcs[i - 1][j - 1] + 1 + else: + lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]) + if return_full_table: + return lcs + return lcs[-1][-1] + + +def _backtracked_lcs( + lcs_table: Sequence[Sequence[int]], pred_tokens: Sequence[str], target_tokens: Sequence[str] +) -> Sequence[int]: + """Backtrack LCS table. + + Args: + lcs_table: A table containing information for the calculation of the longest common subsequence. + pred_tokens: A tokenized predicted sentence. + target_tokens: A tokenized target sentence. + + """ + i = len(pred_tokens) + j = len(target_tokens) + backtracked_lcs: list[int] = [] + while i > 0 and j > 0: + if pred_tokens[i - 1] == target_tokens[j - 1]: + backtracked_lcs.insert(0, j - 1) + i -= 1 + j -= 1 + elif lcs_table[j][i - 1] > lcs_table[j - 1][i]: + i -= 1 + else: + j -= 1 + return backtracked_lcs + + +def _union_lcs(pred_tokens_list: Sequence[Sequence[str]], target_tokens: Sequence[str]) -> Sequence[str]: + r"""Find union LCS between a target sentence and iterable of predicted tokens. + + Args: + pred_tokens_list: A tokenized predicted sentence split by ``'\n'``. + target_tokens: A tokenized single part of target sentence split by ``'\n'``. + + """ + + def lcs_ind(pred_tokens: Sequence[str], target_tokens: Sequence[str]) -> Sequence[int]: + """Return one of the longest of longest common subsequence via backtracked lcs table.""" + lcs_table: Sequence[Sequence[int]] = _lcs(pred_tokens, target_tokens, return_full_table=True) # type: ignore + return _backtracked_lcs(lcs_table, pred_tokens, target_tokens) + + def find_union(lcs_tables: Sequence[Sequence[int]]) -> Sequence[int]: + """Find union LCS given a list of LCS.""" + return sorted(set().union(*lcs_tables)) + + lcs_tables = [lcs_ind(pred_tokens, target_tokens) for pred_tokens in pred_tokens_list] + return [target_tokens[i] for i in find_union(lcs_tables)] + + +def _normalize_and_tokenize_text( + text: str, + stemmer: Optional[Any] = None, + normalizer: Optional[Callable[[str], str]] = None, + tokenizer: Optional[Callable[[str], Sequence[str]]] = None, +) -> Sequence[str]: + """Rouge score should be calculated only over lowercased words and digits. + + Optionally, Porter stemmer can be used to strip word suffixes to improve matching. The text normalization follows + the implemantion from `Rouge score_Text Normalizition`_. + + Args: + text: An input sentence. + stemmer: Porter stemmer instance to strip word suffixes to improve matching. + normalizer: A user's own normalizer function. + If this is ``None``, replacing any non-alpha-numeric characters with spaces is default. + This function must take a ``str`` and return a ``str``. + tokenizer: + A user's own tokenizer function. If this is ``None``, splitting by spaces is default + This function must take a ``str`` and return ``Sequence[str]`` + + """ + # If normalizer is none, replace any non-alpha-numeric characters with spaces. + text = normalizer(text) if callable(normalizer) else re.sub(r"[^a-z0-9]+", " ", text.lower()) + + # If tokenizer is none, splitting by spaces + tokens = tokenizer(text) if callable(tokenizer) else re.split(r"\s+", text) + + if stemmer: + # Only stem words more than 3 characters long. + tokens = [stemmer.stem(x) if len(x) > 3 else x for x in tokens] + + # One final check to drop any empty or invalid tokens. + return [x for x in tokens if (isinstance(x, str) and len(x) > 0)] + + +def _rouge_n_score(pred: Sequence[str], target: Sequence[str], n_gram: int) -> dict[str, Tensor]: + """Compute precision, recall and F1 score for the Rouge-N metric. + + Args: + pred: A predicted sentence. + target: A target sentence. + n_gram: N-gram overlap. + + """ + + def _create_ngrams(tokens: Sequence[str], n: int) -> Counter: + ngrams: Counter = Counter() + for ngram in (tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1)): + ngrams[ngram] += 1 + return ngrams + + pred_ngrams, target_ngrams = _create_ngrams(pred, n_gram), _create_ngrams(target, n_gram) + pred_len, target_len = sum(pred_ngrams.values()), sum(target_ngrams.values()) + if 0 in (pred_len, target_len): + return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)} + + # It is sufficient to take a set(pred_tokenized) for hits count as we consider intersenction of pred & target + hits = sum(min(pred_ngrams[w], target_ngrams[w]) for w in set(pred_ngrams)) + return _compute_metrics(hits, max(pred_len, 1), max(target_len, 1)) + + +def _rouge_l_score(pred: Sequence[str], target: Sequence[str]) -> dict[str, Tensor]: + """Compute precision, recall and F1 score for the Rouge-L metric. + + Args: + pred: A predicted sentence. + target: A target sentence. + + """ + pred_len, target_len = len(pred), len(target) + if 0 in (pred_len, target_len): + return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)} + + lcs: int = _lcs(pred, target) # type: ignore + return _compute_metrics(lcs, pred_len, target_len) + + +def _rouge_lsum_score(pred: Sequence[Sequence[str]], target: Sequence[Sequence[str]]) -> dict[str, Tensor]: + r"""Compute precision, recall and F1 score for the Rouge-LSum metric. + + More information can be found in Section 3.2 of the referenced paper [1]. This implementation follow the official + implementation from: + https://github.com/google-research/google-research/blob/master/rouge/rouge_scorer.py. + + Args: + pred: An iterable of predicted sentence split by '\n'. + target: An iterable target sentence split by '\n'. + + References: + [1] ROUGE: A Package for Automatic Evaluation of Summaries by Chin-Yew Lin. https://aclanthology.org/W04-1013/ + + """ + pred_len = sum(map(len, pred)) + target_len = sum(map(len, target)) + if 0 in (pred_len, target_len): + return {"precision": tensor(0.0), "recall": tensor(0.0), "fmeasure": tensor(0.0)} + + # Get token counts + def _get_token_counts(sentences: Sequence[Sequence[str]]) -> Counter: + ngrams: Counter = Counter() + for sentence in sentences: + ngrams.update(sentence) + return ngrams + + pred_tokens_count = _get_token_counts(pred) + target_tokens_count = _get_token_counts(target) + + # Calculate hits + hits = 0 + for tgt in target: + lcs = _union_lcs(pred, tgt) + for token in lcs: + if pred_tokens_count[token] > 0 and target_tokens_count[token] > 0: + hits += 1 + pred_tokens_count[token] -= 1 + target_tokens_count[token] -= 1 + + return _compute_metrics(hits, pred_len, target_len) + + +def _rouge_score_update( + preds: Sequence[str], + target: Sequence[Sequence[str]], + rouge_keys_values: list[Union[int, str]], + accumulate: str, + stemmer: Optional[Any] = None, + normalizer: Optional[Callable[[str], str]] = None, + tokenizer: Optional[Callable[[str], Sequence[str]]] = None, +) -> dict[Union[int, str], list[dict[str, Tensor]]]: + """Update the rouge score with the current set of predicted and target sentences. + + Args: + preds: An iterable of predicted sentences. + target: An iterable of iterable of target sentences. + rouge_keys_values: List of N-grams/'L'/'Lsum' arguments. + accumulate: Useful in case of multi-reference rouge score. + ``avg`` takes the avg of all references with respect to predictions + ``best`` takes the best fmeasure score obtained between prediction and multiple corresponding references. + Allowed values are ``avg`` and ``best``. + stemmer: Porter stemmer instance to strip word suffixes to improve matching. + normalizer: + A user's own normalizer function. + If this is ``None``, replacing any non-alpha-numeric characters with spaces is default. + This function must take a `str` and return a `str`. + tokenizer: + A user's own tokenizer function. If this is ``None``, splitting by spaces is default + This function must take a `str` and return `Sequence[str]` + + Example: + >>> preds = ["My name is John"] + >>> target = [["Is your name John"]] + >>> from pprint import pprint + >>> score = _rouge_score_update(preds, target, rouge_keys_values=[1, 2, 'L'], accumulate='best') + >>> pprint(score) + {1: [{'fmeasure': tensor(0.7500), + 'precision': tensor(0.7500), + 'recall': tensor(0.7500)}], + 2: [{'fmeasure': tensor(0.), 'precision': tensor(0.), 'recall': tensor(0.)}], + 'L': [{'fmeasure': tensor(0.5000), + 'precision': tensor(0.5000), + 'recall': tensor(0.5000)}]} + + """ + results: dict[Union[int, str], list[dict[str, Tensor]]] = {rouge_key: [] for rouge_key in rouge_keys_values} + + for pred_raw, target_raw in zip(preds, target): + result_inner: dict[Union[int, str], dict[str, Tensor]] = {rouge_key: {} for rouge_key in rouge_keys_values} + result_avg: dict[Union[int, str], list[dict[str, Tensor]]] = {rouge_key: [] for rouge_key in rouge_keys_values} + list_results = [] + pred = _normalize_and_tokenize_text(pred_raw, stemmer, normalizer, tokenizer) + if "Lsum" in rouge_keys_values: + pred_lsum = [ + _normalize_and_tokenize_text(pred_sentence, stemmer, normalizer, tokenizer) + for pred_sentence in _split_sentence(pred_raw) + ] + + for target_raw_inner in target_raw: + tgt = _normalize_and_tokenize_text(target_raw_inner, stemmer, normalizer, tokenizer) + + if "Lsum" in rouge_keys_values: + target_lsum = [ + _normalize_and_tokenize_text(tgt_sentence, stemmer, normalizer, tokenizer) + for tgt_sentence in _split_sentence(target_raw_inner) + ] + + for rouge_key in rouge_keys_values: + if isinstance(rouge_key, int): + score = _rouge_n_score(pred, tgt, rouge_key) + elif rouge_key == "L": + score = _rouge_l_score(pred, tgt) + elif rouge_key == "Lsum": + score = _rouge_lsum_score(pred_lsum, target_lsum) + result_inner[rouge_key] = score + result_avg[rouge_key].append(score) + list_results.append(result_inner.copy()) + + if accumulate == "best": + for k in rouge_keys_values: + index = torch.argmax(torch.tensor([s[k]["fmeasure"] for s in list_results])) + results[k].append(list_results[index][k]) + + elif accumulate == "avg": + new_result_avg: dict[Union[int, str], dict[str, Tensor]] = { + rouge_key: {} for rouge_key in rouge_keys_values + } + for rouge_key, metrics in result_avg.items(): + _dict_metric_score_batch: dict[str, List[Tensor]] = {} + for metric in metrics: + for _type, value in metric.items(): + if _type not in _dict_metric_score_batch: + _dict_metric_score_batch[_type] = [] + _dict_metric_score_batch[_type].append(value) + + new_result_avg[rouge_key] = { + _type: torch.tensor(_dict_metric_score_batch[_type]).mean() for _type in _dict_metric_score_batch + } + + for rouge_key in rouge_keys_values: + results[rouge_key].append(new_result_avg[rouge_key]) # todo + + return results + + +def _rouge_score_compute(sentence_results: dict[str, List[Tensor]]) -> dict[str, Tensor]: + """Compute the combined ROUGE metric for all the input set of predicted and target sentences. + + Args: + sentence_results: Rouge-N/Rouge-L/Rouge-LSum metrics calculated for single sentence. + + """ + results: dict[str, Tensor] = {} + # Obtain mean scores for individual rouge metrics + if sentence_results == {}: + return results + + for rouge_key, scores in sentence_results.items(): + results[rouge_key] = torch.tensor(scores).mean() + + return results + + +def rouge_score( + preds: Union[str, Sequence[str]], + target: Union[str, Sequence[str], Sequence[Sequence[str]]], + accumulate: Literal["avg", "best"] = "best", + use_stemmer: bool = False, + normalizer: Optional[Callable[[str], str]] = None, + tokenizer: Optional[Callable[[str], Sequence[str]]] = None, + rouge_keys: Union[str, tuple[str, ...]] = ("rouge1", "rouge2", "rougeL", "rougeLsum"), +) -> dict[str, Tensor]: + """Calculate `Calculate Rouge Score`_ , used for automatic summarization. + + Args: + preds: An iterable of predicted sentences or a single predicted sentence. + target: + An iterable of iterables of target sentences or an iterable of target sentences or a single target sentence. + accumulate: + Useful in case of multi-reference rouge score. + + - ``avg`` takes the avg of all references with respect to predictions + - ``best`` takes the best fmeasure score obtained between prediction and multiple corresponding references. + + use_stemmer: Use Porter stemmer to strip word suffixes to improve matching. + normalizer: A user's own normalizer function. + If this is ``None``, replacing any non-alpha-numeric characters with spaces is default. + This function must take a ``str`` and return a ``str``. + tokenizer: A user's own tokenizer function. If this is ``None``, splitting by spaces is default + This function must take a ``str`` and return ``Sequence[str]`` + rouge_keys: A list of rouge types to calculate. + Keys that are allowed are ``rougeL``, ``rougeLsum``, and ``rouge1`` through ``rouge9``. + + Return: + Python dictionary of rouge scores for each input rouge key. + + Example: + >>> from torchmetrics.functional.text.rouge import rouge_score + >>> preds = "My name is John" + >>> target = "Is your name John" + >>> from pprint import pprint + >>> pprint(rouge_score(preds, target)) + {'rouge1_fmeasure': tensor(0.7500), + 'rouge1_precision': tensor(0.7500), + 'rouge1_recall': tensor(0.7500), + 'rouge2_fmeasure': tensor(0.), + 'rouge2_precision': tensor(0.), + 'rouge2_recall': tensor(0.), + 'rougeL_fmeasure': tensor(0.5000), + 'rougeL_precision': tensor(0.5000), + 'rougeL_recall': tensor(0.5000), + 'rougeLsum_fmeasure': tensor(0.5000), + 'rougeLsum_precision': tensor(0.5000), + 'rougeLsum_recall': tensor(0.5000)} + + + Raises: + ModuleNotFoundError: + If the python package ``nltk`` is not installed. + ValueError: + If any of the ``rouge_keys`` does not belong to the allowed set of keys. + + References: + [1] ROUGE: A Package for Automatic Evaluation of Summaries by Chin-Yew Lin. https://aclanthology.org/W04-1013/ + + """ + if use_stemmer: + if not _NLTK_AVAILABLE: + raise ModuleNotFoundError("Stemmer requires that `nltk` is installed. Use `pip install nltk`.") + import nltk + + stemmer = nltk.stem.porter.PorterStemmer() if use_stemmer else None + + if not isinstance(rouge_keys, tuple): + rouge_keys = (rouge_keys,) + for key in rouge_keys: + if key not in ALLOWED_ROUGE_KEYS: + raise ValueError(f"Got unknown rouge key {key}. Expected to be one of {list(ALLOWED_ROUGE_KEYS.keys())}") + rouge_keys_values = [ALLOWED_ROUGE_KEYS[key] for key in rouge_keys] + + if isinstance(target, list) and all(isinstance(tgt, str) for tgt in target): + target = [target] if isinstance(preds, str) else [[tgt] for tgt in target] + + if isinstance(preds, str): + preds = [preds] + + if isinstance(target, str): + target = [[target]] + + sentence_results: dict[Union[int, str], list[dict[str, Tensor]]] = _rouge_score_update( + preds, + target, + rouge_keys_values, + stemmer=stemmer, + normalizer=normalizer, + tokenizer=tokenizer, + accumulate=accumulate, + ) + + output: dict[str, List[Tensor]] = { + f"rouge{rouge_key}_{tp}": [] for rouge_key in rouge_keys_values for tp in ["fmeasure", "precision", "recall"] + } + for rouge_key, metrics in sentence_results.items(): + for metric in metrics: + for tp, value in metric.items(): + output[f"rouge{rouge_key}_{tp}"].append(value) # todo + + return _rouge_score_compute(output) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/sacre_bleu.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/sacre_bleu.py new file mode 100644 index 0000000000000000000000000000000000000000..e69ec621c9d30f9afa2e1f9ad1c52a4a7848916d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/sacre_bleu.py @@ -0,0 +1,555 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# referenced from +# Library Name: torchtext +# Authors: torchtext authors and @sluks +# Date: 2020-07-18 +# Link: https://pytorch.org/text/_modules/torchtext/data/metrics.html#bleu_score + +############## + +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + +############## + +# MIT License +# Copyright (c) 2017 - Shujian Huang + +import os +import re +import tempfile +from collections.abc import Sequence +from functools import partial +from typing import Any, ClassVar, Optional + +import torch +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.functional.text.bleu import _bleu_score_compute, _bleu_score_update +from torchmetrics.utilities.imports import ( + _IPADIC_AVAILABLE, + _MECAB_AVAILABLE, + _MECAB_KO_AVAILABLE, + _MECAB_KO_DIC_AVAILABLE, + _REGEX_AVAILABLE, + _SENTENCEPIECE_AVAILABLE, +) + +AVAILABLE_TOKENIZERS = ("none", "13a", "zh", "intl", "char", "ja-mecab", "ko-mecab", "flores101", "flores200") +_TokenizersLiteral = Literal["none", "13a", "zh", "intl", "char", "ja-mecab", "ko-mecab", "flores101", "flores200"] + +_UCODE_RANGES = ( + ("\u3400", "\u4db5"), # CJK Unified Ideographs Extension A, release 3.0 + ("\u4e00", "\u9fa5"), # CJK Unified Ideographs, release 1.1 + ("\u9fa6", "\u9fbb"), # CJK Unified Ideographs, release 4.1 + ("\uf900", "\ufa2d"), # CJK Compatibility Ideographs, release 1.1 + ("\ufa30", "\ufa6a"), # CJK Compatibility Ideographs, release 3.2 + ("\ufa70", "\ufad9"), # CJK Compatibility Ideographs, release 4.1 + ("\u20000", "\u2a6d6"), # (UTF16) CJK Unified Ideographs Extension B, release 3.1 + ("\u2f800", "\u2fa1d"), # (UTF16) CJK Compatibility Supplement, release 3.1 + ("\uff00", "\uffef"), # Full width ASCII, full width of English punctuation, + # half width Katakana, half wide half width kana, Korean alphabet + ("\u2e80", "\u2eff"), # CJK Radicals Supplement + ("\u3000", "\u303f"), # CJK punctuation mark + ("\u31c0", "\u31ef"), # CJK stroke + ("\u2f00", "\u2fdf"), # Kangxi Radicals + ("\u2ff0", "\u2fff"), # Chinese character structure + ("\u3100", "\u312f"), # Phonetic symbols + ("\u31a0", "\u31bf"), # Phonetic symbols (Taiwanese and Hakka expansion) + ("\ufe10", "\ufe1f"), + ("\ufe30", "\ufe4f"), + ("\u2600", "\u26ff"), + ("\u2700", "\u27bf"), + ("\u3200", "\u32ff"), + ("\u3300", "\u33ff"), +) + + +_FLORES_LOCAL_DIR = os.path.join(tempfile.gettempdir(), "torchmetrics-flores") +# Model paths copied from https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/tokenizers/tokenizer_spm.py. +_FLORES_MODELS_URL = { + "flores101": "https://dl.fbaipublicfiles.com/fairseq/models/flores/sacrebleu_tokenizer_spm.model", + "flores200": "https://tinyurl.com/flores200sacrebleuspm", +} + + +class _SacreBLEUTokenizer: + """Tokenizer used for SacreBLEU calculation. + + Source: https://github.com/mjpost/sacrebleu/tree/master/sacrebleu/tokenizers + + """ + + _REGEX = ( + # language-dependent part (assuming Western languages) + (re.compile(r"([\{-\~\[-\` -\&\(-\+\:-\@\/])"), r" \1 "), + # tokenize period and comma unless preceded by a digit + (re.compile(r"([^0-9])([\.,])"), r"\1 \2 "), + # tokenize period and comma unless followed by a digit + (re.compile(r"([\.,])([^0-9])"), r" \1 \2"), + # tokenize dash when preceded by a digit + (re.compile(r"([0-9])(-)"), r"\1 \2 "), + # one space only between words + # NOTE: Doing this in Python (below) is faster + # (re.compile(r'\s+'), r' '), + ) + + if _REGEX_AVAILABLE: + import regex + + _INT_REGEX = ( + # Separate out punctuation preceded by a non-digit + (regex.compile(r"(\P{N})(\p{P})"), r"\1 \2 "), + # Separate out punctuation followed by a non-digit + (regex.compile(r"(\p{P})(\P{N})"), r" \1 \2"), + # Separate out symbols + (regex.compile(r"(\p{S})"), r" \1 "), + ) + + _TOKENIZE_FN: ClassVar[dict] = { + "none": "_tokenize_base", + "13a": "_tokenize_13a", + "zh": "_tokenize_zh", + "intl": "_tokenize_international", + "char": "_tokenize_char", + "ja-mecab": "_tokenize_ja_mecab", + "ko-mecab": "_tokenize_ko_mecab", + "flores101": "_tokenize_flores_101", + "flores200": "_tokenize_flores_200", + } + + # Keep it as class variable to avoid initializing over and over again + sentencepiece_processors: ClassVar[dict[str, Optional[Any]]] = {"flores101": None, "flores200": None} + + def __init__(self, tokenize: _TokenizersLiteral, lowercase: bool = False) -> None: + self._check_tokenizers_validity(tokenize) + + self.tokenize_fn = getattr(self, self._TOKENIZE_FN[tokenize]) + self.lowercase = lowercase + + def __call__(self, line: str) -> Sequence[str]: + tokenized_line = self.tokenize_fn(line) + return self._lower(tokenized_line, self.lowercase).split() + + @classmethod + def tokenize( + cls: type["_SacreBLEUTokenizer"], + line: str, + tokenize: _TokenizersLiteral, + lowercase: bool = False, + ) -> Sequence[str]: + cls._check_tokenizers_validity(tokenize) + + tokenize_fn = getattr(cls, cls._TOKENIZE_FN[tokenize]) + tokenized_line = tokenize_fn(line) + return cls._lower(tokenized_line, lowercase).split() + + @classmethod + def _tokenize_regex(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Post-processing tokenizer for `13a` and `zh` tokenizers. + + Args: + line: a segment to tokenize + + Return: + the tokenized line + + """ + for _re, repl in cls._REGEX: + line = _re.sub(repl, line) + # no leading or trailing spaces, single space within words + return " ".join(line.split()) + + @staticmethod + def _is_chinese_char(uchar: str) -> bool: + """Check if character is chinese. + + Args: + uchar: input char in unicode. + + Return: + whether the input char is a Chinese character. + + """ + return any(start <= uchar <= end for start, end in _UCODE_RANGES) + + @classmethod + def _tokenize_base(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenizes an input line with the tokenizer. + + Args: + line: a segment to tokenize + + Return: + the tokenized line + + """ + return line + + @classmethod + def _tokenize_13a(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenizes a line using a relatively minimal tokenization that is equivalent to mteval-v13a, used by WMT. + + Args: + line: input sentence + + Return: + tokenized sentence + + """ + # language-independent part: + line = line.replace("", "") + line = line.replace("-\n", "") + line = line.replace("\n", " ") + + if "&" in line: + line = line.replace(""", '"') + line = line.replace("&", "&") + line = line.replace("<", "<") + line = line.replace(">", ">") + + return cls._tokenize_regex(f" {line} ") + + @classmethod + def _tokenize_zh(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenization of Chinese text. + + This is done in two steps: separate each Chinese characters (by utf-8 encoding) and afterwards tokenize the + Chinese part (following the `13a` i.e. mteval tokenizer). + Author: Shujian Huang huangsj@nju.edu.cn. + + Args: + line: input sentence + + Return: + tokenized sentence + + """ + line = line.strip() + line_in_chars = "" + + for char in line: + if cls._is_chinese_char(char): + line_in_chars += " " + line_in_chars += char + line_in_chars += " " + else: + line_in_chars += char + + return cls._tokenize_regex(line_in_chars) + + @classmethod + def _tokenize_international(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + r"""Tokenizes a string following the official BLEU implementation. + + See github.com/moses-smt/mosesdecoder/blob/master/scripts/generic/mteval-v14.pl#L954-L983 + + In our case, the input string is expected to be just one line. + We just tokenize on punctuation and symbols, + except when a punctuation is preceded and followed by a digit + (e.g. a comma/dot as a thousand/decimal separator). + We do not recover escaped forms of punctuation such as ' or > + as these should never appear in MT system outputs (see issue #138) + + Note that a number (e.g., a year) followed by a dot at the end of + sentence is NOT tokenized, i.e. the dot stays with the number because + `s/(\\p{P})(\\P{N})/ $1 $2/g` does not match this case (unless we add a + space after each sentence). However, this error is already in the + original mteval-v14.pl and we want to be consistent with it. + The error is not present in the non-international version, + which uses `$norm_text = " $norm_text "`. + + Args: + line: the input string to tokenize. + + Return: + The tokenized string. + + """ + for _re, repl in cls._INT_REGEX: + line = _re.sub(repl, line) + + return " ".join(line.split()) + + @classmethod + def _tokenize_char(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenizes all the characters in the input line. + + Args: + line: a segment to tokenize + + Return: + the tokenized line + + """ + return " ".join(char for char in line) + + @classmethod + def _tokenize_ja_mecab(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenizes a Japanese string line using MeCab morphological analyzer. + + Args: + line: the input string to tokenize. + + Return: + The tokenized string. + + """ + import ipadic + import MeCab + + tagger = MeCab.Tagger(ipadic.MECAB_ARGS + " -Owakati") + + line = line.strip() + return tagger.parse(line).strip() + + @classmethod + def _tokenize_ko_mecab(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenizes a Korean string line using MeCab-korean morphological analyzer. + + Args: + line: the input string to tokenize. + + Return: + The tokenized string. + + """ + import mecab_ko + import mecab_ko_dic + + tagger = mecab_ko.Tagger(mecab_ko_dic.MECAB_ARGS + " -Owakati") + + line = line.strip() + return tagger.parse(line).strip() + + @classmethod + def _tokenize_flores( + cls: type["_SacreBLEUTokenizer"], line: str, tokenize: Literal["flores101", "flores200"] + ) -> str: + """Tokenizes a string line using sentencepiece tokenizer. + + Args: + line: the input string to tokenize. + tokenize: Tokenization technique to be used. + + Return: + The tokenized string. + + """ + import sentencepiece + + if cls.sentencepiece_processors[tokenize] is None: + cls.sentencepiece_processors[tokenize] = sentencepiece.SentencePieceProcessor() + + file_path = os.path.join(_FLORES_LOCAL_DIR, _FLORES_MODELS_URL[tokenize].split("/")[-1]) + if not os.path.exists(file_path): + cls.download_flores_file(tokenize) + + cls.sentencepiece_processors[tokenize].Load(file_path) # type: ignore[union-attr] + + return " ".join(cls.sentencepiece_processors[tokenize].EncodeAsPieces(line)) # type: ignore[union-attr] + + @classmethod + def _tokenize_flores_101(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenizes a string line using sentencepiece tokenizer according to `FLORES-101`_ dataset. + + Args: + line: the input string to tokenize. + + Return: + The tokenized string. + + """ + return cls._tokenize_flores(line, "flores101") + + @classmethod + def _tokenize_flores_200(cls: type["_SacreBLEUTokenizer"], line: str) -> str: + """Tokenizes a string line using sentencepiece tokenizer according to `FLORES-200`_ dataset. + + Args: + line: the input string to tokenize. + + Return: + The tokenized string. + + """ + return cls._tokenize_flores(line, "flores200") + + @staticmethod + def _lower(line: str, lowercase: bool) -> str: + if lowercase: + return line.lower() + return line + + @classmethod + def _check_tokenizers_validity(cls: type["_SacreBLEUTokenizer"], tokenize: _TokenizersLiteral) -> None: + """Check if a supported tokenizer is chosen. + + Also check all dependencies of a given tokenizers are installed. + + """ + if tokenize not in cls._TOKENIZE_FN: + raise ValueError(f"Unsupported tokenizer selected. Please, choose one of {list(cls._TOKENIZE_FN.keys())}") + + if tokenize == "intl" and not _REGEX_AVAILABLE: + raise ModuleNotFoundError( + "`'intl'` tokenization requires that `regex` is installed." + " Use `pip install regex` or `pip install torchmetrics[text]`." + ) + + if tokenize == "ja-mecab" and not (_MECAB_AVAILABLE and _IPADIC_AVAILABLE): + raise ModuleNotFoundError( + "`'ja-mecab'` tokenization requires that `MeCab` and `ipadic` are installed." + " Use `pip install mecab-python3 ipadic` or `pip install torchmetrics[text]`." + ) + + if tokenize == "ko-mecab" and not (_MECAB_KO_AVAILABLE and _MECAB_KO_DIC_AVAILABLE): + raise ModuleNotFoundError( + "`'ko-mecab'` tokenization requires that `mecab_ko` and `mecab_ko_dic` are installed." + " Use `pip install mecab_ko mecab_ko_dic` or `pip install torchmetrics[text]`." + ) + + if "flores" in tokenize and not _SENTENCEPIECE_AVAILABLE: + raise ModuleNotFoundError( + "`'flores101' and 'flores200'` tokenizations require that `sentencepiece` is installed." + " Use `pip install sentencepiece` or `pip install torchmetrics[text]`." + ) + + @staticmethod + def download_flores_file(model_name: Literal["flores101", "flores200"]) -> None: + """Download necessary files for `flores` tokenization via `sentencepiece`.""" + import ssl + import urllib.request + + os.makedirs(_FLORES_LOCAL_DIR, exist_ok=True) + + model_url = _FLORES_MODELS_URL[model_name] + file_path = os.path.join(_FLORES_LOCAL_DIR, model_url.split("/")[-1]) + + try: + with open(file_path, "wb") as out_file, urllib.request.urlopen(model_url) as remote_file: + out_file.write(remote_file.read()) + except ssl.SSLError as e: + raise OSError(f"Failed to download {model_name} model.") from e + + +def sacre_bleu_score( + preds: Sequence[str], + target: Sequence[Sequence[str]], + n_gram: int = 4, + smooth: bool = False, + tokenize: _TokenizersLiteral = "13a", + lowercase: bool = False, + weights: Optional[Sequence[float]] = None, +) -> Tensor: + """Calculate `BLEU score`_ [1] of machine translated text with one or more references. + + This implementation follows the behaviour of SacreBLEU [2] implementation from https://github.com/mjpost/sacrebleu. + + .. note:: + In the original SacreBLEU, references are passed as a list of reference sets (grouped by reference index). + In TorchMetrics, references are passed grouped per prediction (each prediction has its own list of references). + + For example:: + + # Predictions + preds = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.'] + + # Original SacreBLEU: + refs = [ + ['The dog bit the man.', 'It was not unexpected.', 'The man bit him first.'], # First set + ['The dog had bit the man.', 'No one was surprised.', 'The man had bitten the dog.'], # Second set + ] + + # TorchMetrics SacreBLEU: + target = [ + ['The dog bit the man.', 'The dog had bit the man.'], # References for first prediction + ['It was not unexpected.', 'No one was surprised.'], # References for second prediction + ['The man bit him first.', 'The man had bitten the dog.'], # References for third prediction + ] + + Args: + preds: An iterable of machine translated corpus + target: An iterable of iterables of reference corpus + n_gram: Gram value ranged from 1 to 4 + smooth: Whether to apply smoothing - see [2] + tokenize: Tokenization technique to be used. Choose between ``'none'``, ``'13a'``, ``'zh'``, ``'intl'``, + ``'char'``, ``'ja-mecab'``, ``'ko-mecab'``, ``'flores101'`` and ``'flores200'``. + lowercase: If ``True``, BLEU score over lowercased text is calculated. + weights: + Weights used for unigrams, bigrams, etc. to calculate BLEU score. + If not provided, uniform weights are used. + + Return: + Tensor with BLEU Score + + Raises: + ValueError: If ``preds`` and ``target`` corpus have different lengths. + ValueError: If a length of a list of weights is not ``None`` and not equal to ``n_gram``. + + Example: + >>> from torchmetrics.functional.text import sacre_bleu_score + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> sacre_bleu_score(preds, target) + tensor(0.7598) + + References: + [1] BLEU: a Method for Automatic Evaluation of Machine Translation by Papineni, + Kishore, Salim Roukos, Todd Ward, and Wei-Jing Zhu `BLEU`_ + + [2] A Call for Clarity in Reporting BLEU Scores by Matt Post. + + [3] Automatic Evaluation of Machine Translation Quality Using Longest Common Subsequence + and Skip-Bigram Statistics by Chin-Yew Lin and Franz Josef Och `Machine Translation Evolution`_ + + """ + if len(preds) != len(target): + raise ValueError(f"Corpus has different size {len(preds)} != {len(target)}") + + if weights is not None and len(weights) != n_gram: + raise ValueError(f"List of weights has different weights than `n_gram`: {len(weights)} != {n_gram}") + if weights is None: + weights = [1.0 / n_gram] * n_gram + + numerator = torch.zeros(n_gram) + denominator = torch.zeros(n_gram) + preds_len = tensor(0.0) + target_len = tensor(0.0) + + tokenize_fn = partial(_SacreBLEUTokenizer.tokenize, tokenize=tokenize, lowercase=lowercase) + preds_len, target_len = _bleu_score_update( + preds, + target, + numerator, + denominator, + preds_len, + target_len, + n_gram, + tokenize_fn, + ) + + return _bleu_score_compute(preds_len, target_len, numerator, denominator, n_gram, weights, smooth) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/squad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/squad.py new file mode 100644 index 0000000000000000000000000000000000000000..c52f0860e140a723bf54f50fed800682df1b5def --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/squad.py @@ -0,0 +1,252 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Adapted from: +# Link: https://worksheets.codalab.org/rest/bundles/0x6b567e1cf2e041ec80d7098f031c5c9e/contents/blob/ +# Link: https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py +import re +import string +from collections import Counter +from typing import Any, Callable, Union + +from torch import Tensor, tensor + +from torchmetrics.utilities import rank_zero_warn + +SINGLE_PRED_TYPE = dict[str, str] +PREDS_TYPE = Union[SINGLE_PRED_TYPE, list[SINGLE_PRED_TYPE]] +SINGLE_TARGET_TYPE = dict[str, Union[str, dict[str, Union[list[str], list[int]]]]] +TARGETS_TYPE = Union[SINGLE_TARGET_TYPE, list[SINGLE_TARGET_TYPE]] +UPDATE_METHOD_SINGLE_PRED_TYPE = Union[list[dict[str, Union[str, int]]], str, dict[str, Union[list[str], list[int]]]] + +SQuAD_FORMAT = { + "answers": {"answer_start": [1], "text": ["This is a test text"]}, + "context": "This is a test context.", + "id": "1", + "question": "Is this a test?", + "title": "train test", +} + + +def _normalize_text(s: str) -> str: + """Lower text and remove punctuation, articles and extra whitespace.""" + + def remove_articles(text: str) -> str: + return re.sub(r"\b(a|an|the)\b", " ", text) + + def white_space_fix(text: str) -> str: + return " ".join(text.split()) + + def remove_punc(text: str) -> str: + exclude = set(string.punctuation) + return "".join(ch for ch in text if ch not in exclude) + + def lower(text: str) -> str: + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + +def _get_tokens(s: str) -> list[str]: + """Split a sentence into separate tokens.""" + return [] if not s else _normalize_text(s).split() + + +def _compute_f1_score(predicted_answer: str, target_answer: str) -> Tensor: + """Compute F1 Score for two sentences.""" + target_tokens = _get_tokens(target_answer) + predicted_tokens = _get_tokens(predicted_answer) + common = Counter(target_tokens) & Counter(predicted_tokens) + num_same = tensor(sum(common.values())) + if len(target_tokens) == 0 or len(predicted_tokens) == 0: + # If either is no-answer, then F1 is 1 if they agree, 0 otherwise + return tensor(int(target_tokens == predicted_tokens)) + if num_same == 0: + return tensor(0.0) + precision = 1.0 * num_same / tensor(len(predicted_tokens)) + recall = 1.0 * num_same / tensor(len(target_tokens)) + return (2 * precision * recall) / (precision + recall) + + +def _compute_exact_match_score(prediction: str, ground_truth: str) -> Tensor: + """Compute Exact Match for two sentences.""" + return tensor(int(_normalize_text(prediction) == _normalize_text(ground_truth))) + + +def _metric_max_over_ground_truths( + metric_fn: Callable[[str, str], Tensor], prediction: str, ground_truths: list[str] +) -> Tensor: + """Calculate maximum score for a predicted answer with all reference answers.""" + return max(metric_fn(prediction, truth) for truth in ground_truths) # type: ignore[type-var] + + +def _squad_input_check( + preds: PREDS_TYPE, targets: TARGETS_TYPE +) -> tuple[dict[str, str], list[dict[str, list[dict[str, list[dict[str, Any]]]]]]]: + """Check for types and convert the input to necessary format to compute the input.""" + if isinstance(preds, dict): + preds = [preds] + + if isinstance(targets, dict): + targets = [targets] + + for pred in preds: + pred_keys = pred.keys() + if "prediction_text" not in pred_keys or "id" not in pred_keys: + raise KeyError( + "Expected keys in a single prediction are 'prediction_text' and 'id'." + "Please make sure that 'prediction_text' maps to the answer string and 'id' maps to the key string." + ) + + for target in targets: + target_keys = target.keys() + if "answers" not in target_keys or "id" not in target_keys: + raise KeyError( + "Expected keys in a single target are 'answers' and 'id'." + "Please make sure that 'answers' maps to a `SQuAD` format dictionary and 'id' maps to the key string.\n" + "SQuAD Format: " + f"{SQuAD_FORMAT}" + ) + + answers: dict[str, Union[list[str], list[int]]] = target["answers"] # type: ignore[assignment] + if "text" not in answers: + raise KeyError( + "Expected keys in a 'answers' are 'text'." + "Please make sure that 'answer' maps to a `SQuAD` format dictionary.\n" + "SQuAD Format: " + f"{SQuAD_FORMAT}" + ) + + preds_dict = {prediction["id"]: prediction["prediction_text"] for prediction in preds} + _fn_answer = lambda tgt: {"answers": [{"text": txt} for txt in tgt["answers"]["text"]], "id": tgt["id"]} + targets_dict = [{"paragraphs": [{"qas": [_fn_answer(target) for target in targets]}]}] + return preds_dict, targets_dict + + +def _squad_update( + preds: dict[str, str], + target: list[dict[str, list[dict[str, list[dict[str, Any]]]]]], +) -> tuple[Tensor, Tensor, Tensor]: + """Compute F1 Score and Exact Match for a collection of predictions and references. + + Args: + preds: A dictionary mapping an `id` to the predicted `answer`. + target: + A list of dictionary mapping `paragraphs` to list of dictionary mapping `qas` to a list of dictionary + containing `id` and list of all possible `answers`. + + Return: + Tuple containing F1 score, Exact match score and total number of examples. + + Example: + >>> from torchmetrics.functional.text.squad import _squad_update + >>> preds = [{"prediction_text": "1976", "id": "56e10a3be3433e1400422b22"}] + >>> target = [{"answers": {"answer_start": [97], "text": ["1976"]}, "id": "56e10a3be3433e1400422b22"}] + >>> preds_dict = {pred["id"]: pred["prediction_text"] for pred in preds} + >>> targets_dict = [ + ... dict(paragraphs=[dict(qas=[dict(answers=[ + ... {"text": txt} for txt in tgt["answers"]["text"]], id=tgt["id"]) for tgt in target + ... ])]) + ... ] + >>> _squad_update(preds_dict, targets_dict) + (tensor(1.), tensor(1.), tensor(1)) + + """ + f1 = tensor(0.0) + exact_match = tensor(0.0) + total = tensor(0) + for article in target: + for paragraph in article["paragraphs"]: + for qa in paragraph["qas"]: + total += 1 + if qa["id"] not in preds: + rank_zero_warn(f"Unanswered question {qa['id']} will receive score 0.") + continue + ground_truths = [x["text"] for x in qa["answers"]] + pred = preds[qa["id"]] + exact_match += _metric_max_over_ground_truths(_compute_exact_match_score, pred, ground_truths) + f1 += _metric_max_over_ground_truths(_compute_f1_score, pred, ground_truths) + + return f1, exact_match, total + + +def _squad_compute(f1: Tensor, exact_match: Tensor, total: Tensor) -> dict[str, Tensor]: + """Aggregate the F1 Score and Exact match for the batch. + + Return: + Dictionary containing the F1 score, Exact match score for the batch. + + """ + exact_match = 100.0 * exact_match / total + f1 = 100.0 * f1 / total + return {"exact_match": exact_match, "f1": f1} + + +def squad(preds: PREDS_TYPE, target: TARGETS_TYPE) -> dict[str, Tensor]: + """Calculate `SQuAD Metric`_ . + + Args: + preds: A Dictionary or List of Dictionary-s that map `id` and `prediction_text` to the respective values. + + Example prediction: + + .. code-block:: python + + {"prediction_text": "TorchMetrics is awesome", "id": "123"} + + target: A Dictionary or List of Dictionary-s that contain the `answers` and `id` in the SQuAD Format. + + Example target: + + .. code-block:: python + + { + 'answers': [{'answer_start': [1], 'text': ['This is a test answer']}], + 'id': '1', + } + + Reference SQuAD Format: + + .. code-block:: python + + { + 'answers': {'answer_start': [1], 'text': ['This is a test text']}, + 'context': 'This is a test context.', + 'id': '1', + 'question': 'Is this a test?', + 'title': 'train test' + } + + + Return: + Dictionary containing the F1 score, Exact match score for the batch. + + Example: + >>> from torchmetrics.functional.text.squad import squad + >>> preds = [{"prediction_text": "1976", "id": "56e10a3be3433e1400422b22"}] + >>> target = [{"answers": {"answer_start": [97], "text": ["1976"]},"id": "56e10a3be3433e1400422b22"}] + >>> squad(preds, target) + {'exact_match': tensor(100.), 'f1': tensor(100.)} + + Raises: + KeyError: + If the required keys are missing in either predictions or targets. + + References: + [1] SQuAD: 100,000+ Questions for Machine Comprehension of Text by Pranav Rajpurkar, Jian Zhang, Konstantin + Lopyrev, Percy Liang `SQuAD Metric`_ . + + """ + preds_dict, target_dict = _squad_input_check(preds, target) + f1, exact_match, total = _squad_update(preds_dict, target_dict) + return _squad_compute(f1, exact_match, total) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/ter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/ter.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7a6211e0d2d40825daeca80cc425f6c960cafe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/ter.py @@ -0,0 +1,598 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# referenced from +# Library Name: torchtext +# Authors: torchtext authors +# Date: 2021-11-30 +# Link: + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# Copyright 2020 Memsource +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +from collections.abc import Iterator, Sequence +from functools import lru_cache +from typing import List, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.text.helper import ( + _flip_trace, + _LevenshteinEditDistance, + _trace_to_alignment, + _validate_inputs, +) + +# Tercom-inspired limits +_MAX_SHIFT_SIZE = 10 +_MAX_SHIFT_DIST = 50 + +# Sacrebleu-inspired limits +_MAX_SHIFT_CANDIDATES = 1000 + + +class _TercomTokenizer: + """Re-implementation of Tercom Tokenizer in Python 3. + + See src/ter/core/Normalizer.java in https://github.com/jhclark/tercom Note that Python doesn't support named Unicode + blocks so the mapping for relevant blocks was taken from here: https://unicode-table.com/en/blocks/ + + This implementation follows the implementation from + https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/tokenizers/tokenizer_ter.py. + + """ + + _ASIAN_PUNCTUATION = r"([\u3001\u3002\u3008-\u3011\u3014-\u301f\uff61-\uff65\u30fb])" + _FULL_WIDTH_PUNCTUATION = r"([\uff0e\uff0c\uff1f\uff1a\uff1b\uff01\uff02\uff08\uff09])" + + def __init__( + self, + normalize: bool = False, + no_punctuation: bool = False, + lowercase: bool = True, + asian_support: bool = False, + ) -> None: + """Initialize the tokenizer. + + Args: + normalize: An indication whether a general tokenization to be applied. + no_punctuation: An indication whteher a punctuation to be removed from the sentences. + lowercase: An indication whether to enable case-insensitivity. + asian_support: An indication whether asian characters to be processed. + + """ + self.normalize = normalize + self.no_punctuation = no_punctuation + self.lowercase = lowercase + self.asian_support = asian_support + + @lru_cache(maxsize=2**16) # noqa: B019 + def __call__(self, sentence: str) -> str: + """Apply a different tokenization techniques according. + + Args: + sentence: An input sentence to pre-process and tokenize. + + Return: + A tokenized and pre-processed sentence. + + """ + if not sentence: + return "" + + if self.lowercase: + sentence = sentence.lower() + + if self.normalize: + sentence = self._normalize_general_and_western(sentence) + if self.asian_support: + sentence = self._normalize_asian(sentence) + + if self.no_punctuation: + sentence = self._remove_punct(sentence) + if self.asian_support: + sentence = self._remove_asian_punct(sentence) + + # Strip extra whitespaces + return " ".join(sentence.split()) + + @staticmethod + def _normalize_general_and_western(sentence: str) -> str: + """Apply a language-independent (general) tokenization.""" + sentence = f" {sentence} " + rules = [ + (r"\n-", ""), + # join lines + (r"\n", " "), + # handle XML escaped symbols + (r""", '"'), + (r"&", "&"), + (r"<", "<"), + (r">", ">"), + # tokenize punctuation + (r"([{-~[-` -&(-+:-@/])", r" \1 "), + # handle possessive + (r"'s ", r" 's "), + (r"'s$", r" 's"), + # tokenize period and comma unless preceded by a digit + (r"([^0-9])([\.,])", r"\1 \2 "), + # tokenize period and comma unless followed by a digit + (r"([\.,])([^0-9])", r" \1 \2"), + # tokenize dash when preceded by a digit + (r"([0-9])(-)", r"\1 \2 "), + ] + for pattern, replacement in rules: + sentence = re.sub(pattern, replacement, sentence) + + return sentence + + @classmethod + def _normalize_asian(cls: type["_TercomTokenizer"], sentence: str) -> str: + """Split Chinese chars and Japanese kanji down to character level.""" + # 4E00—9FFF CJK Unified Ideographs + # 3400—4DBF CJK Unified Ideographs Extension A + sentence = re.sub(r"([\u4e00-\u9fff\u3400-\u4dbf])", r" \1 ", sentence) + # 31C0—31EF CJK Strokes + # 2E80—2EFF CJK Radicals Supplement + sentence = re.sub(r"([\u31c0-\u31ef\u2e80-\u2eff])", r" \1 ", sentence) + # 3300—33FF CJK Compatibility + # F900—FAFF CJK Compatibility Ideographs + # FE30—FE4F CJK Compatibility Forms + sentence = re.sub(r"([\u3300-\u33ff\uf900-\ufaff\ufe30-\ufe4f])", r" \1 ", sentence) + # 3200—32FF Enclosed CJK Letters and Months + sentence = re.sub(r"([\u3200-\u3f22])", r" \1 ", sentence) + # Split Hiragana, Katakana, and KatakanaPhoneticExtensions + # only when adjacent to something else + # 3040—309F Hiragana + # 30A0—30FF Katakana + # 31F0—31FF Katakana Phonetic Extensions + sentence = re.sub(r"(^|^[\u3040-\u309f])([\u3040-\u309f]+)(?=$|^[\u3040-\u309f])", r"\1 \2 ", sentence) + sentence = re.sub(r"(^|^[\u30a0-\u30ff])([\u30a0-\u30ff]+)(?=$|^[\u30a0-\u30ff])", r"\1 \2 ", sentence) + sentence = re.sub(r"(^|^[\u31f0-\u31ff])([\u31f0-\u31ff]+)(?=$|^[\u31f0-\u31ff])", r"\1 \2 ", sentence) + + sentence = re.sub(cls._ASIAN_PUNCTUATION, r" \1 ", sentence) + return re.sub(cls._FULL_WIDTH_PUNCTUATION, r" \1 ", sentence) + + @staticmethod + def _remove_punct(sentence: str) -> str: + """Remove punctuation from an input sentence string.""" + return re.sub(r"[\.,\?:;!\"\(\)]", "", sentence) + + @classmethod + def _remove_asian_punct(cls: type["_TercomTokenizer"], sentence: str) -> str: + """Remove asian punctuation from an input sentence string.""" + sentence = re.sub(cls._ASIAN_PUNCTUATION, r"", sentence) + return re.sub(cls._FULL_WIDTH_PUNCTUATION, r"", sentence) + + +def _preprocess_sentence(sentence: str, tokenizer: _TercomTokenizer) -> str: + """Given a sentence, apply tokenization. + + Args: + sentence: The input sentence string. + tokenizer: An instance of ``_TercomTokenizer`` handling a sentence tokenization. + + Return: + The pre-processed output sentence string. + + """ + return tokenizer(sentence.rstrip()) + + +def _find_shifted_pairs(pred_words: list[str], target_words: list[str]) -> Iterator[tuple[int, int, int]]: + """Find matching word sub-sequences in two lists of words. Ignores sub- sequences starting at the same position. + + Args: + pred_words: A list of a tokenized hypothesis sentence. + target_words: A list of a tokenized reference sentence. + + Return: + Yields tuples of ``target_start, pred_start, length`` such that: + ``target_words[target_start : target_start + length] == pred_words[pred_start : pred_start + length]`` + + pred_start: + A list of hypothesis start indices. + target_start: + A list of reference start indices. + length: + A length of a word span to be considered. + + """ + for pred_start in range(len(pred_words)): + for target_start in range(len(target_words)): + # this is slightly different from what tercom does but this should + # really only kick in in degenerate cases + if abs(target_start - pred_start) > _MAX_SHIFT_DIST: + continue + + for length in range(1, _MAX_SHIFT_SIZE): + # Check if hypothesis and reference are equal so far + if pred_words[pred_start + length - 1] != target_words[target_start + length - 1]: + break + yield pred_start, target_start, length + + # Stop processing once a sequence is consumed. + _hyp = len(pred_words) == pred_start + length + _ref = len(target_words) == target_start + length + if _hyp or _ref: + break + + +def _handle_corner_cases_during_shifting( + alignments: dict[int, int], + pred_errors: list[int], + target_errors: list[int], + pred_start: int, + target_start: int, + length: int, +) -> bool: + """Return ``True`` if any of corner cases has been met. Otherwise, ``False`` is returned. + + Args: + alignments: A dictionary mapping aligned positions between a reference and a hypothesis. + pred_errors: A list of error positions in a hypothesis. + target_errors: A list of error positions in a reference. + pred_start: A hypothesis start index. + target_start: A reference start index. + length: A length of a word span to be considered. + + Return: + An indication whether any of conrner cases has been met. + + """ + # don't do the shift unless both the hypothesis was wrong and the + # reference doesn't match hypothesis at the target position + if sum(pred_errors[pred_start : pred_start + length]) == 0: + return True + + if sum(target_errors[target_start : target_start + length]) == 0: + return True + + # don't try to shift within the subsequence + return pred_start <= alignments[target_start] < pred_start + length + + +def _perform_shift(words: list[str], start: int, length: int, target: int) -> list[str]: + """Perform a shift in ``words`` from ``start`` to ``target``. + + Args: + words: A words to shift. + start: An index where to start shifting from. + length: A number of how many words to be considered. + target: An index where to end shifting. + + Return: + A list of shifted words. + + """ + + def _shift_word_before_previous_position(words: list[str], start: int, target: int, length: int) -> list[str]: + return words[:target] + words[start : start + length] + words[target:start] + words[start + length :] + + def _shift_word_after_previous_position(words: list[str], start: int, target: int, length: int) -> list[str]: + return words[:start] + words[start + length : target] + words[start : start + length] + words[target:] + + def _shift_word_within_shifted_string(words: list[str], start: int, target: int, length: int) -> list[str]: + shifted_words = words[:start] + shifted_words += words[start + length : length + target] + shifted_words += words[start : start + length] + shifted_words += words[length + target :] + return shifted_words + + if target < start: + return _shift_word_before_previous_position(words, start, target, length) + if target > start + length: + return _shift_word_after_previous_position(words, start, target, length) + return _shift_word_within_shifted_string(words, start, target, length) + + +def _shift_words( + pred_words: list[str], + target_words: list[str], + cached_edit_distance: _LevenshteinEditDistance, + checked_candidates: int, +) -> tuple[int, list[str], int]: + """Attempt to shift words to match a hypothesis with a reference. + + It returns the lowest number of required edits between a hypothesis and a provided reference, a list of shifted + words and number of checked candidates. Note that the filtering of possible shifts and shift selection are heavily + based on somewhat arbitrary heuristics. The code here follows as closely as possible the logic in Tercom, not + always justifying the particular design choices. + The paragraph copied from https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/lib_ter.py. + + Args: + pred_words: A list of tokenized hypothesis sentence. + target_words: A list of lists of tokenized reference sentences. + cached_edit_distance: A pre-computed edit distance between a hypothesis and a reference. + checked_candidates: A number of checked hypothesis candidates to match a provided reference. + + Return: + best_score: + The best (lowest) number of required edits to match hypothesis and reference sentences. + shifted_words: + A list of shifted words in hypothesis sentences. + checked_candidates: + A number of checked hypothesis candidates to match a provided reference. + + """ + edit_distance, inverted_trace = cached_edit_distance(pred_words) + trace = _flip_trace(inverted_trace) + alignments, target_errors, pred_errors = _trace_to_alignment(trace) + + best: Optional[tuple[int, int, int, int, list[str]]] = None + + for pred_start, target_start, length in _find_shifted_pairs(pred_words, target_words): + if _handle_corner_cases_during_shifting( + alignments, pred_errors, target_errors, pred_start, target_start, length + ): + continue + + prev_idx = -1 + for offset in range(-1, length): + if target_start + offset == -1: + idx = 0 + elif target_start + offset in alignments: + idx = alignments[target_start + offset] + 1 + # offset is out of bounds => aims past reference + else: + break + # Skip idx if already tried + if idx == prev_idx: + continue + + prev_idx = idx + + shifted_words = _perform_shift(pred_words, pred_start, length, idx) + + # Elements of the tuple are designed to replicate Tercom ranking of shifts: + candidate = ( + edit_distance - cached_edit_distance(shifted_words)[0], # highest score first + length, # then, longest match first + -pred_start, # then, earliest match first + -idx, # then, earliest target position first + shifted_words, + ) + + checked_candidates += 1 + + if not best or candidate > best: + best = candidate + + if checked_candidates >= _MAX_SHIFT_CANDIDATES: + break + + if not best: + return 0, pred_words, checked_candidates + best_score, _, _, _, shifted_words = best + return best_score, shifted_words, checked_candidates + + +def _translation_edit_rate(pred_words: list[str], target_words: list[str]) -> Tensor: + """Compute translation edit rate between hypothesis and reference sentences. + + Args: + pred_words: A list of a tokenized hypothesis sentence. + target_words: A list of lists of tokenized reference sentences. + + Return: + A number of required edits to match hypothesis and reference sentences. + + """ + if len(target_words) == 0: + return tensor(0.0) + + cached_edit_distance = _LevenshteinEditDistance(target_words) + num_shifts = 0 + checked_candidates = 0 + input_words = pred_words + + while True: + # do shifts until they stop reducing the edit distance + delta, new_input_words, checked_candidates = _shift_words( + input_words, target_words, cached_edit_distance, checked_candidates + ) + if checked_candidates >= _MAX_SHIFT_CANDIDATES or delta <= 0: + break + num_shifts += 1 + input_words = new_input_words + + edit_distance, _ = cached_edit_distance(input_words) + total_edits = num_shifts + edit_distance + + return tensor(total_edits) + + +def _compute_sentence_statistics(pred_words: list[str], target_words: list[list[str]]) -> tuple[Tensor, Tensor]: + """Compute sentence TER statistics between hypothesis and provided references. + + Args: + pred_words: A list of tokenized hypothesis sentence. + target_words: A list of lists of tokenized reference sentences. + + Return: + best_num_edits: + The best (lowest) number of required edits to match hypothesis and reference sentences. + avg_tgt_len: + Average length of tokenized reference sentences. + + """ + tgt_lengths = tensor(0.0) + best_num_edits = tensor(2e16) + + for tgt_words in target_words: + num_edits = _translation_edit_rate(tgt_words, pred_words) + tgt_lengths += len(tgt_words) + if num_edits < best_num_edits: + best_num_edits = num_edits + + avg_tgt_len = tgt_lengths / len(target_words) + return best_num_edits, avg_tgt_len + + +def _compute_ter_score_from_statistics(num_edits: Tensor, tgt_length: Tensor) -> Tensor: + """Compute TER score based on pre-computed a number of edits and an average reference length. + + Args: + num_edits: A number of required edits to match hypothesis and reference sentences. + tgt_length: An average length of reference sentences. + + Return: + A corpus-level TER score or 1 if reference_length == 0. + + """ + if tgt_length > 0 and num_edits > 0: + return num_edits / tgt_length + if tgt_length == 0 and num_edits > 0: + return tensor(1.0) + return tensor(0.0) + + +def _ter_update( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + tokenizer: _TercomTokenizer, + total_num_edits: Tensor, + total_tgt_length: Tensor, + sentence_ter: Optional[List[Tensor]] = None, +) -> tuple[Tensor, Tensor, Optional[List[Tensor]]]: + """Update TER statistics. + + Args: + preds: An iterable of hypothesis corpus. + target: An iterable of iterables of reference corpus. + tokenizer: An instance of ``_TercomTokenizer`` handling a sentence tokenization. + total_num_edits: A total number of required edits to match hypothesis and reference sentences. + total_tgt_length: A total average length of reference sentences. + sentence_ter: A list of sentence-level TER values + + Return: + total_num_edits: + A total number of required edits to match hypothesis and reference sentences. + total_tgt_length: + A total average length of reference sentences. + sentence_ter: + (Optionally) A list of sentence-level TER. + + Raises: + ValueError: + If length of ``preds`` and ``target`` differs. + + """ + target, preds = _validate_inputs(target, preds) + + for pred, tgt in zip(preds, target): + tgt_words_: list[list[str]] = [_preprocess_sentence(_tgt, tokenizer).split() for _tgt in tgt] + pred_words_: list[str] = _preprocess_sentence(pred, tokenizer).split() + num_edits, tgt_length = _compute_sentence_statistics(pred_words_, tgt_words_) + total_num_edits += num_edits + total_tgt_length += tgt_length + if sentence_ter is not None: + sentence_ter.append(_compute_ter_score_from_statistics(num_edits, tgt_length).unsqueeze(0)) + return total_num_edits, total_tgt_length, sentence_ter + + +def _ter_compute(total_num_edits: Tensor, total_tgt_length: Tensor) -> Tensor: + """Compute TER based on pre-computed a total number of edits and a total average reference length. + + Args: + total_num_edits: A total number of required edits to match hypothesis and reference sentences. + total_tgt_length: A total average length of reference sentences. + + Return: + A corpus-level TER score. + + """ + return _compute_ter_score_from_statistics(total_num_edits, total_tgt_length) + + +def translation_edit_rate( + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + normalize: bool = False, + no_punctuation: bool = False, + lowercase: bool = True, + asian_support: bool = False, + return_sentence_level_score: bool = False, +) -> Union[Tensor, tuple[Tensor, List[Tensor]]]: + """Calculate Translation edit rate (`TER`_) of machine translated text with one or more references. + + This implementation follows the implementations from + https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/ter.py. The `sacrebleu` implementation is a + near-exact reimplementation of the Tercom algorithm, produces identical results on all "sane" outputs. + + Args: + preds: An iterable of hypothesis corpus. + target: An iterable of iterables of reference corpus. + normalize: An indication whether a general tokenization to be applied. + no_punctuation: An indication whteher a punctuation to be removed from the sentences. + lowercase: An indication whether to enable case-insensitivity. + asian_support: An indication whether asian characters to be processed. + return_sentence_level_score: An indication whether a sentence-level TER to be returned. + + Return: + A corpus-level translation edit rate (TER). + (Optionally) A list of sentence-level translation_edit_rate (TER) if `return_sentence_level_score=True`. + + Example: + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> translation_edit_rate(preds, target) + tensor(0.1538) + + References: + [1] A Study of Translation Edit Rate with Targeted Human Annotation + by Mathew Snover, Bonnie Dorr, Richard Schwartz, Linnea Micciulla and John Makhoul `TER`_ + + """ + if not isinstance(normalize, bool): + raise ValueError(f"Expected argument `normalize` to be of type boolean but got {normalize}.") + if not isinstance(no_punctuation, bool): + raise ValueError(f"Expected argument `no_punctuation` to be of type boolean but got {no_punctuation}.") + if not isinstance(lowercase, bool): + raise ValueError(f"Expected argument `lowercase` to be of type boolean but got {lowercase}.") + if not isinstance(asian_support, bool): + raise ValueError(f"Expected argument `asian_support` to be of type boolean but got {asian_support}.") + + tokenizer: _TercomTokenizer = _TercomTokenizer(normalize, no_punctuation, lowercase, asian_support) + + total_num_edits = tensor(0.0) + total_tgt_length = tensor(0.0) + sentence_ter: Optional[List[Tensor]] = [] if return_sentence_level_score else None + + total_num_edits, total_tgt_length, sentence_ter = _ter_update( + preds, + target, + tokenizer, + total_num_edits, + total_tgt_length, + sentence_ter, + ) + ter_score = _ter_compute(total_num_edits, total_tgt_length) + + if sentence_ter: + return ter_score, sentence_ter + return ter_score diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wer.py new file mode 100644 index 0000000000000000000000000000000000000000..b61bdb4c10536a2b1ff7f66b6493181ffc8fc47f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wer.py @@ -0,0 +1,87 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.helper import _edit_distance + + +def _wer_update( + preds: Union[str, list[str]], + target: Union[str, list[str]], +) -> tuple[Tensor, Tensor]: + """Update the wer score with the current set of references and predictions. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Number of edit operations to get from the reference to the prediction, summed over all samples + Number of words overall references + + """ + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + errors = tensor(0, dtype=torch.float) + total = tensor(0, dtype=torch.float) + for pred, tgt in zip(preds, target): + pred_tokens = pred.split() + tgt_tokens = tgt.split() + errors += _edit_distance(pred_tokens, tgt_tokens) + total += len(tgt_tokens) + return errors, total + + +def _wer_compute(errors: Tensor, total: Tensor) -> Tensor: + """Compute the word error rate. + + Args: + errors: Number of edit operations to get from the reference to the prediction, summed over all samples + total: Number of words overall references + + Returns: + Word error rate score + + """ + return errors / total + + +def word_error_rate(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Word error rate (WordErrorRate_) is a common metric of performance of an automatic speech recognition system. + + This value indicates the percentage of words that were incorrectly predicted. The lower the value, the better the + performance of the ASR system with a WER of 0 being a perfect score. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Word error rate score + + Examples: + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> word_error_rate(preds=preds, target=target) + tensor(0.5000) + + """ + errors, total = _wer_update(preds, target) + return _wer_compute(errors, total) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wil.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wil.py new file mode 100644 index 0000000000000000000000000000000000000000..3d8c370facb09d0c9b04661255882eee77d0eebd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wil.py @@ -0,0 +1,94 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +from torch import Tensor, tensor + +from torchmetrics.functional.text.helper import _edit_distance + + +def _word_info_lost_update( + preds: Union[str, list[str]], + target: Union[str, list[str]], +) -> tuple[Tensor, Tensor, Tensor]: + """Update the WIL score with the current set of references and predictions. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Number of edit operations to get from the reference to the prediction, summed over all samples + Number of words overall references + Number of words overall predictions + + """ + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + total = tensor(0.0) + errors = tensor(0.0) + target_total = tensor(0.0) + preds_total = tensor(0.0) + for pred, tgt in zip(preds, target): + pred_tokens = pred.split() + target_tokens = tgt.split() + errors += _edit_distance(pred_tokens, target_tokens) + target_total += len(target_tokens) + preds_total += len(pred_tokens) + total += max(len(target_tokens), len(pred_tokens)) + + return errors - total, target_total, preds_total + + +def _word_info_lost_compute(errors: Tensor, target_total: Tensor, preds_total: Tensor) -> Tensor: + """Compute the Word Information Lost. + + Args: + errors: Number of edit operations to get from the reference to the prediction, summed over all samples + target_total: Number of words overall references + preds_total: Number of words overall prediction + + Returns: + Word Information Lost score + + """ + return 1 - ((errors / target_total) * (errors / preds_total)) + + +def word_information_lost(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Word Information Lost rate is a metric of the performance of an automatic speech recognition system. + + This value indicates the percentage of characters that were incorrectly predicted. The lower the value, the better + the performance of the ASR system with a Word Information Lost rate of 0 being a perfect score. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Word Information Lost rate + + Examples: + >>> from torchmetrics.functional.text import word_information_lost + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> word_information_lost(preds, target) + tensor(0.6528) + + """ + errors, target_total, preds_total = _word_info_lost_update(preds, target) + return _word_info_lost_compute(errors, target_total, preds_total) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wip.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wip.py new file mode 100644 index 0000000000000000000000000000000000000000..77dae42e5ed1daa857ab5eaf0fa43f9058d1a6d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/text/wip.py @@ -0,0 +1,93 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +from torch import Tensor, tensor + +from torchmetrics.functional.text.helper import _edit_distance + + +def _wip_update( + preds: Union[str, list[str]], + target: Union[str, list[str]], +) -> tuple[Tensor, Tensor, Tensor]: + """Update the wip score with the current set of references and predictions. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Number of edit operations to get from the reference to the prediction, summed over all samples + Number of words overall references + Number of words overall prediction + + """ + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + total = tensor(0.0) + errors = tensor(0.0) + target_total = tensor(0.0) + preds_total = tensor(0.0) + for pred, tgt in zip(preds, target): + pred_tokens = pred.split() + target_tokens = tgt.split() + errors += _edit_distance(pred_tokens, target_tokens) + target_total += len(target_tokens) + preds_total += len(pred_tokens) + total += max(len(target_tokens), len(pred_tokens)) + + return errors - total, target_total, preds_total + + +def _wip_compute(errors: Tensor, target_total: Tensor, preds_total: Tensor) -> Tensor: + """Compute the Word Information Preserved. + + Args: + errors: Number of edit operations to get from the reference to the prediction, summed over all samples + target_total: Number of words overall references + preds_total: Number of words overall prediction + + Returns: + Word Information Preserved score + + """ + return (errors / target_total) * (errors / preds_total) + + +def word_information_preserved(preds: Union[str, list[str]], target: Union[str, list[str]]) -> Tensor: + """Word Information Preserved rate is a metric of the performance of an automatic speech recognition system. + + This value indicates the percentage of characters that were incorrectly predicted. The lower the value, the + better the performance of the ASR system with a Word Information preserved rate of 0 being a perfect score. + + Args: + preds: Transcription(s) to score as a string or list of strings + target: Reference(s) for each speech input as a string or list of strings + + Returns: + Word Information preserved rate + + Examples: + >>> from torchmetrics.functional.text import word_information_preserved + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> word_information_preserved(preds, target) + tensor(0.3472) + + """ + errors, reference_total, prediction_total = _wip_update(preds, target) + return _wip_compute(errors, reference_total, prediction_total) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/video/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc86ba0e06d1ead2b635c41565b00eada54a0aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/video/__init__.py @@ -0,0 +1,21 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.utilities.imports import _TORCH_VMAF_AVAILABLE + +__all__ = [] + +if _TORCH_VMAF_AVAILABLE: + from torchmetrics.functional.video.vmaf import video_multi_method_assessment_fusion + + __all__ += ["video_multi_method_assessment_fusion"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/video/vmaf.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/video/vmaf.py new file mode 100644 index 0000000000000000000000000000000000000000..c82ad760b658445c3f41d9283a71d8a0bee97b43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/video/vmaf.py @@ -0,0 +1,142 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Dict, Union + +import torch +from torch import Tensor + +from torchmetrics.utilities.imports import _EINOPS_AVAILABLE, _TORCH_VMAF_AVAILABLE + +if _TORCH_VMAF_AVAILABLE: + import pandas as pd # pandas is installed as a dependency of vmaf-torch + from vmaf_torch import VMAF +else: + __doctest_skip__ = ["video_multi_method_assessment_fusion"] + +if _EINOPS_AVAILABLE: + from einops import rearrange + + +def calculate_luma(video: Tensor) -> Tensor: + """Calculate the luma component of a video tensor.""" + r = video[:, 0, :, :, :] + g = video[:, 1, :, :, :] + b = video[:, 2, :, :, :] + return (0.299 * r + 0.587 * g + 0.114 * b).unsqueeze(1) * 255 # [0, 1] -> [0, 255] + + +def video_multi_method_assessment_fusion( + preds: Tensor, + target: Tensor, + features: bool = False, +) -> Union[Tensor, Dict[str, Tensor]]: + """Calculates Video Multi-Method Assessment Fusion (VMAF) metric. + + VMAF is a full-reference video quality assessment algorithm that combines multiple quality assessment features + such as detail loss, motion, and contrast using a machine learning model to predict human perception of video + quality more accurately than traditional metrics like PSNR or SSIM. + + The metric works by: + + 1. Converting input videos to luma component (grayscale) + 2. Computing multiple elementary features: + - Additive Detail Measure (ADM): Evaluates detail preservation at different scales + - Visual Information Fidelity (VIF): Measures preservation of visual information across frequency bands + - Motion: Quantifies the amount of motion in the video + 3. Combining these features using a trained SVM model to predict quality + + .. note:: + This implementation requires you to have vmaf-torch installed: https://github.com/alvitrioliks/VMAF-torch. + Install either by cloning the repository and running `pip install .` or with `pip install torchmetrics[video]`. + + Args: + preds: Video tensor of shape (batch, channels, frames, height, width). Expected to be in RGB format + with values in range [0, 1]. + target: Video tensor of shape (batch, channels, frames, height, width). Expected to be in RGB format + with values in range [0, 1]. + features: If True, all the elementary features (ADM, VIF, motion) are returned along with the VMAF score in + a dictionary. This corresponds to the output you would get from the VMAF command line tool with the `--csv` + option enabled. If False, only the VMAF score is returned as a tensor. + + Returns: + - If `features` is False, returns a tensor with shape (batch, frame) of VMAF score for each frame in + each video. Higher scores indicate better quality, with typical values ranging from 0 to 100. + + - If `features` is True, returns a dictionary where each value is a (batch, frame) tensor of the + corresponding feature. The keys are: + + - 'integer_motion2': Integer motion feature + - 'integer_motion': Integer motion feature + - 'integer_adm2': Integer ADM feature + - 'integer_adm_scale0': Integer ADM feature at scale 0 + - 'integer_adm_scale1': Integer ADM feature at scale 1 + - 'integer_adm_scale2': Integer ADM feature at scale 2 + - 'integer_adm_scale3': Integer ADM feature at scale 3 + - 'integer_vif_scale0': Integer VIF feature at scale 0 + - 'integer_vif_scale1': Integer VIF feature at scale 1 + - 'integer_vif_scale2': Integer VIF feature at scale 2 + - 'integer_vif_scale3': Integer VIF feature at scale 3 + - 'vmaf': VMAF score for each frame in each video + + Example: + >>> import torch + >>> from torchmetrics.functional.video import video_multi_method_assessment_fusion + >>> # 2 videos, 3 channels, 10 frames, 32x32 resolution + >>> preds = torch.rand(2, 3, 10, 32, 32, generator=torch.manual_seed(42)) + >>> target = torch.rand(2, 3, 10, 32, 32, generator=torch.manual_seed(43)) + >>> vmaf_score = video_multi_method_assessment_fusion(preds, target) + >>> torch.round(vmaf_score, decimals=2) + tensor([[ 9.9900, 15.9000, 14.2600, 16.6100, 15.9100, 14.3000, 13.5800, 13.4900, 15.4700, 20.2800], + [ 6.2500, 11.3000, 17.3000, 11.4600, 19.0600, 14.9300, 14.0500, 14.4100, 12.4700, 14.8200]]) + >>> vmaf_dict = video_multi_method_assessment_fusion(preds, target, features=True) + >>> # show a couple of features, more features are available + >>> vmaf_dict['vmaf'].round(decimals=2) + tensor([[ 9.9900, 15.9000, 14.2600, 16.6100, 15.9100, 14.3000, 13.5800, 13.4900, 15.4700, 20.2800], + [ 6.2500, 11.3000, 17.3000, 11.4600, 19.0600, 14.9300, 14.0500, 14.4100, 12.4700, 14.8200]]) + >>> vmaf_dict['integer_adm2'].round(decimals=2) + tensor([[0.4500, 0.4500, 0.3600, 0.4700, 0.4300, 0.3600, 0.3900, 0.4100, 0.3700, 0.4700], + [0.4200, 0.3900, 0.4400, 0.3700, 0.4500, 0.3900, 0.3800, 0.4800, 0.3900, 0.3900]]) + + """ + if not _TORCH_VMAF_AVAILABLE: + raise RuntimeError("vmaf-torch is not installed. Please install with `pip install torchmetrics[video]`.") + b = preds.shape[0] + orig_dtype, device = preds.dtype, preds.device + preds_luma = calculate_luma(preds) + target_luma = calculate_luma(target) + + vmaf = VMAF().to(device) + + # we need to compute the model for each video separately + if not features: + scores = [ + vmaf.compute_vmaf_score( + rearrange(target_luma[video], "c f h w -> f c h w"), rearrange(preds_luma[video], "c f h w -> f c h w") + ) + for video in range(b) + ] + return torch.cat(scores, dim=1).t().to(orig_dtype) + + scores_and_features = [ + vmaf.table( + rearrange(target_luma[video], "c f h w -> f c h w"), rearrange(preds_luma[video], "c f h w -> f c h w") + ) + for video in range(b) + ] + dfs = [scores_and_features[video].apply(pd.to_numeric, errors="coerce") for video in range(b)] + result = [ + {col: torch.tensor(dfs[video][col].values, dtype=orig_dtype) for col in dfs[video].columns if col != "Frame"} + for video in range(b) + ] + return {col: torch.stack([result[video][col] for video in range(b)]) for col in result[0]} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..997e7791d3338a63520a30f74cd340abfe749648 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/__init__.py @@ -0,0 +1,70 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.image.d_lambda import SpectralDistortionIndex +from torchmetrics.image.d_s import SpatialDistortionIndex +from torchmetrics.image.dists import DeepImageStructureAndTextureSimilarity +from torchmetrics.image.ergas import ErrorRelativeGlobalDimensionlessSynthesis +from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance +from torchmetrics.image.psnr import PeakSignalNoiseRatio +from torchmetrics.image.psnrb import PeakSignalNoiseRatioWithBlockedEffect +from torchmetrics.image.qnr import QualityWithNoReference +from torchmetrics.image.rase import RelativeAverageSpectralError +from torchmetrics.image.rmse_sw import RootMeanSquaredErrorUsingSlidingWindow +from torchmetrics.image.sam import SpectralAngleMapper +from torchmetrics.image.scc import SpatialCorrelationCoefficient +from torchmetrics.image.ssim import MultiScaleStructuralSimilarityIndexMeasure, StructuralSimilarityIndexMeasure +from torchmetrics.image.tv import TotalVariation +from torchmetrics.image.uqi import UniversalImageQualityIndex +from torchmetrics.image.vif import VisualInformationFidelity +from torchmetrics.utilities.imports import ( + _TORCH_FIDELITY_AVAILABLE, + _TORCHVISION_AVAILABLE, +) + +__all__ = [ + "DeepImageStructureAndTextureSimilarity", + "ErrorRelativeGlobalDimensionlessSynthesis", + "MemorizationInformedFrechetInceptionDistance", + "MultiScaleStructuralSimilarityIndexMeasure", + "PeakSignalNoiseRatio", + "PeakSignalNoiseRatioWithBlockedEffect", + "QualityWithNoReference", + "RelativeAverageSpectralError", + "RootMeanSquaredErrorUsingSlidingWindow", + "SpatialCorrelationCoefficient", + "SpatialDistortionIndex", + "SpectralAngleMapper", + "SpectralDistortionIndex", + "StructuralSimilarityIndexMeasure", + "TotalVariation", + "UniversalImageQualityIndex", + "VisualInformationFidelity", +] + +if _TORCH_FIDELITY_AVAILABLE: + from torchmetrics.image.fid import FrechetInceptionDistance + from torchmetrics.image.inception import InceptionScore + from torchmetrics.image.kid import KernelInceptionDistance + + __all__ += [ + "FrechetInceptionDistance", + "InceptionScore", + "KernelInceptionDistance", + ] + +if _TORCHVISION_AVAILABLE: + from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity + from torchmetrics.image.perceptual_path_length import PerceptualPathLength + + __all__ += ["LearnedPerceptualImagePatchSimilarity", "PerceptualPathLength"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/_deprecated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..8baeda78ab511c4f780bee53c32bca9cf3a91c93 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/_deprecated.py @@ -0,0 +1,262 @@ +from collections.abc import Sequence +from typing import Any, Optional, Union + +from typing_extensions import Literal + +from torchmetrics.image.d_lambda import SpectralDistortionIndex +from torchmetrics.image.ergas import ErrorRelativeGlobalDimensionlessSynthesis +from torchmetrics.image.psnr import PeakSignalNoiseRatio +from torchmetrics.image.rase import RelativeAverageSpectralError +from torchmetrics.image.rmse_sw import RootMeanSquaredErrorUsingSlidingWindow +from torchmetrics.image.sam import SpectralAngleMapper +from torchmetrics.image.ssim import MultiScaleStructuralSimilarityIndexMeasure, StructuralSimilarityIndexMeasure +from torchmetrics.image.tv import TotalVariation +from torchmetrics.image.uqi import UniversalImageQualityIndex +from torchmetrics.utilities.prints import _deprecated_root_import_class + + +class _ErrorRelativeGlobalDimensionlessSynthesis(ErrorRelativeGlobalDimensionlessSynthesis): + """Wrapper for deprecated import. + + >>> from torch import rand + >>> preds = rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> ergas = _ErrorRelativeGlobalDimensionlessSynthesis() + >>> ergas(preds, target).round() + tensor(10.) + + """ + + def __init__( + self, + ratio: float = 4, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("ErrorRelativeGlobalDimensionlessSynthesis", "image") + super().__init__(ratio=ratio, reduction=reduction, **kwargs) + + +class _MultiScaleStructuralSimilarityIndexMeasure(MultiScaleStructuralSimilarityIndexMeasure): + """Wrapper for deprecated import. + + >>> from torch import rand + >>> preds = rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> ms_ssim = _MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0) + >>> ms_ssim(preds, target) + tensor(0.9628) + + """ + + def __init__( + self, + gaussian_kernel: bool = True, + kernel_size: Union[int, Sequence[int]] = 11, + sigma: Union[float, Sequence[float]] = 1.5, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + betas: tuple[float, ...] = (0.0448, 0.2856, 0.3001, 0.2363, 0.1333), + normalize: Literal["relu", "simple", None] = "relu", + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("MultiScaleStructuralSimilarityIndexMeasure", "image") + super().__init__( + gaussian_kernel=gaussian_kernel, + kernel_size=kernel_size, + sigma=sigma, + reduction=reduction, + data_range=data_range, + k1=k1, + k2=k2, + betas=betas, + normalize=normalize, + **kwargs, + ) + + +class _PeakSignalNoiseRatio(PeakSignalNoiseRatio): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> psnr = _PeakSignalNoiseRatio() + >>> preds = tensor([[0.0, 1.0], [2.0, 3.0]]) + >>> target = tensor([[3.0, 2.0], [1.0, 0.0]]) + >>> psnr(preds, target) + tensor(2.5527) + + """ + + def __init__( + self, + data_range: Union[float, tuple[float, float]] = 3.0, + base: float = 10.0, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + dim: Optional[Union[int, tuple[int, ...]]] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("PeakSignalNoiseRatio", "image") + super().__init__(data_range=data_range, base=base, reduction=reduction, dim=dim, **kwargs) + + +class _RelativeAverageSpectralError(RelativeAverageSpectralError): + """Wrapper for deprecated import. + + >>> from torch import rand + >>> preds = rand(4, 3, 16, 16) + >>> target = rand(4, 3, 16, 16) + >>> rase = _RelativeAverageSpectralError() + >>> rase(preds, target) + tensor(5326.40...) + + """ + + def __init__( + self, + window_size: int = 8, + **kwargs: dict[str, Any], + ) -> None: + _deprecated_root_import_class("RelativeAverageSpectralError", "image") + super().__init__(window_size=window_size, **kwargs) + + +class _RootMeanSquaredErrorUsingSlidingWindow(RootMeanSquaredErrorUsingSlidingWindow): + """Wrapper for deprecated import. + + >>> from torch import rand + >>> preds = rand(4, 3, 16, 16) + >>> target = rand(4, 3, 16, 16) + >>> rmse_sw = RootMeanSquaredErrorUsingSlidingWindow() + >>> rmse_sw(preds, target) + tensor(0.4158) + + """ + + def __init__( + self, + window_size: int = 8, + **kwargs: dict[str, Any], + ) -> None: + _deprecated_root_import_class("RootMeanSquaredErrorUsingSlidingWindow", "image") + super().__init__(window_size=window_size, **kwargs) + + +class _SpectralAngleMapper(SpectralAngleMapper): + """Wrapper for deprecated import. + + >>> from torch import rand + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> sam = _SpectralAngleMapper() + >>> sam(preds, target) + tensor(0.5914) + + """ + + def __init__( + self, + reduction: Literal["elementwise_mean", "sum", "none"] = "elementwise_mean", + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("SpectralAngleMapper", "image") + super().__init__(reduction=reduction, **kwargs) + + +class _SpectralDistortionIndex(SpectralDistortionIndex): + """Wrapper for deprecated import. + + >>> from torch import rand + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> sdi = _SpectralDistortionIndex() + >>> sdi(preds, target) + tensor(0.0234) + + """ + + def __init__( + self, p: int = 1, reduction: Literal["elementwise_mean", "sum", "none"] = "elementwise_mean", **kwargs: Any + ) -> None: + _deprecated_root_import_class("SpectralDistortionIndex", "image") + super().__init__(p=p, reduction=reduction, **kwargs) + + +class _StructuralSimilarityIndexMeasure(StructuralSimilarityIndexMeasure): + """Wrapper for deprecated import. + + >>> import torch + >>> preds = torch.rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> ssim = _StructuralSimilarityIndexMeasure(data_range=1.0) + >>> ssim(preds, target) + tensor(0.9219) + + """ + + def __init__( + self, + gaussian_kernel: bool = True, + sigma: Union[float, Sequence[float]] = 1.5, + kernel_size: Union[int, Sequence[int]] = 11, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + return_full_image: bool = False, + return_contrast_sensitivity: bool = False, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("StructuralSimilarityIndexMeasure", "image") + super().__init__( + gaussian_kernel=gaussian_kernel, + sigma=sigma, + kernel_size=kernel_size, + reduction=reduction, + data_range=data_range, + k1=k1, + k2=k2, + return_full_image=return_full_image, + return_contrast_sensitivity=return_contrast_sensitivity, + **kwargs, + ) + + +class _TotalVariation(TotalVariation): + """Wrapper for deprecated import. + + >>> from torch import rand + >>> tv = _TotalVariation() + >>> img = rand(5, 3, 28, 28) + >>> tv(img) + tensor(7546.8018) + + """ + + def __init__(self, reduction: Literal["mean", "sum", "none", None] = "sum", **kwargs: Any) -> None: + _deprecated_root_import_class("TotalVariation", "image") + super().__init__(reduction=reduction, **kwargs) + + +class _UniversalImageQualityIndex(UniversalImageQualityIndex): + """Wrapper for deprecated import. + + >>> import torch + >>> preds = torch.rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> uqi = _UniversalImageQualityIndex() + >>> uqi(preds, target) + tensor(0.9216) + + """ + + def __init__( + self, + kernel_size: Sequence[int] = (11, 11), + sigma: Sequence[float] = (1.5, 1.5), + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("UniversalImageQualityIndex", "image") + super().__init__(kernel_size=kernel_size, sigma=sigma, reduction=reduction, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/arniqa.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/arniqa.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4ca137a53c55d6f5468c1a77c77a17570d6425 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/arniqa.py @@ -0,0 +1,216 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.arniqa import ( + _ARNIQA, + _TYPE_REGRESSOR_DATASET, + _arniqa_compute, + _arniqa_update, + _NoTrainArniqa, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_GREATER_EQUAL_2_2, _TORCHVISION_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ARNIQA.plot"] + +if _TORCH_GREATER_EQUAL_2_2 and _TORCHVISION_AVAILABLE: + + def _download_arniqa() -> None: + _ARNIQA(regressor_dataset="koniq10k") + + if _SKIP_SLOW_DOCTEST and not _try_proceed_with_timeout(_download_arniqa): + __doctest_skip__ = ["ARNIQA", "ARNIQA.plot"] +else: + __doctest_skip__ = ["ARNIQA", "ARNIQA.plot"] + + +class ARNIQA(Metric): + """ARNIQA: leArning distoRtion maNifold for Image Quality Assessment metric. + + `ARNIQA`_ is a No-Reference Image Quality Assessment metric that predicts the technical quality of an image with + a high correlation with human opinions. ARNIQA consists of an encoder and a regressor. The encoder is a ResNet-50 + model trained in a self-supervised way to model the image distortion manifold to generate similar representation for + images with similar distortions, regardless of the image content. The regressor is a linear model trained on IQA + datasets using the ground-truth quality scores. ARNIQA extracts the features from the full- and half-scale versions + of the input image and then outputs a quality score in the [0, 1] range, where higher is better. + + The input image is expected to have shape ``(N, 3, H, W)``. The image should be in the [0, 1] range if `normalize` + is set to ``True``, otherwise it should be normalized with the ImageNet mean and standard deviation. + + .. note:: + Using this metric requires you to have ``torchvision`` package installed. Either install as + ``pip install torchmetrics[image]`` or ``pip install torchvision``. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``img`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``arniqa`` (:class:`~torch.Tensor`): tensor with ARNIQA score. If `reduction` is set to ``none``, the output will + have shape ``(N,)``, otherwise it will be a scalar tensor. Tensor values are in the [0, 1] range, where higher + is better. + + Args: + img: the input image + regressor_dataset: dataset used for training the regressor. Choose between [``koniq10k``, ``kadid10k``]. + ``koniq10k`` corresponds to the `KonIQ-10k`_ dataset, which consists of real-world images with authentic + distortions. ``kadid10k`` corresponds to the `KADID-10k`_ dataset, which consists of images with + synthetically generated distortions. + reduction: indicates how to reduce over the batch dimension. Choose between [``sum``, ``mean``, ``none``]. + normalize: by default this is ``True`` meaning that the input is expected to be in the [0, 1] range. If set + to ``False`` will instead expect input to be already normalized with the ImageNet mean and standard + deviation. + autocast: if ``True``, metric will convert model to mixed precision before running forward pass. + kwargs: additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ModuleNotFoundError: + If ``torchvision`` package is not installed + ValueError: + If ``regressor_dataset`` is not in [``"kadid10k"``, ``"koniq10k"``] + ValueError: + If ``reduction`` is not in [``"sum"``, ``"mean"``, ``"none"``] + ValueError: + If ``normalize`` is not a bool + ValueError: + If the input image is not a valid image tensor with shape [N, 3, H, W]. + ValueError: + If the input image values are not in the [0, 1] range when ``normalize`` is set to ``True`` + + Examples: + >>> from torch import rand + >>> from torchmetrics.image.arniqa import ARNIQA + >>> img = rand(8, 3, 224, 224) + >>> # Non-normalized input + >>> metric = ARNIQA(regressor_dataset='koniq10k', normalize=True) + >>> metric(img) + tensor(0.5308) + + >>> from torch import rand + >>> from torchmetrics.image.arniqa import ARNIQA + >>> from torchvision.transforms import Normalize + >>> img = rand(8, 3, 224, 224) + >>> img = Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])(img) + >>> # Normalized input + >>> metric = ARNIQA(regressor_dataset='koniq10k', normalize=False) + >>> metric(img) + tensor(0.5065) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + sum_scores: Tensor + num_scores: Tensor + feature_network: str = "model" + + def __init__( + self, + regressor_dataset: _TYPE_REGRESSOR_DATASET = "koniq10k", + reduction: Literal["sum", "mean", "none"] = "mean", + normalize: bool = True, + autocast: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if not _TORCH_GREATER_EQUAL_2_2: # ToDo: RuntimeError: "slow_conv2d_cpu" not implemented for 'Half' + raise RuntimeError("ARNIQA metric requires PyTorch >= 2.2.0") + + if not _TORCHVISION_AVAILABLE: + raise ModuleNotFoundError( + "ARNIQA metric requires that torchvision is installed." + " Either install as `pip install torchmetrics[image]` or `pip install torchvision`." + ) + + self.model = _NoTrainArniqa(regressor_dataset=regressor_dataset) + + valid_reduction = ("mean", "sum", "none") + if reduction not in valid_reduction: + raise ValueError(f"Argument `reduction` must be one of {valid_reduction}, but got {reduction}") + self.reduction = reduction + + if not isinstance(normalize, bool): + raise ValueError(f"Argument `normalize` should be a bool but got {normalize}") + self.normalize = normalize + self.autocast = autocast + + self.add_state("sum_scores", torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("num_scores", torch.tensor(0.0), dist_reduce_fx="sum") + + def update(self, img: Tensor) -> None: + """Update internal states with arniqa score.""" + loss, num_scores = _arniqa_update(img, model=self.model, normalize=self.normalize, autocast=self.autocast) + self.sum_scores += loss.sum() + self.num_scores += num_scores + + def compute(self) -> Tensor: + """Compute final arniqa metric.""" + return _arniqa_compute(self.sum_scores, self.num_scores, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image.arniqa import ARNIQA + >>> metric = ARNIQA(regressor_dataset='koniq10k') + >>> metric.update(torch.rand(8, 3, 224, 224)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image.arniqa import ARNIQA + >>> metric = ARNIQA(regressor_dataset='koniq10k') + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.rand(8, 3, 224, 224))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/d_lambda.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/d_lambda.py new file mode 100644 index 0000000000000000000000000000000000000000..97d95ccd926689d1b027efe5811146934902216c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/d_lambda.py @@ -0,0 +1,152 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.d_lambda import _spectral_distortion_index_compute, _spectral_distortion_index_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["SpectralDistortionIndex.plot"] + + +class SpectralDistortionIndex(Metric): + """Compute Spectral Distortion Index (SpectralDistortionIndex_) also now as D_lambda. + + The metric is used to compare the spectral distortion between two images. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Low resolution multispectral image of shape ``(N,C,H,W)`` + - ``target``(:class:`~torch.Tensor`): High resolution fused image of shape ``(N,C,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``sdi`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average SDI value + over sample else returns tensor of shape ``(N,)`` with SDI values per sample + + Args: + p: Large spectral differences + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'``: no reduction will be applied + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import rand + >>> from torchmetrics.image import SpectralDistortionIndex + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> sdi = SpectralDistortionIndex() + >>> sdi(preds, target) + tensor(0.0234) + + """ + + higher_is_better: bool = True + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, p: int = 1, reduction: Literal["elementwise_mean", "sum", "none"] = "elementwise_mean", **kwargs: Any + ) -> None: + super().__init__(**kwargs) + rank_zero_warn( + "Metric `SpectralDistortionIndex` will save all targets and" + " predictions in buffer. For large datasets this may lead" + " to large memory footprint." + ) + + if not isinstance(p, int) or p <= 0: + raise ValueError(f"Expected `p` to be a positive integer. Got p: {p}.") + self.p = p + allowed_reductions = ("elementwise_mean", "sum", "none") + if reduction not in allowed_reductions: + raise ValueError(f"Expected argument `reduction` be one of {allowed_reductions} but got {reduction}") + self.reduction = reduction + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("target", default=[], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with preds and target.""" + preds, target = _spectral_distortion_index_update(preds, target) + self.preds.append(preds) + self.target.append(target) + + def compute(self) -> Tensor: + """Compute and returns spectral distortion index.""" + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + return _spectral_distortion_index_compute(preds, target, self.p, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torch import rand + >>> from torchmetrics.image import SpectralDistortionIndex + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> metric = SpectralDistortionIndex() + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import rand + >>> from torchmetrics.image import SpectralDistortionIndex + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> metric = SpectralDistortionIndex() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/d_s.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/d_s.py new file mode 100644 index 0000000000000000000000000000000000000000..9143810f5459be7eb98362234f33952e5b11547b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/d_s.py @@ -0,0 +1,223 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.d_s import _spatial_distortion_index_compute, _spatial_distortion_index_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCHVISION_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["SpatialDistortionIndex.plot"] + +if not _TORCHVISION_AVAILABLE: + __doctest_skip__ = ["SpatialDistortionIndex", "SpatialDistortionIndex.plot"] + + +class SpatialDistortionIndex(Metric): + r"""Compute Spatial Distortion Index (SpatialDistortionIndex_) also now as D_s. + + The metric is used to compare the spatial distortion between two images. A value of 0 indicates no distortion + (optimal value) and corresponds to the case where the high resolution panchromatic image is equal to the low + resolution panchromatic image. The metric is defined as: + + .. math:: + D_s = \\sqrt[q]{\frac{1}{L}\\sum_{l=1}^L|Q(\\hat{G_l}, P) - Q(\tilde{G}, \tilde{P})|^q} + + where :math:`Q` is the universal image quality index (see this + :class:`~torchmetrics.image.UniversalImageQualityIndex` for more info), :math:`\\hat{G_l}` is the l-th band of the + high resolution multispectral image, :math:`\tilde{G}` is the high resolution panchromatic image, :math:`P` is the + high resolution panchromatic image, :math:`\tilde{P}` is the low resolution panchromatic image, :math:`L` is the + number of bands and :math:`q` is the order of the norm applied on the difference. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): High resolution multispectral image of shape ``(N,C,H,W)``. + - ``target`` (:class:`~Dict`): A dictionary containing the following keys: + - ``ms`` (:class:`~torch.Tensor`): Low resolution multispectral image of shape ``(N,C,H',W')``. + - ``pan`` (:class:`~torch.Tensor`): High resolution panchromatic image of shape ``(N,C,H,W)``. + - ``pan_lr`` (:class:`~torch.Tensor`): Low resolution panchromatic image of shape ``(N,C,H',W')``. + + where H and W must be multiple of H' and W'. + + As output of `forward` and `compute` the metric returns the following output + + - ``sdi`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average SDI value + over sample else returns tensor of shape ``(N,)`` with SDI values per sample + + Args: + norm_order: Order of the norm applied on the difference. + window_size: Window size of the filter applied to degrade the high resolution panchromatic image. + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'``: no reduction will be applied + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import rand + >>> from torchmetrics.image import SpatialDistortionIndex + >>> preds = rand([16, 3, 32, 32]) + >>> target = { + ... 'ms': rand([16, 3, 16, 16]), + ... 'pan': rand([16, 3, 32, 32]), + ... } + >>> sdi = SpatialDistortionIndex() + >>> sdi(preds, target) + tensor(0.0090) + + """ + + higher_is_better: bool = False + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + ms: List[Tensor] + pan: List[Tensor] + pan_lr: List[Tensor] + + def __init__( + self, + norm_order: int = 1, + window_size: int = 7, + reduction: Literal["elementwise_mean", "sum", "none"] = "elementwise_mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + rank_zero_warn( + "Metric `SpatialDistortionIndex` will save all targets and" + " predictions in buffer. For large datasets this may lead" + " to large memory footprint." + ) + + if not isinstance(norm_order, int) or norm_order <= 0: + raise ValueError(f"Expected `norm_order` to be a positive integer. Got norm_order: {norm_order}.") + self.norm_order = norm_order + if not isinstance(window_size, int) or window_size <= 0: + raise ValueError(f"Expected `window_size` to be a positive integer. Got window_size: {window_size}.") + self.window_size = window_size + allowed_reductions = ("elementwise_mean", "sum", "none") + if reduction not in allowed_reductions: + raise ValueError(f"Expected argument `reduction` be one of {allowed_reductions} but got {reduction}") + self.reduction = reduction + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("ms", default=[], dist_reduce_fx="cat") + self.add_state("pan", default=[], dist_reduce_fx="cat") + self.add_state("pan_lr", default=[], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: dict[str, Tensor]) -> None: + """Update state with preds and target. + + Args: + preds: High resolution multispectral image. + target: A dictionary containing the following keys: + + - ``'ms'``: low resolution multispectral image. + - ``'pan'``: high resolution panchromatic image. + - ``'pan_lr'``: (optional) low resolution panchromatic image. + + Raises: + ValueError: + If ``target`` doesn't have ``ms`` and ``pan``. + + """ + if "ms" not in target: + raise ValueError(f"Expected `target` to have key `ms`. Got target: {target.keys()}.") + if "pan" not in target: + raise ValueError(f"Expected `target` to have key `pan`. Got target: {target.keys()}.") + ms = target["ms"] + pan = target["pan"] + pan_lr = target.get("pan_lr") + preds, ms, pan, pan_lr = _spatial_distortion_index_update(preds, ms, pan, pan_lr) + self.preds.append(preds) + self.ms.append(target["ms"]) + self.pan.append(target["pan"]) + if "pan_lr" in target: + self.pan_lr.append(target["pan_lr"]) + + def compute(self) -> Tensor: + """Compute and returns spatial distortion index.""" + preds = dim_zero_cat(self.preds) + ms = dim_zero_cat(self.ms) + pan = dim_zero_cat(self.pan) + pan_lr = dim_zero_cat(self.pan_lr) if len(self.pan_lr) > 0 else None + target = {"ms": ms, "pan": pan} + target.update({"pan_lr": pan_lr} if pan_lr is not None else {}) + return _spatial_distortion_index_compute( + preds, ms, pan, pan_lr, self.norm_order, self.window_size, self.reduction + ) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torch import rand + >>> from torchmetrics.image import SpatialDistortionIndex + >>> preds = rand([16, 3, 32, 32]) + >>> target = { + ... 'ms': rand([16, 3, 16, 16]), + ... 'pan': rand([16, 3, 32, 32]), + ... } + >>> metric = SpatialDistortionIndex() + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import rand + >>> from torchmetrics.image import SpatialDistortionIndex + >>> preds = rand([16, 3, 32, 32]) + >>> target = { + ... 'ms': rand([16, 3, 16, 16]), + ... 'pan': rand([16, 3, 32, 32]), + ... } + >>> metric = SpatialDistortionIndex() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/dists.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/dists.py new file mode 100644 index 0000000000000000000000000000000000000000..0c3877e099d26a19bb00062147bd15892eef81c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/dists.py @@ -0,0 +1,136 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Literal, Optional, Sequence, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.image.dists import _dists_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCHVISION_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["DeepImageStructureAndTextureSimilarity.plot"] + +if not _TORCHVISION_AVAILABLE: + __doctest_skip__ = ["DeepImageStructureAndTextureSimilarity", "DeepImageStructureAndTextureSimilarity.plot"] + + +class DeepImageStructureAndTextureSimilarity(Metric): + """Calculates Deep Image Structure and Texture Similarity (DISTS) score. + + The metric is a full-reference image quality assessment (IQA) model that combines sensitivity to structural + distortions (e.g., artifacts due to noise, blur, or compression) with a tolerance of texture resampling + (exchanging the content of a texture region with a new sample of the same texture). The metric is based on + a convolutional neural network (CNN) that transforms the reference and distorted images to a new representation. + Within this representation, a set of measurements are developed that are sufficient to capture the appearance + of a variety of different visual distortions. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)`` + - ``target`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``lpips`` (:class:`~torch.Tensor`): returns float scalar tensor with average LPIPS value over samples + + Args: + reduction: specifies the reduction to apply to the output. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If `reduction` is not one of ["mean", "sum"] + + Example: + >>> from torch import rand + >>> from torchmetrics.image.dists import DeepImageStructureAndTextureSimilarity + >>> metric = DeepImageStructureAndTextureSimilarity() + >>> preds = rand(10, 3, 100, 100) + >>> target = rand(10, 3, 100, 100) + >>> metric(preds, target) + tensor(0.1882, grad_fn=) + + """ + + score: Tensor + total: Tensor + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + def __init__(self, reduction: Optional[Literal["mean", "sum"]] = "mean", **kwargs: Any) -> None: + super().__init__(**kwargs) + allowed_reductions = ("mean", "sum") + if reduction not in allowed_reductions: + raise ValueError(f"Argument `reduction` expected to be one of {allowed_reductions} but got {reduction}") + self.reduction = reduction + self.add_state("score", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=torch.tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update the metric state.""" + scores = _dists_update(preds, target) + self.score += scores.sum() + self.total += preds.shape[0] + + def compute(self) -> Tensor: + """Computes the DISTS score.""" + return self.score / self.total if self.reduction == "mean" else self.score + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image.dists import DeepImageStructureAndTextureSimilarity + >>> metric = DeepImageStructureAndTextureSimilarity() + >>> metric.update(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image.dists import DeepImageStructureAndTextureSimilarity + >>> metric = DeepImageStructureAndTextureSimilarity() + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/ergas.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/ergas.py new file mode 100644 index 0000000000000000000000000000000000000000..22c24b164f13fc837cb25f4d9c259b410f393d2b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/ergas.py @@ -0,0 +1,158 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.ergas import _ergas_compute, _ergas_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ErrorRelativeGlobalDimensionlessSynthesis.plot"] + + +class ErrorRelativeGlobalDimensionlessSynthesis(Metric): + r"""Calculate the `Error relative global dimensionless synthesis`_ (ERGAS) metric. + + This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each + band of the result image. It is defined as: + + .. math:: + ERGAS = \frac{100}{r} \cdot \sqrt{\frac{1}{N} \sum_{k=1}^{N} \frac{RMSE(B_k)^2}{\mu_k^2}} + + where :math:`r=h/l` denote the ratio in spatial resolution (pixel size) between the high and low resolution images. + :math:`N` is the number of spectral bands, :math:`RMSE(B_k)` is the root mean square error of the k-th band between + low and high resolution images, and :math:`\\mu_k` is the mean value of the k-th band of the reference image. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of `forward` and `compute` the metric returns the following output + + - ``ergas`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average ERGAS + value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample + + Args: + ratio: ratio of high resolution to low resolution. + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import rand + >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis + >>> preds = rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> ergas = ErrorRelativeGlobalDimensionlessSynthesis() + >>> ergas(preds, target).round() + tensor(10.) + + """ + + higher_is_better: bool = False + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + ratio: float = 4, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + rank_zero_warn( + "Metric `UniversalImageQualityIndex` will save all targets and" + " predictions in buffer. For large datasets this may lead" + " to large memory footprint." + ) + + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("target", default=[], dist_reduce_fx="cat") + self.ratio = ratio + self.reduction = reduction + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + preds, target = _ergas_update(preds, target) + self.preds.append(preds) + self.target.append(target) + + def compute(self) -> Tensor: + """Compute explained variance over state.""" + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + return _ergas_compute(preds, target, self.ratio, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torch import rand + >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis + >>> preds = rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> metric = ErrorRelativeGlobalDimensionlessSynthesis() + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import rand + >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis + >>> preds = rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> metric = ErrorRelativeGlobalDimensionlessSynthesis() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/fid.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/fid.py new file mode 100644 index 0000000000000000000000000000000000000000..49f9f057d837ef375bad1074f1a8aafc4f732d9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/fid.py @@ -0,0 +1,495 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from copy import deepcopy +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from torch.nn import Module +from torch.nn.functional import adaptive_avg_pool2d + +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["FrechetInceptionDistance.plot"] + +if _TORCH_FIDELITY_AVAILABLE: + from torch_fidelity.feature_extractor_inceptionv3 import FeatureExtractorInceptionV3 as _FeatureExtractorInceptionV3 + from torch_fidelity.helpers import vassert + from torch_fidelity.interpolate_compat_tensorflow import interpolate_bilinear_2d_like_tensorflow1x +else: + + class _FeatureExtractorInceptionV3(Module): # type: ignore[no-redef] + pass + + vassert = None + interpolate_bilinear_2d_like_tensorflow1x = None + + __doctest_skip__ = ["FrechetInceptionDistance", "FrechetInceptionDistance.plot"] + + +class NoTrainInceptionV3(_FeatureExtractorInceptionV3): + """Module that never leaves evaluation mode.""" + + INPUT_IMAGE_SIZE: int + + def __init__( + self, + name: str, + features_list: list[str], + feature_extractor_weights_path: Optional[str] = None, + antialias: bool = True, + ) -> None: + if not _TORCH_FIDELITY_AVAILABLE: + raise ModuleNotFoundError( + "NoTrainInceptionV3 module requires that `Torch-fidelity` is installed." + " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`." + ) + + super().__init__(name, features_list, feature_extractor_weights_path) + self.use_antialias = antialias + # put into evaluation mode + self.eval() + + def train(self, mode: bool) -> "NoTrainInceptionV3": + """Force network to always be in evaluation mode.""" + return super().train(False) + + def _torch_fidelity_forward(self, x: Tensor) -> tuple[Tensor, ...]: + """Forward method of inception net. + + Copy of the forward method from this file: + https://github.com/toshas/torch-fidelity/blob/master/torch_fidelity/feature_extractor_inceptionv3.py + with a single line change regarding the casting of `x` in the beginning. + + Corresponding license file (Apache License, Version 2.0): + https://github.com/toshas/torch-fidelity/blob/master/LICENSE.md + + """ + vassert(torch.is_tensor(x) and x.dtype == torch.uint8, "Expecting image as torch.Tensor with dtype=torch.uint8") + features = {} + remaining_features = self.features_list.copy() + + x = x.to(self._dtype) if hasattr(self, "_dtype") else x.to(torch.float) + if self.use_antialias: + x = torch.nn.functional.interpolate( + x, + size=(self.INPUT_IMAGE_SIZE, self.INPUT_IMAGE_SIZE), + mode="bilinear", + align_corners=False, + antialias=True, + ) + else: + x = interpolate_bilinear_2d_like_tensorflow1x( + x, + size=(self.INPUT_IMAGE_SIZE, self.INPUT_IMAGE_SIZE), + align_corners=False, + ) + + x = (x - 128) / 128 + + x = self.Conv2d_1a_3x3(x) + x = self.Conv2d_2a_3x3(x) + x = self.Conv2d_2b_3x3(x) + x = self.MaxPool_1(x) + + if "64" in remaining_features: + features["64"] = adaptive_avg_pool2d(x, output_size=(1, 1)).squeeze(-1).squeeze(-1) + remaining_features.remove("64") + if len(remaining_features) == 0: + return tuple(features[a] for a in self.features_list) + + x = self.Conv2d_3b_1x1(x) + x = self.Conv2d_4a_3x3(x) + x = self.MaxPool_2(x) + + if "192" in remaining_features: + features["192"] = adaptive_avg_pool2d(x, output_size=(1, 1)).squeeze(-1).squeeze(-1) + remaining_features.remove("192") + if len(remaining_features) == 0: + return tuple(features[a] for a in self.features_list) + + x = self.Mixed_5b(x) + x = self.Mixed_5c(x) + x = self.Mixed_5d(x) + x = self.Mixed_6a(x) + x = self.Mixed_6b(x) + x = self.Mixed_6c(x) + x = self.Mixed_6d(x) + x = self.Mixed_6e(x) + + if "768" in remaining_features: + features["768"] = adaptive_avg_pool2d(x, output_size=(1, 1)).squeeze(-1).squeeze(-1) + remaining_features.remove("768") + if len(remaining_features) == 0: + return tuple(features[a] for a in self.features_list) + + x = self.Mixed_7a(x) + x = self.Mixed_7b(x) + x = self.Mixed_7c(x) + x = self.AvgPool(x) + x = torch.flatten(x, 1) + + if "2048" in remaining_features: + features["2048"] = x + remaining_features.remove("2048") + if len(remaining_features) == 0: + return tuple(features[a] for a in self.features_list) + + if "logits_unbiased" in remaining_features: + x = x.mm(self.fc.weight.T) + # N x 1008 (num_classes) + features["logits_unbiased"] = x + remaining_features.remove("logits_unbiased") + if len(remaining_features) == 0: + return tuple(features[a] for a in self.features_list) + + x = x + self.fc.bias.unsqueeze(0) + else: + x = self.fc(x) + + features["logits"] = x + return tuple(features[a] for a in self.features_list) + + def forward(self, x: Tensor) -> Tensor: + """Forward pass of neural network with reshaping of output.""" + out = self._torch_fidelity_forward(x) + return out[0].reshape(x.shape[0], -1) + + +def _compute_fid(mu1: Tensor, sigma1: Tensor, mu2: Tensor, sigma2: Tensor) -> Tensor: + r"""Compute adjusted version of `Fid Score`_. + + The Frechet Inception Distance between two multivariate Gaussians X_x ~ N(mu_1, sigm_1) + and X_y ~ N(mu_2, sigm_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(sigm_1 + sigm_2 - 2*sqrt(sigm_1*sigm_2)). + + Args: + mu1: mean of activations calculated on predicted (x) samples + sigma1: covariance matrix over activations calculated on predicted (x) samples + mu2: mean of activations calculated on target (y) samples + sigma2: covariance matrix over activations calculated on target (y) samples + + Returns: + Scalar value of the distance between sets. + + """ + a = (mu1 - mu2).square().sum(dim=-1) + b = sigma1.trace() + sigma2.trace() + c = torch.linalg.eigvals(sigma1 @ sigma2).sqrt().real.sum(dim=-1) + + return a + b - 2 * c + + +class FrechetInceptionDistance(Metric): + r"""Calculate Fréchet inception distance (FID_) which is used to assess the quality of generated images. + + .. math:: + FID = \|\mu - \mu_w\|^2 + tr(\Sigma + \Sigma_w - 2(\Sigma \Sigma_w)^{\frac{1}{2}}) + + where :math:`\mathcal{N}(\mu, \Sigma)` is the multivariate normal distribution estimated from Inception v3 + (`fid ref1`_) features calculated on real life images and :math:`\mathcal{N}(\mu_w, \Sigma_w)` is the + multivariate normal distribution estimated from Inception v3 features calculated on generated (fake) images. + The metric was originally proposed in `fid ref1`_. + + Using the default feature extraction (Inception v3 using the original weights from `fid ref2`_), the input is + expected to be mini-batches of 3-channel RGB images of shape ``(3xHxW)``. If argument ``normalize`` + is ``True`` images are expected to be dtype ``float`` and have values in the ``[0,1]`` range, else if + ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]`` + range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian + flag ``real`` determines if the images should update the statistics of the real distribution or the + fake distribution. + + Using custom feature extractor is also possible. One can give a torch.nn.Module as `feature` argument. This + custom feature extractor is expected to have output shape of ``(1, num_features)``. This would change the + used feature extractor from default (Inception v3) to the given network. In case network doesn't have + ``num_features`` attribute, a random tensor will be given to the network to infer feature dimensionality. + Size of this tensor can be controlled by ``input_img_size`` argument and type of the tensor can be controlled + with ``normalize`` argument (``True`` uses float32 tensors and ``False`` uses int8 tensors). In this case, update + method expects to have the tensor given to `imgs` argument to be in the correct shape and type that is compatible + to the custom feature extractor. + + This metric is known to be unstable in its calculatations, and we recommend for the best results using this metric + that you calculate using `torch.float64` (default is `torch.float32`) which can be set using the `.set_dtype` + method of the metric. + + .. hint:: + Using this metric with the default feature extractor requires that ``torch-fidelity`` + is installed. Either install as ``pip install torchmetrics[image]`` or ``pip install torch-fidelity`` + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor with + - ``real`` (:class:`~bool`): bool indicating if ``imgs`` belong to the real or the fake distribution + + As output of `forward` and `compute` the metric returns the following output + + - ``fid`` (:class:`~torch.Tensor`): float scalar tensor with mean FID value over samples + + Args: + feature: + Either an integer or ``nn.Module``: + + - an integer will indicate the inceptionv3 feature layer to choose. Can be one of the following: + 64, 192, 768, 2048 + - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns + an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size. + + reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not + change, the features can be cached them to avoid recomputing them which is costly. Set this to ``False`` if + your dataset does not change. + normalize: + Argument for controlling the input image dtype normalization: + + - If default feature extractor is used, controls whether input imgs have values in range [0, 1] or not: + + - True: if input imgs have values ranged in [0, 1]. They are cast to int8/byte tensors. + - False: if input imgs have values ranged in [0, 255]. No casting is done. + + - If custom feature extractor module is used, controls type of the input img tensors: + + - True: if input imgs are expected to be in the data type of torch.float32. + - False: if input imgs are expected to be in the data type of torch.int8. + input_img_size: tuple of integers. Indicates input img size to the custom feature extractor network if provided. + use_antialias: boolian flag to indicate whether to use antialiasing when resizing images. This will change the + resize function to use bilinear interpolation with antialiasing, which is different from the original + Inception v3 implementation. Does not apply to custom feature extractor networks. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If torch version is lower than 1.9 + ModuleNotFoundError: + If ``feature`` is set to an ``int`` (default settings) and ``torch-fidelity`` is not installed + ValueError: + If ``feature`` is set to an ``int`` not in [64, 192, 768, 2048] + TypeError: + If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module`` + ValueError: + If ``reset_real_features`` is not an ``bool`` + + Example: + >>> from torch import rand + >>> from torchmetrics.image.fid import FrechetInceptionDistance + >>> fid = FrechetInceptionDistance(feature=64) + >>> # generate two slightly overlapping image intensity distributions + >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> fid.update(imgs_dist1, real=True) + >>> fid.update(imgs_dist2, real=False) + >>> fid.compute() + tensor(12.6388) + + """ + + higher_is_better: bool = False + is_differentiable: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + real_features_sum: Tensor + real_features_cov_sum: Tensor + real_features_num_samples: Tensor + + fake_features_sum: Tensor + fake_features_cov_sum: Tensor + fake_features_num_samples: Tensor + + inception: Module + feature_network: str = "inception" + + def __init__( + self, + feature: Union[int, Module] = 2048, + reset_real_features: bool = True, + normalize: bool = False, + input_img_size: tuple[int, int, int] = (3, 299, 299), + feature_extractor_weights_path: Optional[str] = None, + antialias: bool = True, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if not isinstance(normalize, bool): + raise ValueError("Argument `normalize` expected to be a bool") + self.normalize = normalize + self.used_custom_model = False + antialias = antialias + + if isinstance(feature, int): + num_features = feature + if not _TORCH_FIDELITY_AVAILABLE: + raise ModuleNotFoundError( + "FrechetInceptionDistance metric requires that `Torch-fidelity` is installed." + " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`." + ) + valid_int_input = (64, 192, 768, 2048) + if feature not in valid_int_input: + raise ValueError( + f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}." + ) + + self.inception = NoTrainInceptionV3( + name="inception-v3-compat", + features_list=[str(feature)], + feature_extractor_weights_path=feature_extractor_weights_path, + antialias=antialias, + ) + + elif isinstance(feature, Module): + self.inception = feature + self.used_custom_model = True + if hasattr(self.inception, "num_features"): + if isinstance(self.inception.num_features, int): + num_features = self.inception.num_features + elif isinstance(self.inception.num_features, Tensor): + num_features = int(self.inception.num_features.item()) + else: + raise TypeError("Expected `self.inception.num_features` to be of type int or Tensor.") + else: + if self.normalize: + dummy_image = torch.rand(1, *input_img_size, dtype=torch.float32) + else: + dummy_image = torch.randint(0, 255, (1, *input_img_size), dtype=torch.uint8) + num_features = self.inception(dummy_image).shape[-1] + else: + raise TypeError("Got unknown input to argument `feature`") + + if not isinstance(reset_real_features, bool): + raise ValueError("Argument `reset_real_features` expected to be a bool") + self.reset_real_features = reset_real_features + + mx_num_feats = (num_features, num_features) + self.add_state("real_features_sum", torch.zeros(num_features).double(), dist_reduce_fx="sum") + self.add_state("real_features_cov_sum", torch.zeros(mx_num_feats).double(), dist_reduce_fx="sum") + self.add_state("real_features_num_samples", torch.tensor(0).long(), dist_reduce_fx="sum") + + self.add_state("fake_features_sum", torch.zeros(num_features).double(), dist_reduce_fx="sum") + self.add_state("fake_features_cov_sum", torch.zeros(mx_num_feats).double(), dist_reduce_fx="sum") + self.add_state("fake_features_num_samples", torch.tensor(0).long(), dist_reduce_fx="sum") + + def update(self, imgs: Tensor, real: bool) -> None: + """Update the state with extracted features. + + Args: + imgs: Input img tensors to evaluate. If used custom feature extractor please + make sure dtype and size is correct for the model. + real: Whether given image is real or fake. + + """ + imgs = (imgs * 255).byte() if self.normalize and (not self.used_custom_model) else imgs + features = self.inception(imgs) + self.orig_dtype = features.dtype + features = features.double() + + if features.dim() == 1: + features = features.unsqueeze(0) + if real: + self.real_features_sum += features.sum(dim=0) + self.real_features_cov_sum += features.t().mm(features) + self.real_features_num_samples += imgs.shape[0] + else: + self.fake_features_sum += features.sum(dim=0) + self.fake_features_cov_sum += features.t().mm(features) + self.fake_features_num_samples += imgs.shape[0] + + def compute(self) -> Tensor: + """Calculate FID score based on accumulated extracted features from the two distributions.""" + if self.real_features_num_samples < 2 or self.fake_features_num_samples < 2: + raise RuntimeError("More than one sample is required for both the real and fake distributed to compute FID") + mean_real = (self.real_features_sum / self.real_features_num_samples).unsqueeze(0) + mean_fake = (self.fake_features_sum / self.fake_features_num_samples).unsqueeze(0) + + cov_real_num = self.real_features_cov_sum - self.real_features_num_samples * mean_real.t().mm(mean_real) + cov_real = cov_real_num / (self.real_features_num_samples - 1) + cov_fake_num = self.fake_features_cov_sum - self.fake_features_num_samples * mean_fake.t().mm(mean_fake) + cov_fake = cov_fake_num / (self.fake_features_num_samples - 1) + return _compute_fid(mean_real.squeeze(0), cov_real, mean_fake.squeeze(0), cov_fake).to(self.orig_dtype) + + def reset(self) -> None: + """Reset metric states.""" + if not self.reset_real_features: + real_features_sum = deepcopy(self.real_features_sum) + real_features_cov_sum = deepcopy(self.real_features_cov_sum) + real_features_num_samples = deepcopy(self.real_features_num_samples) + super().reset() + self.real_features_sum = real_features_sum + self.real_features_cov_sum = real_features_cov_sum + self.real_features_num_samples = real_features_num_samples + else: + super().reset() + + def set_dtype(self, dst_type: Union[str, torch.dtype]) -> "Metric": + """Transfer all metric state to specific dtype. Special version of standard `type` method. + + Arguments: + dst_type: the desired type as ``torch.dtype`` or string + + """ + out = super().set_dtype(dst_type) + if isinstance(out.inception, NoTrainInceptionV3): + out.inception._dtype = dst_type + return out + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image.fid import FrechetInceptionDistance + >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> metric = FrechetInceptionDistance(feature=64) + >>> metric.update(imgs_dist1, real=True) + >>> metric.update(imgs_dist2, real=False) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image.fid import FrechetInceptionDistance + >>> imgs_dist1 = lambda: torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = lambda: torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> metric = FrechetInceptionDistance(feature=64) + >>> values = [ ] + >>> for _ in range(3): + ... metric.update(imgs_dist1(), real=True) + ... metric.update(imgs_dist2(), real=False) + ... values.append(metric.compute()) + ... metric.reset() + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/inception.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/inception.py new file mode 100644 index 0000000000000000000000000000000000000000..fd11a6afe03827b4baed95a9cfff59915806fe0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/inception.py @@ -0,0 +1,221 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from torch.nn import Module + +from torchmetrics.image.fid import NoTrainInceptionV3 +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["InceptionScore.plot"] + + +__doctest_requires__ = {("InceptionScore", "InceptionScore.plot"): ["torch_fidelity"]} + + +class InceptionScore(Metric): + r"""Calculate the Inception Score (IS) which is used to access how realistic generated images are. + + .. math:: + IS = exp(\mathbb{E}_x KL(p(y | x ) || p(y))) + + where :math:`KL(p(y | x) || p(y))` is the KL divergence between the conditional distribution :math:`p(y|x)` + and the marginal distribution :math:`p(y)`. Both the conditional and marginal distribution is calculated + from features extracted from the images. The score is calculated on random splits of the images such that + both a mean and standard deviation of the score are returned. The metric was originally proposed in + `inception ref1`_. + + Using the default feature extraction (Inception v3 using the original weights from `inception ref2`_), the input + is expected to be mini-batches of 3-channel RGB images of shape ``(3xHxW)``. If argument ``normalize`` + is ``True`` images are expected to be dtype ``float`` and have values in the ``[0,1]`` range, else if + ``normalize`` is set to ``False`` images are expected to have dtype uint8 and take values in the ``[0, 255]`` + range. All images will be resized to 299 x 299 which is the size of the original training data. + + .. hint:: + Using this metric with the default feature extractor requires that ``torch-fidelity`` + is installed. Either install as ``pip install torchmetrics[image]`` or + ``pip install torch-fidelity`` + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor + + As output of `forward` and `compute` the metric returns the following output + + - ``inception_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean inception score over subsets + - ``inception_std`` (:class:`~torch.Tensor`): float scalar tensor with standard deviation of inception score + over subsets + + Args: + feature: + Either an str, integer or ``nn.Module``: + + - an str or integer will indicate the inceptionv3 feature layer to choose. Can be one of the following: + 'logits_unbiased', 64, 192, 768, 2048 + - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns + an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size. + + splits: integer determining how many splits the inception score calculation should be split among + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``feature`` is set to an ``str`` or ``int`` and ``torch-fidelity`` is not installed + ValueError: + If ``feature`` is set to an ``str`` or ``int`` and not one of ``('logits_unbiased', 64, 192, 768, 2048)`` + TypeError: + If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module`` + + Example: + >>> from torch import rand + >>> from torchmetrics.image.inception import InceptionScore + >>> inception = InceptionScore() + >>> # generate some images + >>> imgs = torch.randint(0, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> inception.update(imgs) + >>> inception.compute() + (tensor(1.0549), tensor(0.0121)) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + features: list + inception: Module + feature_network: str = "inception" + + def __init__( + self, + feature: Union[str, int, Module] = "logits_unbiased", + splits: int = 10, + normalize: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + rank_zero_warn( + "Metric `InceptionScore` will save all extracted features in buffer." + " For large datasets this may lead to large memory footprint.", + UserWarning, + ) + + if isinstance(feature, (str, int)): + if not _TORCH_FIDELITY_AVAILABLE: + raise ModuleNotFoundError( + "InceptionScore metric requires that `Torch-fidelity` is installed." + " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`." + ) + valid_int_input = ("logits_unbiased", 64, 192, 768, 2048) + if feature not in valid_int_input: + raise ValueError( + f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}." + ) + + self.inception = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)]) + elif isinstance(feature, Module): + self.inception = feature + else: + raise TypeError("Got unknown input to argument `feature`") + + if not isinstance(normalize, bool): + raise ValueError("Argument `normalize` expected to be a bool") + self.normalize = normalize + + self.splits = splits + self.add_state("features", [], dist_reduce_fx=None) + + def update(self, imgs: Tensor) -> None: + """Update the state with extracted features.""" + imgs = (imgs * 255).byte() if self.normalize else imgs + features = self.inception(imgs) + self.features.append(features) + + def compute(self) -> tuple[Tensor, Tensor]: + """Compute metric.""" + features = dim_zero_cat(self.features) + # random permute the features + idx = torch.randperm(features.shape[0]) + features = features[idx] + + # calculate probs and logits + prob = features.softmax(dim=1) + log_prob = features.log_softmax(dim=1) + + # split into groups + prob = prob.chunk(self.splits, dim=0) + log_prob = log_prob.chunk(self.splits, dim=0) + + # calculate score per split + mean_prob = [p.mean(dim=0, keepdim=True) for p in prob] + kl_ = [p * (log_p - m_p.log()) for p, log_p, m_p in zip(prob, log_prob, mean_prob)] + kl_ = [k.sum(dim=1).mean().exp() for k in kl_] + kl = torch.stack(kl_) + + # return mean and std + return kl.mean(), kl.std() + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image.inception import InceptionScore + >>> metric = InceptionScore() + >>> metric.update(torch.randint(0, 255, (50, 3, 299, 299), dtype=torch.uint8)) + >>> fig_, ax_ = metric.plot() # the returned plot only shows the mean value by default + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image.inception import InceptionScore + >>> metric = InceptionScore() + >>> values = [ ] + >>> for _ in range(3): + ... # we index by 0 such that only the mean value is plotted + ... values.append(metric(torch.randint(0, 255, (50, 3, 299, 299), dtype=torch.uint8))[0]) + >>> fig_, ax_ = metric.plot(values) + + """ + val = val or self.compute()[0] # by default we select the mean to plot + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/kid.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/kid.py new file mode 100644 index 0000000000000000000000000000000000000000..99c2b04bf7be577c1174e4a9c0d173066e6995c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/kid.py @@ -0,0 +1,358 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +import torch +from torch import Tensor +from torch.nn import Module + +from torchmetrics.image.fid import NoTrainInceptionV3 +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["KernelInceptionDistance.plot"] + +__doctest_requires__ = {("KernelInceptionDistance", "KernelInceptionDistance.plot"): ["torch_fidelity"]} + + +def maximum_mean_discrepancy(k_xx: Tensor, k_xy: Tensor, k_yy: Tensor) -> Tensor: + """Adapted from `KID Score`_.""" + m = k_xx.shape[0] + + diag_x = torch.diag(k_xx) + diag_y = torch.diag(k_yy) + + kt_xx_sums = k_xx.sum(dim=-1) - diag_x + kt_yy_sums = k_yy.sum(dim=-1) - diag_y + k_xy_sums = k_xy.sum(dim=0) + + kt_xx_sum = kt_xx_sums.sum() + kt_yy_sum = kt_yy_sums.sum() + k_xy_sum = k_xy_sums.sum() + + value = (kt_xx_sum + kt_yy_sum) / (m * (m - 1)) + value -= 2 * k_xy_sum / (m**2) + return value + + +def poly_kernel(f1: Tensor, f2: Tensor, degree: int = 3, gamma: Optional[float] = None, coef: float = 1.0) -> Tensor: + """Adapted from `KID Score`_.""" + if gamma is None: + gamma = 1.0 / f1.shape[1] + return (f1 @ f2.T * gamma + coef) ** degree + + +def poly_mmd( + f_real: Tensor, f_fake: Tensor, degree: int = 3, gamma: Optional[float] = None, coef: float = 1.0 +) -> Tensor: + """Adapted from `KID Score`_.""" + k_11 = poly_kernel(f_real, f_real, degree, gamma, coef) + k_22 = poly_kernel(f_fake, f_fake, degree, gamma, coef) + k_12 = poly_kernel(f_real, f_fake, degree, gamma, coef) + return maximum_mean_discrepancy(k_11, k_12, k_22) + + +class KernelInceptionDistance(Metric): + r"""Calculate Kernel Inception Distance (KID) which is used to access the quality of generated images. + + .. math:: + KID = MMD(f_{real}, f_{fake})^2 + + where :math:`MMD` is the maximum mean discrepancy and :math:`I_{real}, I_{fake}` are extracted features + from real and fake images, see `kid ref1`_ for more details. In particular, calculating the MMD requires the + evaluation of a polynomial kernel function :math:`k` + + .. math:: + k(x,y) = (\gamma * x^T y + coef)^{degree} + + which controls the distance between two features. In practise the MMD is calculated over a number of + subsets to be able to both get the mean and standard deviation of KID. + + Using the default feature extraction (Inception v3 using the original weights from `kid ref2`_), the input is + expected to be mini-batches of 3-channel RGB images of shape ``(3xHxW)``. If argument ``normalize`` + is ``True`` images are expected to be dtype ``float`` and have values in the ``[0,1]`` range, else if + ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]`` + range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian + flag ``real`` determines if the images should update the statistics of the real distribution or the + fake distribution. + + Using custom feature extractor is also possible. One can give a torch.nn.Module as `feature` argument. This + custom feature extractor is expected to have output shape of ``(1, num_features)`` This would change the + used feature extractor from default (Inception v3) to the given network. ``normalize`` argument won't have any + effect and update method expects to have the tensor given to `imgs` argument to be in the correct shape and + type that is compatible to the custom feature extractor. + + .. hint:: + Using this metric with the default feature extractor requires that ``torch-fidelity`` + is installed. Either install as ``pip install torchmetrics[image]`` or + ``pip install torch-fidelity`` + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor of shape ``(N,C,H,W)`` + - ``real`` (`bool`): bool indicating if ``imgs`` belong to the real or the fake distribution + + As output of `forward` and `compute` the metric returns the following output + + - ``kid_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean value over subsets + - ``kid_std`` (:class:`~torch.Tensor`): float scalar tensor with standard deviation value over subsets + + Args: + feature: Either an str, integer or ``nn.Module``: + + - an str or integer will indicate the inceptionv3 feature layer to choose. Can be one of the following: + 'logits_unbiased', 64, 192, 768, 2048 + - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns + an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size. + + subsets: Number of subsets to calculate the mean and standard deviation scores over + subset_size: Number of randomly picked samples in each subset + degree: Degree of the polynomial kernel function + gamma: Scale-length of polynomial kernel. If set to ``None`` will be automatically set to the feature size + coef: Bias term in the polynomial kernel. + reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not + change, the features can cached them to avoid recomputing them which is costly. Set this to ``False`` if + your dataset does not change. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``feature`` is set to an ``int`` (default settings) and ``torch-fidelity`` is not installed + ValueError: + If ``feature`` is set to an ``int`` not in ``(64, 192, 768, 2048)`` + ValueError: + If ``subsets`` is not an integer larger than 0 + ValueError: + If ``subset_size`` is not an integer larger than 0 + ValueError: + If ``degree`` is not an integer larger than 0 + ValueError: + If ``gamma`` is neither ``None`` or a float larger than 0 + ValueError: + If ``coef`` is not an float larger than 0 + ValueError: + If ``reset_real_features`` is not an ``bool`` + + Example: + >>> from torch import randint + >>> from torchmetrics.image.kid import KernelInceptionDistance + >>> kid = KernelInceptionDistance(subset_size=50) + >>> # generate two slightly overlapping image intensity distributions + >>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> kid.update(imgs_dist1, real=True) + >>> kid.update(imgs_dist2, real=False) + >>> kid.compute() + (tensor(0.0312), tensor(0.0025)) + + """ + + higher_is_better: bool = False + is_differentiable: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + real_features: List[Tensor] + fake_features: List[Tensor] + inception: Module + feature_network: str = "inception" + + def __init__( + self, + feature: Union[str, int, Module] = 2048, + subsets: int = 100, + subset_size: int = 1000, + degree: int = 3, + gamma: Optional[float] = None, + coef: float = 1.0, + reset_real_features: bool = True, + normalize: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + rank_zero_warn( + "Metric `Kernel Inception Distance` will save all extracted features in buffer." + " For large datasets this may lead to large memory footprint.", + UserWarning, + ) + + self.used_custom_model = False + + if isinstance(feature, (str, int)): + if not _TORCH_FIDELITY_AVAILABLE: + raise ModuleNotFoundError( + "Kernel Inception Distance metric requires that `Torch-fidelity` is installed." + " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`." + ) + valid_int_input = ("logits_unbiased", 64, 192, 768, 2048) + if feature not in valid_int_input: + raise ValueError( + f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}." + ) + + self.inception: Module = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)]) + elif isinstance(feature, Module): + self.inception = feature + self.used_custom_model = True + else: + raise TypeError("Got unknown input to argument `feature`") + + if not (isinstance(subsets, int) and subsets > 0): + raise ValueError("Argument `subsets` expected to be integer larger than 0") + self.subsets = subsets + + if not (isinstance(subset_size, int) and subset_size > 0): + raise ValueError("Argument `subset_size` expected to be integer larger than 0") + self.subset_size = subset_size + + if not (isinstance(degree, int) and degree > 0): + raise ValueError("Argument `degree` expected to be integer larger than 0") + self.degree = degree + + if gamma is not None and not (isinstance(gamma, float) and gamma > 0): + raise ValueError("Argument `gamma` expected to be `None` or float larger than 0") + self.gamma = gamma + + if not (isinstance(coef, float) and coef > 0): + raise ValueError("Argument `coef` expected to be float larger than 0") + self.coef = coef + + if not isinstance(reset_real_features, bool): + raise ValueError("Argument `reset_real_features` expected to be a bool") + self.reset_real_features = reset_real_features + + if not isinstance(normalize, bool): + raise ValueError("Argument `normalize` expected to be a bool") + self.normalize = normalize + + # states for extracted features + self.add_state("real_features", [], dist_reduce_fx=None) + self.add_state("fake_features", [], dist_reduce_fx=None) + + def update(self, imgs: Tensor, real: bool) -> None: + """Update the state with extracted features. + + Args: + imgs: Input img tensors to evaluate. If used custom feature extractor please + make sure dtype and size is correct for the model. + real: Whether given image is real or fake. + + """ + imgs = (imgs * 255).byte() if self.normalize and (not self.used_custom_model) else imgs + features = self.inception(imgs) + + if real: + self.real_features.append(features) + else: + self.fake_features.append(features) + + def compute(self) -> tuple[Tensor, Tensor]: + """Calculate KID score based on accumulated extracted features from the two distributions. + + Implementation inspired by `Fid Score`_ + + Returns: + kid_mean (:class:`~torch.Tensor`): float scalar tensor with mean value over subsets + kid_std (:class:`~torch.Tensor`): float scalar tensor with standard deviation value over subsets + + """ + real_features = dim_zero_cat(self.real_features) + fake_features = dim_zero_cat(self.fake_features) + + n_samples_real = real_features.shape[0] + if n_samples_real < self.subset_size: + raise ValueError("Argument `subset_size` should be smaller than the number of samples") + n_samples_fake = fake_features.shape[0] + if n_samples_fake < self.subset_size: + raise ValueError("Argument `subset_size` should be smaller than the number of samples") + + kid_scores_ = [] + for _ in range(self.subsets): + perm = torch.randperm(n_samples_real) + f_real = real_features[perm[: self.subset_size]] + perm = torch.randperm(n_samples_fake) + f_fake = fake_features[perm[: self.subset_size]] + + o = poly_mmd(f_real, f_fake, self.degree, self.gamma, self.coef) + kid_scores_.append(o) + kid_scores = torch.stack(kid_scores_) + return kid_scores.mean(), kid_scores.std(unbiased=False) + + def reset(self) -> None: + """Reset metric states.""" + if not self.reset_real_features: + # remove temporarily to avoid resetting + value = self._defaults.pop("real_features") + super().reset() + self._defaults["real_features"] = value + else: + super().reset() + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image.kid import KernelInceptionDistance + >>> imgs_dist1 = torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = torch.randint(100, 255, (30, 3, 299, 299), dtype=torch.uint8) + >>> metric = KernelInceptionDistance(subsets=3, subset_size=20) + >>> metric.update(imgs_dist1, real=True) + >>> metric.update(imgs_dist2, real=False) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image.kid import KernelInceptionDistance + >>> imgs_dist1 = lambda: torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = lambda: torch.randint(100, 255, (30, 3, 299, 299), dtype=torch.uint8) + >>> metric = KernelInceptionDistance(subsets=3, subset_size=20) + >>> values = [ ] + >>> for _ in range(3): + ... metric.update(imgs_dist1(), real=True) + ... metric.update(imgs_dist2(), real=False) + ... values.append(metric.compute()[0]) + ... metric.reset() + >>> fig_, ax_ = metric.plot(values) + + """ + val = val or self.compute()[0] # by default we select the mean to plot + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/lpip.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/lpip.py new file mode 100644 index 0000000000000000000000000000000000000000..43a15bd1b0509d957ef44bad03ea0e8aec0decd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/lpip.py @@ -0,0 +1,195 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, ClassVar, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.lpips import _LPIPS, _lpips_compute, _lpips_update, _NoTrainLpips +from torchmetrics.metric import Metric +from torchmetrics.utilities import dim_zero_cat +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCHVISION_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["LearnedPerceptualImagePatchSimilarity.plot"] + +if _TORCHVISION_AVAILABLE: + + def _download_lpips() -> None: + _LPIPS(pretrained=True, net="vgg") + + if _SKIP_SLOW_DOCTEST and not _try_proceed_with_timeout(_download_lpips): + __doctest_skip__ = ["LearnedPerceptualImagePatchSimilarity", "LearnedPerceptualImagePatchSimilarity.plot"] +else: + __doctest_skip__ = ["LearnedPerceptualImagePatchSimilarity", "LearnedPerceptualImagePatchSimilarity.plot"] + + +class LearnedPerceptualImagePatchSimilarity(Metric): + """The Learned Perceptual Image Patch Similarity (`LPIPS_`) calculates perceptual similarity between two images. + + LPIPS essentially computes the similarity between the activations of two image patches for some pre-defined network. + This measure has been shown to match human perception well. A low LPIPS score means that image patches are + perceptual similar. + + Both input image patches are expected to have shape ``(N, 3, H, W)``. The minimum size of `H, W` depends on the + chosen backbone (see `net_type` arg). + + .. hint:: + Using this metrics requires you to have ``torchvision`` package installed. Either install as + ``pip install torchmetrics[image]`` or ``pip install torchvision``. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``img1`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)`` + - ``img2`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``lpips`` (:class:`~torch.Tensor`): returns float scalar tensor with average LPIPS value over samples + + Args: + net_type: str indicating backbone network type to use. Choose between `'alex'`, `'vgg'` or `'squeeze'` + reduction: str indicating how to reduce over the batch dimension. Choose between `'sum'`, `'mean'`,`'none'` + or `None`. + normalize: by default this is ``False`` meaning that the input is expected to be in the [-1,1] range. If set + to ``True`` will instead expect input to be in the ``[0,1]`` range. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ModuleNotFoundError: + If ``torchvision`` package is not installed + ValueError: + If ``net_type`` is not one of ``"vgg"``, ``"alex"`` or ``"squeeze"`` + ValueError: + If ``reduction`` is not one of ``"mean"`` or ``"sum"`` + + Example: + >>> from torch import rand + >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity + >>> lpips = LearnedPerceptualImagePatchSimilarity(net_type='squeeze') + >>> # LPIPS needs the images to be in the [-1, 1] range. + >>> img1 = (rand(10, 3, 100, 100) * 2) - 1 + >>> img2 = (rand(10, 3, 100, 100) * 2) - 1 + >>> lpips(img1, img2) + tensor(0.1024) + + >>> from torch import rand, Generator + >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity + >>> gen = Generator().manual_seed(42) + >>> lpips = LearnedPerceptualImagePatchSimilarity(net_type='squeeze', reduction='none') + >>> # LPIPS needs the images to be in the [-1, 1] range. + >>> img1 = (rand(2, 3, 100, 100, generator=gen) * 2) - 1 + >>> img2 = (rand(2, 3, 100, 100, generator=gen) * 2) - 1 + >>> lpips(img1, img2) + tensor([0.1024, 0.0938]) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + all_scores: list[Tensor] + feature_network: str = "net" + + # due to the use of named tuple in the backbone the net variable cannot be scripted + __jit_ignored_attributes__: ClassVar[list[str]] = ["net"] + + def __init__( + self, + net_type: Literal["vgg", "alex", "squeeze"] = "alex", + reduction: Optional[Literal["sum", "mean", "none"]] = "mean", + normalize: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if not _TORCHVISION_AVAILABLE: + raise ModuleNotFoundError( + "LPIPS metric requires that torchvision is installed." + " Either install as `pip install torchmetrics[image]` or `pip install torchvision`." + ) + + valid_net_type = ("vgg", "alex", "squeeze") + if net_type not in valid_net_type: + raise ValueError(f"Argument `net_type` must be one of {valid_net_type}, but got {net_type}.") + self.net = _NoTrainLpips(net=net_type) + + valid_reduction = ("mean", "sum", "none", None) + if reduction not in valid_reduction: + raise ValueError(f"Argument `reduction` must be one of {valid_reduction}, but got {reduction}") + self.reduction = reduction + + if not isinstance(normalize, bool): + raise ValueError(f"Argument `normalize` should be an bool but got {normalize}") + self.normalize = normalize + + self.add_state("all_scores", default=[], dist_reduce_fx=None) + + def update(self, img1: Tensor, img2: Tensor) -> None: + """Update internal states with lpips score.""" + loss = _lpips_update(img1, img2, net=self.net, normalize=self.normalize) + self.all_scores.append(loss) + + def compute(self) -> Tensor: + """Compute final perceptual similarity metric.""" + scores = dim_zero_cat(self.all_scores) + return _lpips_compute(scores, reduction=self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity + >>> metric = LearnedPerceptualImagePatchSimilarity(net_type='squeeze') + >>> metric.update(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity + >>> metric = LearnedPerceptualImagePatchSimilarity(net_type='squeeze') + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/mifid.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/mifid.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5c9bf8dbc93361780a049c97548b32e9453976 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/mifid.py @@ -0,0 +1,297 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +import torch +from torch import Tensor +from torch.nn import Module + +from torchmetrics.image.fid import NoTrainInceptionV3, _compute_fid +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +__doctest_requires__ = { + ("MemorizationInformedFrechetInceptionDistance", "MemorizationInformedFrechetInceptionDistance.plot"): [ + "torch_fidelity" + ] +} + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MemorizationInformedFrechetInceptionDistance.plot"] + + +def _compute_cosine_distance(features1: Tensor, features2: Tensor, cosine_distance_eps: float = 0.1) -> Tensor: + """Compute the cosine distance between two sets of features.""" + features1_nozero = features1[torch.sum(features1, dim=1) != 0] + features2_nozero = features2[torch.sum(features2, dim=1) != 0] + + # normalize + norm_f1 = features1_nozero / torch.norm(features1_nozero, dim=1, keepdim=True) + norm_f2 = features2_nozero / torch.norm(features2_nozero, dim=1, keepdim=True) + + d = 1.0 - torch.abs(torch.matmul(norm_f1, norm_f2.t())) + mean_min_d = torch.mean(d.min(dim=1).values) + return mean_min_d if mean_min_d < cosine_distance_eps else torch.ones_like(mean_min_d) + + +def _mifid_compute( + mu1: Tensor, + sigma1: Tensor, + features1: Tensor, + mu2: Tensor, + sigma2: Tensor, + features2: Tensor, + cosine_distance_eps: float = 0.1, +) -> Tensor: + """Compute MIFID score given two sets of features and their statistics.""" + fid_value = _compute_fid(mu1, sigma1, mu2, sigma2) + distance = _compute_cosine_distance(features1, features2, cosine_distance_eps) + # secure that very small fid values does not explode the mifid + return fid_value / (distance + 10e-15) if fid_value > 1e-8 else torch.zeros_like(fid_value) + + +class MemorizationInformedFrechetInceptionDistance(Metric): + r"""Calculate Memorization-Informed Frechet Inception Distance (MIFID_). + + MIFID is a improved variation of the Frechet Inception Distance (FID_) that penalizes memorization of the training + set by the generator. It is calculated as + + .. math:: + MIFID = \frac{FID(F_{real}, F_{fake})}{M(F_{real}, F_{fake})} + + where :math:`FID` is the normal FID score and :math:`M` is the memorization penalty. The memorization penalty + essentially corresponds to the average minimum cosine distance between the features of the real and fake + distribution. + + Using the default feature extraction (Inception v3 using the original weights from `fid ref2`_), the input is + expected to be mini-batches of 3-channel RGB images of shape ``(3 x H x W)``. If argument ``normalize`` + is ``True`` images are expected to be dtype ``float`` and have values in the ``[0, 1]`` range, else if + ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]`` + range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian + flag ``real`` determines if the images should update the statistics of the real distribution or the + fake distribution. + + .. hint:: + Using this metrics requires you to have ``scipy`` install. Either install as ``pip install + torchmetrics[image]`` or ``pip install scipy`` + + .. hint:: + Using this metric with the default feature extractor requires that ``torch-fidelity`` + is installed. Either install as ``pip install torchmetrics[image]`` or + ``pip install torch-fidelity`` + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor with + - ``real`` (:class:`~bool`): bool indicating if ``imgs`` belong to the real or the fake distribution + + As output of `forward` and `compute` the metric returns the following output + + - ``mifid`` (:class:`~torch.Tensor`): float scalar tensor with mean MIFID value over samples + + Args: + feature: + Either an integer or ``nn.Module``: + + - an integer will indicate the inceptionv3 feature layer to choose. Can be one of the following: + 64, 192, 768, 2048 + - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns + an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size. + + reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not + change, the features can be cached them to avoid recomputing them which is costly. Set this to ``False`` if + your dataset does not change. + normalize: Whether to normalize the input images. If ``True`` the input is expected to be in the range [0, 1] + and converted to ``uint8``. If ``False`` the input is expected to already be in the range [0, 255] and of + type ``uint8``. If a custom feature extractor is used, this argument is ignored. + cosine_distance_eps: Epsilon value for the cosine distance. If the cosine distance is larger than this value + it is set to 1 and thus ignored in the MIFID calculation. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + RuntimeError: + If ``torch`` is version less than 1.10 + ValueError: + If ``feature`` is set to an ``int`` and ``torch-fidelity`` is not installed + ValueError: + If ``feature`` is set to an ``int`` not in [64, 192, 768, 2048] + TypeError: + If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module`` + ValueError: + If ``reset_real_features`` is not an ``bool`` + + Example:: + >>> from torch import randint + >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance + >>> mifid = MemorizationInformedFrechetInceptionDistance(feature=64) + >>> # generate two slightly overlapping image intensity distributions + >>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> mifid.update(imgs_dist1, real=True) + >>> mifid.update(imgs_dist2, real=False) + >>> mifid.compute() + tensor(3003.3691) + + """ + + higher_is_better: bool = False + is_differentiable: bool = False + full_state_update: bool = False + + real_features: List[Tensor] + fake_features: List[Tensor] + + inception: Module + feature_network: str = "inception" + + def __init__( + self, + feature: Union[int, Module] = 2048, + reset_real_features: bool = True, + normalize: bool = False, + cosine_distance_eps: float = 0.1, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + self.used_custom_model = False + + if isinstance(feature, int): + if not _TORCH_FIDELITY_AVAILABLE: + raise ModuleNotFoundError( + "MemorizationInformedFrechetInceptionDistance metric requires that `Torch-fidelity` is installed." + " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`." + ) + valid_int_input = [64, 192, 768, 2048] + if feature not in valid_int_input: + raise ValueError( + f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}." + ) + + self.inception = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)]) + + elif isinstance(feature, Module): + self.inception = feature + self.used_custom_model = True + else: + raise TypeError("Got unknown input to argument `feature`") + + if not isinstance(reset_real_features, bool): + raise ValueError("Argument `reset_real_features` expected to be a bool") + self.reset_real_features = reset_real_features + + if not isinstance(normalize, bool): + raise ValueError("Argument `normalize` expected to be a bool") + self.normalize = normalize + + if not (isinstance(cosine_distance_eps, float) and 1 >= cosine_distance_eps > 0): + raise ValueError("Argument `cosine_distance_eps` expected to be a float greater than 0 and less than 1") + self.cosine_distance_eps = cosine_distance_eps + + # states for extracted features + self.add_state("real_features", [], dist_reduce_fx=None) + self.add_state("fake_features", [], dist_reduce_fx=None) + + def update(self, imgs: Tensor, real: bool) -> None: + """Update the state with extracted features.""" + imgs = (imgs * 255).byte() if self.normalize and not self.used_custom_model else imgs + features = self.inception(imgs) + self.orig_dtype = features.dtype + features = features.double() + + if real: + self.real_features.append(features) + else: + self.fake_features.append(features) + + def compute(self) -> Tensor: + """Calculate FID score based on accumulated extracted features from the two distributions.""" + real_features = dim_zero_cat(self.real_features) + fake_features = dim_zero_cat(self.fake_features) + + mean_real, mean_fake = torch.mean(real_features, dim=0), torch.mean(fake_features, dim=0) + cov_real, cov_fake = torch.cov(real_features.t()), torch.cov(fake_features.t()) + + return _mifid_compute( + mean_real, + cov_real, + real_features, + mean_fake, + cov_fake, + fake_features, + cosine_distance_eps=self.cosine_distance_eps, + ).to(self.orig_dtype) + + def reset(self) -> None: + """Reset metric states.""" + if not self.reset_real_features: + # remove temporarily to avoid resetting + value = self._defaults.pop("real_features") + super().reset() + self._defaults["real_features"] = value + else: + super().reset() + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance + >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> metric = MemorizationInformedFrechetInceptionDistance(feature=64) + >>> metric.update(imgs_dist1, real=True) + >>> metric.update(imgs_dist2, real=False) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance + >>> imgs_dist1 = lambda: torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) + >>> imgs_dist2 = lambda: torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) + >>> metric = MemorizationInformedFrechetInceptionDistance(feature=64) + >>> values = [ ] + >>> for _ in range(3): + ... metric.update(imgs_dist1(), real=True) + ... metric.update(imgs_dist2(), real=False) + ... values.append(metric.compute()) + ... metric.reset() + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/perceptual_path_length.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/perceptual_path_length.py new file mode 100644 index 0000000000000000000000000000000000000000..5c48b57c3fefb7911d372d7ad14b8132777dc179 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/perceptual_path_length.py @@ -0,0 +1,182 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Literal, Optional, Union + +from torch import Tensor, nn + +from torchmetrics.functional.image.lpips import _LPIPS +from torchmetrics.functional.image.perceptual_path_length import ( + GeneratorType, + _perceptual_path_length_validate_arguments, + _validate_generator_model, + perceptual_path_length, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _TORCHVISION_AVAILABLE + +if not _TORCHVISION_AVAILABLE: + __doctest_skip__ = ["PerceptualPathLength"] + + +class PerceptualPathLength(Metric): + r"""Computes the perceptual path length (`PPL`_) of a generator model. + + The perceptual path length can be used to measure the consistency of interpolation in latent-space models. It is + defined as + + .. math:: + PPL = \mathbb{E}\left[\frac{1}{\epsilon^2} D(G(I(z_1, z_2, t)), G(I(z_1, z_2, t+\epsilon)))\right] + + where :math:`G` is the generator, :math:`I` is the interpolation function, :math:`D` is a similarity metric, + :math:`z_1` and :math:`z_2` are two sets of latent points, and :math:`t` is a parameter between 0 and 1. The metric + thus works by interpolating between two sets of latent points, and measuring the similarity between the generated + images. The expectation is approximated by sampling :math:`z_1` and :math:`z_2` from the generator, and averaging + the calculated distanced. The similarity metric :math:`D` is by default the `LPIPS`_ metric, but can be changed by + setting the `sim_net` argument. + + The provided generator model must have a `sample` method with signature `sample(num_samples: int) -> Tensor` where + the returned tensor has shape `(num_samples, z_size)`. If the generator is conditional, it must also have a + `num_classes` attribute. The `forward` method of the generator must have signature `forward(z: Tensor) -> Tensor` + if `conditional=False`, and `forward(z: Tensor, labels: Tensor) -> Tensor` if `conditional=True`. The returned + tensor should have shape `(num_samples, C, H, W)` and be scaled to the range [0, 255]. + + .. hint:: + Using this metric with the default feature extractor requires that ``torchvision`` is installed. + Either install as ``pip install torchmetrics[image]`` or ``pip install torchvision`` + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``generator`` (:class:`~torch.nn.Module`): Generator model, with specific requirements. See above. + + As output of `forward` and `compute` the metric returns the following output + + - ``ppl_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean PPL value over distances + - ``ppl_std`` (:class:`~torch.Tensor`): float scalar tensor with std PPL value over distances + - ``ppl_raw`` (:class:`~torch.Tensor`): float scalar tensor with raw PPL distances + + Args: + num_samples: Number of samples to use for the PPL computation. + conditional: Whether the generator is conditional or not (i.e. whether it takes labels as input). + batch_size: Batch size to use for the PPL computation. + interpolation_method: Interpolation method to use. Choose from 'lerp', 'slerp_any', 'slerp_unit'. + epsilon: Spacing between the points on the path between latent points. + resize: Resize images to this size before computing the similarity between generated images. + lower_discard: Lower quantile to discard from the distances, before computing the mean and standard deviation. + upper_discard: Upper quantile to discard from the distances, before computing the mean and standard deviation. + sim_net: Similarity network to use. Can be a `nn.Module` or one of 'alex', 'vgg', 'squeeze', where the three + latter options correspond to the pretrained networks from the `LPIPS`_ paper. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ModuleNotFoundError: + If ``torch-fidelity`` is not installed. + ValueError: + If ``num_samples`` is not a positive integer. + ValueError: + If `conditional` is not a boolean. + ValueError: + If ``batch_size`` is not a positive integer. + ValueError: + If ``interpolation_method`` is not one of 'lerp', 'slerp_any', 'slerp_unit'. + ValueError: + If ``epsilon`` is not a positive float. + ValueError: + If ``resize`` is not a positive integer. + ValueError: + If ``lower_discard`` is not a float between 0 and 1 or None. + ValueError: + If ``upper_discard`` is not a float between 0 and 1 or None. + + Example:: + >>> import torch + >>> class DummyGenerator(torch.nn.Module): + ... def __init__(self, z_size) -> None: + ... super().__init__() + ... self.z_size = z_size + ... self.model = torch.nn.Sequential(torch.nn.Linear(z_size, 3*128*128), torch.nn.Sigmoid()) + ... def forward(self, z): + ... return 255 * (self.model(z).reshape(-1, 3, 128, 128) + 1) + ... def sample(self, num_samples): + ... return torch.randn(num_samples, self.z_size) + >>> generator = DummyGenerator(2) + >>> ppl = PerceptualPathLength(num_samples=10) + >>> ppl(generator) + (tensor(...), tensor(...), tensor([...])) + + """ + + is_differentiable: bool = False + higher_is_better: Optional[bool] = True + full_state_update: bool = True + + net: nn.Module + feature_network: str = "net" + + def __init__( + self, + num_samples: int = 10_000, + conditional: bool = False, + batch_size: int = 128, + interpolation_method: Literal["lerp", "slerp_any", "slerp_unit"] = "lerp", + epsilon: float = 1e-4, + resize: Optional[int] = 64, + lower_discard: Optional[float] = 0.01, + upper_discard: Optional[float] = 0.99, + sim_net: Union[nn.Module, Literal["alex", "vgg", "squeeze"]] = "vgg", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not _TORCHVISION_AVAILABLE: + raise ModuleNotFoundError( + "Metric `PerceptualPathLength` requires torchvision which is not installed." + "Install with `pip install torchvision` or `pip install torchmetrics[image]`" + ) + _perceptual_path_length_validate_arguments( + num_samples, conditional, batch_size, interpolation_method, epsilon, resize, lower_discard, upper_discard + ) + self.num_samples = num_samples + self.conditional = conditional + self.batch_size = batch_size + self.interpolation_method = interpolation_method + self.epsilon = epsilon + self.resize = resize + self.lower_discard = lower_discard + self.upper_discard = upper_discard + + if isinstance(sim_net, nn.Module): + self.net = sim_net + elif sim_net in ["alex", "vgg", "squeeze"]: + self.net = _LPIPS(pretrained=True, net=sim_net, resize=resize) + else: + raise ValueError(f"sim_net must be a nn.Module or one of 'alex', 'vgg', 'squeeze', got {sim_net}") + + def update(self, generator: GeneratorType) -> None: + """Update the generator model.""" + _validate_generator_model(generator, self.conditional) + self.generator = generator + + def compute(self) -> tuple[Tensor, Tensor, Tensor]: + """Compute the perceptual path length.""" + return perceptual_path_length( + generator=self.generator, + num_samples=self.num_samples, + conditional=self.conditional, + interpolation_method=self.interpolation_method, + epsilon=self.epsilon, + resize=self.resize, + lower_discard=self.lower_discard, + upper_discard=self.upper_discard, + sim_net=self.net, + device=self.device, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/psnr.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/psnr.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c33fcb5c1f79d4b5da9788ac24cf3154527d78 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/psnr.py @@ -0,0 +1,201 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from functools import partial +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.psnr import _psnr_compute, _psnr_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["PeakSignalNoiseRatio.plot"] + + +class PeakSignalNoiseRatio(Metric): + r"""`Compute Peak Signal-to-Noise Ratio`_ (PSNR). + + .. math:: \text{PSNR}(I, J) = 10 * \log_{10} \left(\frac{\max(I)^2}{\text{MSE}(I, J)}\right) + + Where :math:`\text{MSE}` denotes the `mean-squared-error`_ function. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``psnr`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average PSNR value + over sample else returns tensor of shape ``(N,)`` with PSNR values per sample + + Args: + data_range: + the range of the data. If a tuple is provided, then the range is calculated as the difference and + input is clamped between the values. + base: a base of a logarithm to use. + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + dim: + Dimensions to reduce PSNR scores over, provided as either an integer or a list of integers. Default is + None meaning scores will be reduced across all dimensions and all batches. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.image import PeakSignalNoiseRatio + >>> psnr = PeakSignalNoiseRatio(data_range=3.0) + >>> preds = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) + >>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]]) + >>> psnr(preds, target) + tensor(2.5527) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + data_range: Tensor + + def __init__( + self, + data_range: Union[float, tuple[float, float]], + base: float = 10.0, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + dim: Optional[Union[int, tuple[int, ...]]] = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if dim is None and reduction != "elementwise_mean": + rank_zero_warn(f"The `reduction={reduction}` will not have any effect when `dim` is None.") + + if dim is None: + self.add_state("sum_squared_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0), dist_reduce_fx="sum") + else: + self.add_state("sum_squared_error", default=[], dist_reduce_fx="cat") + self.add_state("total", default=[], dist_reduce_fx="cat") + + self.clamping_fn = None + if isinstance(data_range, tuple): + self.add_state("data_range", default=tensor(data_range[1] - data_range[0]), dist_reduce_fx="mean") + self.clamping_fn = partial(torch.clamp, min=data_range[0], max=data_range[1]) + else: + self.add_state("data_range", default=tensor(float(data_range)), dist_reduce_fx="mean") + + self.base = base + self.reduction = reduction + self.dim = tuple(dim) if isinstance(dim, Sequence) else dim + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + if self.clamping_fn is not None: + preds = self.clamping_fn(preds) + target = self.clamping_fn(target) + + sum_squared_error, num_obs = _psnr_update(preds, target, dim=self.dim) + if self.dim is None: + if not isinstance(self.sum_squared_error, Tensor): + raise TypeError( + f"Expected `self.sum_squared_error` to be a Tensor, but got {type(self.sum_squared_error)}" + ) + if not isinstance(self.total, Tensor): + raise TypeError(f"Expected `self.total` to be a Tensor, but got {type(self.total)}") + + self.sum_squared_error += sum_squared_error + self.total += num_obs + else: + if not isinstance(self.sum_squared_error, list): + raise TypeError( + f"Expected `self.sum_squared_error` to be a list, but got {type(self.sum_squared_error)}" + ) + if not isinstance(self.total, list): + raise TypeError(f"Expected `self.total` to be a list, but got {type(self.total)}") + self.sum_squared_error.append(sum_squared_error) + self.total.append(num_obs) + + def compute(self) -> Tensor: + """Compute peak signal-to-noise ratio over state.""" + if isinstance(self.sum_squared_error, torch.Tensor): + sum_squared_error = self.sum_squared_error + elif isinstance(self.sum_squared_error, list): + sum_squared_error = torch.cat([value.flatten() for value in self.sum_squared_error]) + else: + raise TypeError("Expected sum_squared_error to be a Tensor or a list of Tensors") + + if isinstance(self.total, torch.Tensor): + total = self.total + elif isinstance(self.total, list): + total = torch.cat([value.flatten() for value in self.total]) + else: + raise TypeError("Expected total to be a Tensor or a list of Tensors") + + return _psnr_compute(sum_squared_error, total, self.data_range, base=self.base, reduction=self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image import PeakSignalNoiseRatio + >>> metric = PeakSignalNoiseRatio(data_range=1.0) + >>> preds = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) + >>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]]) + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image import PeakSignalNoiseRatio + >>> metric = PeakSignalNoiseRatio(data_range=1.0) + >>> preds = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) + >>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]]) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/psnrb.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/psnrb.py new file mode 100644 index 0000000000000000000000000000000000000000..25fa99bbd5cf43470057eaac399046291e5660c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/psnrb.py @@ -0,0 +1,152 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.image.psnrb import _psnrb_compute, _psnrb_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["PeakSignalNoiseRatioWithBlockedEffect.plot"] + + +class PeakSignalNoiseRatioWithBlockedEffect(Metric): + r"""Computes `Peak Signal to Noise Ratio With Blocked Effect`_ (PSNRB). + + .. math:: + \text{PSNRB}(I, J) = 10 * \log_{10} \left(\frac{\max(I)^2}{\text{MSE}(I, J)-\text{B}(I, J)}\right) + + Where :math:`\text{MSE}` denotes the `mean-squared-error`_ function. This metric is a modified version of PSNR that + better supports evaluation of images with blocked artifacts, that oftens occur in compressed images. + + .. attention:: + Metric only supports grayscale images. If you have RGB images, please convert them to grayscale first. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,1,H,W)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,1,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``psnrb`` (:class:`~torch.Tensor`): float scalar tensor with aggregated PSNRB value + + Args: + data_range: the range of the data. If a tuple is provided then the range is calculated as the difference and + input is clamped between the values. + block_size: integer indication the block size + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import rand + >>> metric = PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0) + >>> preds = rand(2, 1, 10, 10) + >>> target = rand(2, 1, 10, 10) + >>> metric(preds, target) + tensor(7.2893) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = False + + sum_squared_error: Tensor + total: Tensor + bef: Tensor + data_range: Tensor + + def __init__( + self, + data_range: Union[float, tuple[float, float]], + block_size: int = 8, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(block_size, int) and block_size < 1: + raise ValueError("Argument ``block_size`` should be a positive integer") + self.block_size = block_size + + self.add_state("sum_squared_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0), dist_reduce_fx="sum") + self.add_state("bef", default=tensor(0.0), dist_reduce_fx="sum") + + if isinstance(data_range, tuple): + self.add_state("data_range", default=tensor(data_range[1] - data_range[0]), dist_reduce_fx="mean") + self.clamping_fn = lambda x: torch.clamp(x, min=data_range[0], max=data_range[1]) + else: + self.add_state("data_range", default=tensor(float(data_range)), dist_reduce_fx="mean") + self.clamping_fn = None # type: ignore[assignment] + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + if self.clamping_fn is not None: + preds = self.clamping_fn(preds) + target = self.clamping_fn(target) + + sum_squared_error, bef, num_obs = _psnrb_update(preds, target, block_size=self.block_size) + self.sum_squared_error += sum_squared_error + self.bef += bef + self.total += num_obs + + def compute(self) -> Tensor: + """Compute peak signal-to-noise ratio over state.""" + return _psnrb_compute(self.sum_squared_error, self.bef, self.total, self.data_range) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image import PeakSignalNoiseRatioWithBlockedEffect + >>> metric = PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0) + >>> metric.update(torch.rand(2, 1, 10, 10), torch.rand(2, 1, 10, 10)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image import PeakSignalNoiseRatioWithBlockedEffect + >>> metric = PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.rand(2, 1, 10, 10), torch.rand(2, 1, 10, 10))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/qnr.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/qnr.py new file mode 100644 index 0000000000000000000000000000000000000000..f28e61b2fbf2e238bbc59e84719dd7da4fb3b557 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/qnr.py @@ -0,0 +1,227 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.d_lambda import _spectral_distortion_index_compute, _spectral_distortion_index_update +from torchmetrics.functional.image.d_s import _spatial_distortion_index_compute, _spatial_distortion_index_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCHVISION_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["QualityWithNoReference.plot"] + +if not _TORCHVISION_AVAILABLE: + __doctest_skip__ = ["QualityWithNoReference", "QualityWithNoReference.plot"] + + +class QualityWithNoReference(Metric): + """Compute Quality with No Reference (QualityWithNoReference_) also now as QNR. + + The metric is used to compare the joint spectral and spatial distortion between two images. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): High resolution multispectral image of shape ``(N,C,H,W)``. + - ``target`` (:class:`~Dict`): A dictionary containing the following keys: + + - ``ms`` (:class:`~torch.Tensor`): Low resolution multispectral image of shape ``(N,C,H',W')``. + - ``pan`` (:class:`~torch.Tensor`): High resolution panchromatic image of shape ``(N,C,H,W)``. + - ``pan_lr`` (:class:`~torch.Tensor`): (optional) Low resolution panchromatic image of shape ``(N,C,H',W')``. + + where H and W must be multiple of H' and W'. + + When ``pan_lr`` is ``None``, a uniform filter will be applied on ``pan`` to produce a degraded image. The degraded + image is then resized to match the size of ``ms`` and served as ``pan_lr`` in the calculation. + + As output of `forward` and `compute` the metric returns the following output + + - ``qnr`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average QNR value + over sample else returns tensor of shape ``(N,)`` with QNR values per sample + + Args: + alpha: Relevance of spectral distortion. + beta: Relevance of spatial distortion. + norm_order: Order of the norm applied on the difference. + window_size: Window size of the filter applied to degrade the high resolution panchromatic image. + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'``: no reduction will be applied + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import rand + >>> from torchmetrics.image import QualityWithNoReference + >>> preds = rand([16, 3, 32, 32]) + >>> target = { + ... 'ms': rand([16, 3, 16, 16]), + ... 'pan': rand([16, 3, 32, 32]), + ... } + >>> qnr = QualityWithNoReference() + >>> qnr(preds, target) + tensor(0.9694) + + """ + + higher_is_better: bool = True + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + ms: List[Tensor] + pan: List[Tensor] + pan_lr: List[Tensor] + + def __init__( + self, + alpha: float = 1, + beta: float = 1, + norm_order: int = 1, + window_size: int = 7, + reduction: Literal["elementwise_mean", "sum", "none"] = "elementwise_mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + rank_zero_warn( + "Metric `QualityWithNoReference` will save all targets and predictions in buffer." + " For large datasets this may lead to large memory footprint." + ) + + if not isinstance(alpha, (int, float)) or alpha < 0: + raise ValueError(f"Expected `alpha` to be a non-negative real number. Got alpha: {alpha}.") + self.alpha = alpha + if not isinstance(beta, (int, float)) or beta < 0: + raise ValueError(f"Expected `beta` to be a non-negative real number. Got beta: {beta}.") + self.beta = beta + if not isinstance(norm_order, int) or norm_order <= 0: + raise ValueError(f"Expected `norm_order` to be a positive integer. Got norm_order: {norm_order}.") + self.norm_order = norm_order + if not isinstance(window_size, int) or window_size <= 0: + raise ValueError(f"Expected `window_size` to be a positive integer. Got window_size: {window_size}.") + self.window_size = window_size + allowed_reductions = ("elementwise_mean", "sum", "none") + if reduction not in allowed_reductions: + raise ValueError(f"Expected argument `reduction` be one of {allowed_reductions} but got {reduction}") + self.reduction = reduction + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("ms", default=[], dist_reduce_fx="cat") + self.add_state("pan", default=[], dist_reduce_fx="cat") + self.add_state("pan_lr", default=[], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: dict[str, Tensor]) -> None: + """Update state with preds and target. + + Args: + preds: High resolution multispectral image. + target: A dictionary containing the following keys: + + - ``'ms'``: low resolution multispectral image. + - ``'pan'``: high resolution panchromatic image. + - ``'pan_lr'``: (optional) low resolution panchromatic image. + + Raises: + ValueError: + If ``target`` doesn't have ``ms`` and ``pan``. + + """ + if "ms" not in target: + raise ValueError(f"Expected `target` to have key `ms`. Got target: {target.keys()}.") + if "pan" not in target: + raise ValueError(f"Expected `target` to have key `pan`. Got target: {target.keys()}.") + ms = target["ms"] + pan = target["pan"] + pan_lr = target.get("pan_lr") + preds, ms = _spectral_distortion_index_update(preds, ms) + preds, ms, pan, pan_lr = _spatial_distortion_index_update(preds, ms, pan, pan_lr) + self.preds.append(preds) + self.ms.append(target["ms"]) + self.pan.append(target["pan"]) + if "pan_lr" in target: + self.pan_lr.append(target["pan_lr"]) + + def compute(self) -> Tensor: + """Compute and returns quality with no reference.""" + preds = dim_zero_cat(self.preds) + ms = dim_zero_cat(self.ms) + pan = dim_zero_cat(self.pan) + pan_lr = dim_zero_cat(self.pan_lr) if len(self.pan_lr) > 0 else None + d_lambda = _spectral_distortion_index_compute(preds, ms, self.norm_order, self.reduction) + d_s = _spatial_distortion_index_compute( + preds, ms, pan, pan_lr, self.norm_order, self.window_size, self.reduction + ) + return (1 - d_lambda) ** self.alpha * (1 - d_s) ** self.beta + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torch import rand + >>> from torchmetrics.image import QualityWithNoReference + >>> preds = rand([16, 3, 32, 32]) + >>> target = { + ... 'ms': rand([16, 3, 16, 16]), + ... 'pan': rand([16, 3, 32, 32]), + ... } + >>> metric = QualityWithNoReference() + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import rand + >>> from torchmetrics.image import QualityWithNoReference + >>> preds = rand([16, 3, 32, 32]) + >>> target = { + ... 'ms': rand([16, 3, 16, 16]), + ... 'pan': rand([16, 3, 32, 32]), + ... } + >>> metric = QualityWithNoReference() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/rase.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/rase.py new file mode 100644 index 0000000000000000000000000000000000000000..26ecdccfac292c3d2418a1c133352e435f7f5ac1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/rase.py @@ -0,0 +1,135 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor + +from torchmetrics.functional.image.rase import relative_average_spectral_error +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RelativeAverageSpectralError.plot"] + + +class RelativeAverageSpectralError(Metric): + """Computes Relative Average Spectral Error (RASE) (RelativeAverageSpectralError_). + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``rase`` (:class:`~torch.Tensor`): returns float scalar tensor with average RASE value over sample + + Args: + window_size: Sliding window used for rmse calculation + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Return: + Relative Average Spectral Error (RASE) + + Example: + >>> from torch import rand + >>> preds = rand(4, 3, 16, 16) + >>> target = rand(4, 3, 16, 16) + >>> rase = RelativeAverageSpectralError() + >>> rase(preds, target) + tensor(5326.40...) + + Raises: + ValueError: If ``window_size`` is not a positive integer. + + """ + + higher_is_better: bool = False + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + window_size: int = 8, + **kwargs: dict[str, Any], + ) -> None: + super().__init__(**kwargs) + + if not isinstance(window_size, int) or (isinstance(window_size, int) and window_size < 1): + raise ValueError(f"Argument `window_size` is expected to be a positive integer, but got {window_size}") + self.window_size = window_size + + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("target", default=[], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + self.preds.append(preds) + self.target.append(target) + + def compute(self) -> Tensor: + """Compute Relative Average Spectral Error (RASE).""" + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + return relative_average_spectral_error(preds, target, self.window_size) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image import RelativeAverageSpectralError + >>> metric = RelativeAverageSpectralError() + >>> metric.update(torch.rand(4, 3, 16, 16), torch.rand(4, 3, 16, 16)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import rand + >>> from torchmetrics.image import RelativeAverageSpectralError + >>> metric = RelativeAverageSpectralError() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(rand(4, 3, 16, 16), rand(4, 3, 16, 16))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/rmse_sw.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/rmse_sw.py new file mode 100644 index 0000000000000000000000000000000000000000..032705e66a870f3876ae0ba164b960f52a690c08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/rmse_sw.py @@ -0,0 +1,138 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.image.rmse_sw import _rmse_sw_compute, _rmse_sw_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RootMeanSquaredErrorUsingSlidingWindow.plot"] + + +class RootMeanSquaredErrorUsingSlidingWindow(Metric): + """Computes Root Mean Squared Error (RMSE) using sliding window. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``rmse_sw`` (:class:`~torch.Tensor`): returns float scalar tensor with average RMSE-SW value over sample + + Args: + window_size: Sliding window used for rmse calculation + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import rand + >>> from torchmetrics.image import RootMeanSquaredErrorUsingSlidingWindow + >>> preds = rand(4, 3, 16, 16) + >>> target = rand(4, 3, 16, 16) + >>> rmse_sw = RootMeanSquaredErrorUsingSlidingWindow() + >>> rmse_sw(preds, target) + tensor(0.4158) + + Raises: + ValueError: If ``window_size`` is not a positive integer. + + """ + + higher_is_better: bool = False + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + rmse_val_sum: Tensor + rmse_map: Optional[Tensor] = None + total_images: Tensor + + def __init__( + self, + window_size: int = 8, + **kwargs: dict[str, Any], + ) -> None: + super().__init__(**kwargs) + if not isinstance(window_size, int) or (isinstance(window_size, int) and window_size < 1): + raise ValueError("Argument `window_size` is expected to be a positive integer.") + self.window_size = window_size + + self.add_state("rmse_val_sum", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("total_images", default=torch.tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + if self.rmse_map is None: + _img_shape = target.shape[1:] # channels, width, height + self.rmse_map = torch.zeros(_img_shape, dtype=target.dtype, device=target.device) + + self.rmse_val_sum, self.rmse_map, self.total_images = _rmse_sw_update( + preds, target, self.window_size, self.rmse_val_sum, self.rmse_map, self.total_images + ) + + def compute(self) -> Optional[Tensor]: + """Compute Root Mean Squared Error (using sliding window) and potentially return RMSE map.""" + assert self.rmse_map is not None # noqa: S101 # needed for mypy + rmse, _ = _rmse_sw_compute(self.rmse_val_sum, self.rmse_map, self.total_images) + return rmse + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image import RootMeanSquaredErrorUsingSlidingWindow + >>> metric = RootMeanSquaredErrorUsingSlidingWindow() + >>> metric.update(torch.rand(4, 3, 16, 16), torch.rand(4, 3, 16, 16)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image import RootMeanSquaredErrorUsingSlidingWindow + >>> metric = RootMeanSquaredErrorUsingSlidingWindow() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.rand(4, 3, 16, 16), torch.rand(4, 3, 16, 16))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/sam.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/sam.py new file mode 100644 index 0000000000000000000000000000000000000000..b313158f80b07bed157c87f28f39c7698ee066de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/sam.py @@ -0,0 +1,167 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.sam import _sam_compute, _sam_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["SpectralAngleMapper.plot"] + + +class SpectralAngleMapper(Metric): + """`Spectral Angle Mapper`_ determines the spectral similarity between image spectra and reference spectra. + + It works by calculating the angle between the spectra, where small angles between indicate high similarity and + high angles indicate low similarity. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``sam`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average SAM value + over sample else returns tensor of shape ``(N,)`` with SAM values per sample + + Args: + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Return: + Tensor with SpectralAngleMapper score + + Example: + >>> from torch import rand + >>> from torchmetrics.image import SpectralAngleMapper + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> sam = SpectralAngleMapper() + >>> sam(preds, target) + tensor(0.5914) + + """ + + higher_is_better: bool = False + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + sum_sam: Tensor + numel: Tensor + + def __init__( + self, + reduction: Optional[Literal["elementwise_mean", "sum", "none"]] = "elementwise_mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if reduction not in ("elementwise_mean", "sum", "none", None): + raise ValueError( + f"The `reduction` {reduction} is not valid. Valid options are `elementwise_mean`, `sum`, `none`, None." + ) + if reduction == "none" or reduction is None: + rank_zero_warn( + "Metric `SpectralAngleMapper` will save all targets and predictions in the buffer when using" + "`reduction=None` or `reduction='none'. For large datasets, this may lead to a large memory footprint." + ) + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("target", default=[], dist_reduce_fx="cat") + else: + self.add_state("sum_sam", tensor(0.0), dist_reduce_fx="sum") + self.add_state("numel", tensor(0), dist_reduce_fx="sum") + self.reduction = reduction + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + preds, target = _sam_update(preds, target) + if self.reduction == "none" or self.reduction is None: + self.preds.append(preds) + self.target.append(target) + else: + sam_score = _sam_compute(preds, target, reduction="sum") + self.sum_sam += sam_score + p_shape = preds.shape + self.numel += p_shape[0] * p_shape[2] * p_shape[3] + + def compute(self) -> Tensor: + """Compute spectra over state.""" + if self.reduction == "none" or self.reduction is None: + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + return _sam_compute(preds, target, self.reduction) + return self.sum_sam / self.numel if self.reduction == "elementwise_mean" else self.sum_sam + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting single value + >>> from torch import rand + >>> from torchmetrics.image import SpectralAngleMapper + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> metric = SpectralAngleMapper() + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import rand + >>> from torchmetrics.image import SpectralAngleMapper + >>> preds = rand([16, 3, 16, 16]) + >>> target = rand([16, 3, 16, 16]) + >>> metric = SpectralAngleMapper() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/scc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/scc.py new file mode 100644 index 0000000000000000000000000000000000000000..fac28658f63a0036d4510601e9045f9dccac69a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/scc.py @@ -0,0 +1,83 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.image.scc import _scc_per_channel_compute as _scc_compute +from torchmetrics.functional.image.scc import _scc_update +from torchmetrics.metric import Metric + + +class SpatialCorrelationCoefficient(Metric): + """Compute Spatial Correlation Coefficient (SCC_). + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` or ``(N,H,W)``. + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` or ``(N,H,W)``. + + As output of `forward` and `compute` the metric returns the following output + + - ``scc`` (:class:`~torch.Tensor`): Tensor with scc score + + Args: + hp_filter: High-pass filter tensor. default: tensor([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]). + window_size: Local window size integer. default: 8. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import randn + >>> from torchmetrics.image import SpatialCorrelationCoefficient as SCC + >>> preds = randn([32, 3, 64, 64]) + >>> target = randn([32, 3, 64, 64]) + >>> scc = SCC() + >>> scc(preds, target) + tensor(0.0023) + + """ + + is_differentiable = True + higher_is_better = True + full_state_update = False + + scc_score: Tensor + total: Tensor + + def __init__(self, high_pass_filter: Optional[Tensor] = None, window_size: int = 8, **kwargs: Any) -> None: + super().__init__(**kwargs) + + if high_pass_filter is None: + high_pass_filter = tensor([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]) + + self.hp_filter = high_pass_filter + self.ws = window_size + + self.add_state("scc_score", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + preds, target, hp_filter = _scc_update(preds, target, self.hp_filter, self.ws) + scc_per_channel = [ + _scc_compute(preds[:, i, :, :].unsqueeze(1), target[:, i, :, :].unsqueeze(1), hp_filter, self.ws) + for i in range(preds.size(1)) + ] + self.scc_score += torch.sum(torch.mean(torch.cat(scc_per_channel, dim=1), dim=[1, 2, 3])) + self.total += preds.size(0) + + def compute(self) -> Tensor: + """Compute the VIF score based on inputs passed in to ``update`` previously.""" + return self.scc_score / self.total diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/ssim.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/ssim.py new file mode 100644 index 0000000000000000000000000000000000000000..6eab4eecfaa9e34a30953cc9dc5148eebc8bc50b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/ssim.py @@ -0,0 +1,453 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.ssim import _multiscale_ssim_update, _ssim_check_inputs, _ssim_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["StructuralSimilarityIndexMeasure.plot", "MultiScaleStructuralSimilarityIndexMeasure.plot"] + + +class StructuralSimilarityIndexMeasure(Metric): + """Compute Structural Similarity Index Measure (SSIM_). + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of `forward` and `compute` the metric returns the following output + + - ``ssim`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average SSIM value + over sample else returns tensor of shape ``(N,)`` with SSIM values per sample + + Args: + preds: estimated image + target: ground truth image + gaussian_kernel: If ``True`` (default), a gaussian kernel is used, if ``False`` a uniform kernel is used + sigma: Standard deviation of the gaussian kernel, anisotropic kernels are possible. + Ignored if a uniform kernel is used + kernel_size: the size of the uniform kernel, anisotropic kernels are possible. + Ignored if a Gaussian kernel is used + reduction: a method to reduce metric score over individual batch scores + + - ``'elementwise_mean'``: takes the mean + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + data_range: + the range of the data. If None, it is determined from the data (max - min). If a tuple is provided then + the range is calculated as the difference and input is clamped between the values. + k1: Parameter of SSIM. + k2: Parameter of SSIM. + return_full_image: If true, the full ``ssim`` image is returned as a second argument. + Mutually exclusive with ``return_contrast_sensitivity`` + return_contrast_sensitivity: If true, the constant term is returned as a second argument. + The luminance term can be obtained with luminance=ssim/contrast + Mutually exclusive with ``return_full_image`` + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> import torch + >>> from torchmetrics.image import StructuralSimilarityIndexMeasure + >>> preds = torch.rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> ssim = StructuralSimilarityIndexMeasure(data_range=1.0) + >>> ssim(preds, target) + tensor(0.9219) + + """ + + higher_is_better: bool = True + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + gaussian_kernel: bool = True, + sigma: Union[float, Sequence[float]] = 1.5, + kernel_size: Union[int, Sequence[int]] = 11, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + return_full_image: bool = False, + return_contrast_sensitivity: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + valid_reduction = ("elementwise_mean", "sum", "none", None) + if reduction not in valid_reduction: + raise ValueError(f"Argument `reduction` must be one of {valid_reduction}, but got {reduction}") + + if reduction in ("elementwise_mean", "sum"): + self.add_state("similarity", default=torch.tensor(0.0), dist_reduce_fx="sum") + else: + self.add_state("similarity", default=[], dist_reduce_fx=None) + + self.add_state("total", default=torch.tensor(0.0), dist_reduce_fx="sum") + + if return_contrast_sensitivity or return_full_image: + self.add_state("image_return", default=[], dist_reduce_fx="cat") + + self.gaussian_kernel = gaussian_kernel + self.sigma = sigma + self.kernel_size = kernel_size + self.reduction = reduction + self.data_range = data_range + self.k1 = k1 + self.k2 = k2 + self.return_full_image = return_full_image + self.return_contrast_sensitivity = return_contrast_sensitivity + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + preds, target = _ssim_check_inputs(preds, target) + similarity_pack = _ssim_update( + preds, + target, + self.gaussian_kernel, + self.sigma, + self.kernel_size, + self.data_range, + self.k1, + self.k2, + self.return_full_image, + self.return_contrast_sensitivity, + ) + + if isinstance(similarity_pack, tuple): + similarity, image = similarity_pack + else: + similarity = similarity_pack + + if self.return_contrast_sensitivity or self.return_full_image: + if not isinstance(self.image_return, list): + raise TypeError("Expected `self.image_return` to be a list when returning images.") + self.image_return.append(image) + + if self.reduction in ("elementwise_mean", "sum"): + if not isinstance(self.similarity, torch.Tensor): # Ensure it's a Tensor + raise TypeError("Expected `self.similarity` to be a Tensor for reductions.") + self.similarity += similarity.sum() + if not isinstance(self.total, torch.Tensor): + raise TypeError("Expected `self.total` to be a Tensor.") + self.total += preds.shape[0] + else: + if not isinstance(self.similarity, list): + raise TypeError("Expected `self.similarity` to be a list when reduction='none'.") + self.similarity.append(similarity) + + def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Compute SSIM over state.""" + if self.reduction == "elementwise_mean": + if isinstance(self.similarity, Tensor) and isinstance(self.total, Tensor): + similarity = self.similarity / self.total + else: + raise TypeError( + "Expected `self.similarity`and `self.total` to be of type Tensor for elementwise_mean reduction." + ) + elif self.reduction == "sum": + if not isinstance(self.similarity, Tensor): + raise TypeError("Expected `self.similarity` to be a Tensor for sum reduction.") + similarity = self.similarity + else: + if isinstance(self.similarity, list): + similarity = dim_zero_cat(self.similarity) # Concatenate list of Tensors + else: + raise TypeError("Expected `self.similarity` to be a list for reduction='none'.") + + if self.return_contrast_sensitivity or self.return_full_image: + if isinstance(self.image_return, list): + image_return = dim_zero_cat(self.image_return) # Concatenate list of Tensors + else: + raise TypeError("Expected `self.image_return` to be a list when returning images.") + return similarity, image_return + + return similarity + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image import StructuralSimilarityIndexMeasure + >>> preds = torch.rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> metric = StructuralSimilarityIndexMeasure(data_range=1.0) + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image import StructuralSimilarityIndexMeasure + >>> preds = torch.rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> metric = StructuralSimilarityIndexMeasure(data_range=1.0) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) + + +class MultiScaleStructuralSimilarityIndexMeasure(Metric): + """Compute `MultiScaleSSIM`_, Multi-scale Structural Similarity Index Measure. + + This metric is is a generalization of Structural Similarity Index Measure by incorporating image details at + different resolution scores. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of `forward` and `compute` the metric returns the following output + + - ``msssim`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average MSSSIM + value over sample else returns tensor of shape ``(N,)`` with SSIM values per sample + + Args: + gaussian_kernel: If ``True`` (default), a gaussian kernel is used, if false a uniform kernel is used + kernel_size: size of the gaussian kernel + sigma: Standard deviation of the gaussian kernel + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + data_range: + the range of the data. If None, it is determined from the data (max - min). If a tuple is provided then + the range is calculated as the difference and input is clamped between the values. + The ``data_range`` must be given when ``dim`` is not None. + k1: Parameter of structural similarity index measure. + k2: Parameter of structural similarity index measure. + betas: Exponent parameters for individual similarities and contrastive sensitivities returned by different image + resolutions. + normalize: When MultiScaleStructuralSimilarityIndexMeasure loss is used for training, it is desirable to use + normalizes to improve the training stability. This `normalize` argument is out of scope of the original + implementation [1], and it is adapted from https://github.com/jorge-pessoa/pytorch-msssim instead. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Return: + Tensor with Multi-Scale SSIM score + + Raises: + ValueError: + If ``kernel_size`` is not an int or a Sequence of ints with size 2 or 3. + ValueError: + If ``betas`` is not a tuple of floats with length 2. + ValueError: + If ``normalize`` is neither `None`, `ReLU` nor `simple`. + + Example: + >>> from torch import rand + >>> from torchmetrics.image import MultiScaleStructuralSimilarityIndexMeasure + >>> preds = torch.rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> ms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0) + >>> ms_ssim(preds, target) + tensor(0.9628) + + """ + + higher_is_better: bool = True + is_differentiable: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + gaussian_kernel: bool = True, + kernel_size: Union[int, Sequence[int]] = 11, + sigma: Union[float, Sequence[float]] = 1.5, + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + data_range: Optional[Union[float, tuple[float, float]]] = None, + k1: float = 0.01, + k2: float = 0.03, + betas: tuple[float, ...] = (0.0448, 0.2856, 0.3001, 0.2363, 0.1333), + normalize: Literal["relu", "simple", None] = "relu", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + valid_reduction = ("elementwise_mean", "sum", "none", None) + if reduction not in valid_reduction: + raise ValueError(f"Argument `reduction` must be one of {valid_reduction}, but got {reduction}") + + if reduction in ("elementwise_mean", "sum"): + self.add_state("similarity", default=torch.tensor(0.0), dist_reduce_fx="sum") + else: + self.add_state("similarity", default=[], dist_reduce_fx=None) + + self.add_state("total", default=torch.tensor(0.0), dist_reduce_fx="sum") + + if not (isinstance(kernel_size, (Sequence, int))): + raise ValueError( + f"Argument `kernel_size` expected to be an sequence or an int, or a single int. Got {kernel_size}" + ) + if isinstance(kernel_size, Sequence) and ( + len(kernel_size) not in (2, 3) or not all(isinstance(ks, int) for ks in kernel_size) + ): + raise ValueError( + "Argument `kernel_size` expected to be an sequence of size 2 or 3 where each element is an int, " + f"or a single int. Got {kernel_size}" + ) + + self.gaussian_kernel = gaussian_kernel + self.sigma = sigma + self.kernel_size = kernel_size + self.reduction = reduction + self.data_range = data_range + self.k1 = k1 + self.k2 = k2 + if not isinstance(betas, tuple): + raise ValueError("Argument `betas` is expected to be of a type tuple.") + if isinstance(betas, tuple) and not all(isinstance(beta, float) for beta in betas): + raise ValueError("Argument `betas` is expected to be a tuple of floats.") + self.betas = betas + if normalize and normalize not in ("relu", "simple"): + raise ValueError("Argument `normalize` to be expected either `None` or one of 'relu' or 'simple'") + self.normalize = normalize + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + preds, target = _ssim_check_inputs(preds, target) + similarity = _multiscale_ssim_update( + preds, + target, + self.gaussian_kernel, + self.sigma, + self.kernel_size, + self.data_range, + self.k1, + self.k2, + self.betas, + self.normalize, + ) + + if self.reduction in ("none", None): + if not isinstance(self.similarity, list): + raise TypeError("Expected `self.similarity` to be a list for reduction='none'.") + self.similarity.append(similarity) + else: + if not isinstance(self.similarity, Tensor): + raise TypeError("Expected `self.similarity` to be a Tensor for elementwise_mean or sum reduction.") + self.similarity += similarity.sum() + + if not isinstance(self.total, Tensor): + raise TypeError("Expected `self.total` to be a Tensor.") + self.total += torch.tensor(preds.shape[0], dtype=self.total.dtype, device=self.total.device) + + def compute(self) -> Tensor: + """Compute MS-SSIM over state.""" + if self.reduction in ("none", None): + if isinstance(self.similarity, list): + return dim_zero_cat(self.similarity) + raise TypeError("Expected `self.similarity` to be a list for reduction='none'.") + if self.reduction == "sum": + if isinstance(self.similarity, Tensor): + return self.similarity + raise TypeError("Expected `self.similarity` to be a Tensor for sum reduction.") + if isinstance(self.similarity, Tensor) and isinstance(self.total, Tensor): + return self.similarity / self.total + raise TypeError("Expected `self.similarity` and `self.total` to be Tensors for elementwise_mean reduction.") + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torch import rand + >>> from torchmetrics.image import MultiScaleStructuralSimilarityIndexMeasure + >>> preds = rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> metric = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0) + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import rand + >>> from torchmetrics.image import MultiScaleStructuralSimilarityIndexMeasure + >>> preds = rand([3, 3, 256, 256]) + >>> target = preds * 0.75 + >>> metric = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/tv.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/tv.py new file mode 100644 index 0000000000000000000000000000000000000000..287e58a3a43d61e0d75a5fc343cc0384f02bed02 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/tv.py @@ -0,0 +1,139 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +import torch +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.tv import _total_variation_compute, _total_variation_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["TotalVariation.plot"] + + +class TotalVariation(Metric): + """Compute Total Variation loss (`TV`_). + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``img`` (:class:`~torch.Tensor`): A tensor of shape ``(N, C, H, W)`` consisting of images + + As output of `forward` and `compute` the metric returns the following output + + - ``sdi`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average TV value + over sample else returns tensor of shape ``(N,)`` with TV values per sample + + Args: + reduction: a method to reduce metric score over samples + + - ``'mean'``: takes the mean over samples + - ``'sum'``: takes the sum over samples + - ``None`` or ``'none'``: return the score per sample + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``reduction`` is not one of ``'sum'``, ``'mean'``, ``'none'`` or ``None`` + + Example: + >>> from torch import rand + >>> from torchmetrics.image import TotalVariation + >>> tv = TotalVariation() + >>> img = torch.rand(5, 3, 28, 28) + >>> tv(img) + tensor(7546.8018) + + """ + + full_state_update: bool = False + is_differentiable: bool = True + higher_is_better: bool = False + plot_lower_bound: float = 0.0 + + num_elements: Tensor + score_list: List[Tensor] + score: Tensor + + def __init__(self, reduction: Optional[Literal["mean", "sum", "none"]] = "sum", **kwargs: Any) -> None: + super().__init__(**kwargs) + if reduction is not None and reduction not in ("sum", "mean", "none"): + raise ValueError("Expected argument `reduction` to either be 'sum', 'mean', 'none' or None") + self.reduction = reduction + + self.add_state("score_list", default=[], dist_reduce_fx="cat") + self.add_state("score", default=tensor(0, dtype=torch.float), dist_reduce_fx="sum") + self.add_state("num_elements", default=tensor(0, dtype=torch.int), dist_reduce_fx="sum") + + def update(self, img: Tensor) -> None: + """Update current score with batch of input images.""" + score, num_elements = _total_variation_update(img) + if self.reduction is None or self.reduction == "none": + self.score_list.append(score) + else: + self.score += score.sum() + self.num_elements += num_elements + + def compute(self) -> Tensor: + """Compute final total variation.""" + score = dim_zero_cat(self.score_list) if self.reduction is None or self.reduction == "none" else self.score + return _total_variation_compute(score, self.num_elements, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image import TotalVariation + >>> metric = TotalVariation() + >>> metric.update(torch.rand(5, 3, 28, 28)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image import TotalVariation + >>> metric = TotalVariation() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.rand(5, 3, 28, 28))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/uqi.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/uqi.py new file mode 100644 index 0000000000000000000000000000000000000000..c503cc1f394a805a90fc96d40d016da47ea1d209 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/uqi.py @@ -0,0 +1,170 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.uqi import _uqi_compute, _uqi_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["UniversalImageQualityIndex.plot"] + + +class UniversalImageQualityIndex(Metric): + """Compute Universal Image Quality Index (UniversalImageQualityIndex_). + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``uiqi`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average UIQI value + over sample else returns tensor of shape ``(N,)`` with UIQI values per sample + + Args: + kernel_size: size of the gaussian kernel + sigma: Standard deviation of the gaussian kernel + reduction: a method to reduce metric score over labels. + + - ``'elementwise_mean'``: takes the mean (default) + - ``'sum'``: takes the sum + - ``'none'`` or ``None``: no reduction will be applied + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Return: + Tensor with UniversalImageQualityIndex score + + Example: + >>> import torch + >>> from torchmetrics.image import UniversalImageQualityIndex + >>> preds = torch.rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> uqi = UniversalImageQualityIndex() + >>> uqi(preds, target) + tensor(0.9216) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + sum_uqi: Tensor + numel: Tensor + + def __init__( + self, + kernel_size: Sequence[int] = (11, 11), + sigma: Sequence[float] = (1.5, 1.5), + reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if reduction not in ("elementwise_mean", "sum", "none", None): + raise ValueError( + f"The `reduction` {reduction} is not valid. Valid options are `elementwise_mean`, `sum`, `none`, None." + ) + if reduction is None or reduction == "none": + rank_zero_warn( + "Metric `UniversalImageQualityIndex` will save all targets and predictions in the buffer when using" + "`reduction=None` or `reduction='none'. For large datasets, this may lead to a large memory footprint." + ) + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("target", default=[], dist_reduce_fx="cat") + else: + self.add_state("sum_uqi", tensor(0.0), dist_reduce_fx="sum") + self.add_state("numel", tensor(0), dist_reduce_fx="sum") + self.kernel_size = kernel_size + self.sigma = sigma + self.reduction = reduction + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + preds, target = _uqi_update(preds, target) + if self.reduction is None or self.reduction == "none": + self.preds.append(preds) + self.target.append(target) + else: + uqi_score = _uqi_compute(preds, target, self.kernel_size, self.sigma, reduction="sum") + self.sum_uqi += uqi_score + ps = preds.shape + self.numel += ps[0] * ps[1] * (ps[2] - self.kernel_size[0] + 1) * (ps[3] - self.kernel_size[1] + 1) + + def compute(self) -> Tensor: + """Compute explained variance over state.""" + if self.reduction == "none" or self.reduction is None: + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + return _uqi_compute(preds, target, self.kernel_size, self.sigma, self.reduction) + return self.sum_uqi / self.numel if self.reduction == "elementwise_mean" else self.sum_uqi + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.image import UniversalImageQualityIndex + >>> preds = torch.rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> metric = UniversalImageQualityIndex() + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.image import UniversalImageQualityIndex + >>> preds = torch.rand([16, 1, 16, 16]) + >>> target = preds * 0.75 + >>> metric = UniversalImageQualityIndex() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/vif.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/vif.py new file mode 100644 index 0000000000000000000000000000000000000000..2366acd466bc26449c1cb2467302b4b8e16265f7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/image/vif.py @@ -0,0 +1,99 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, List + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.image.vif import _vif_per_channel +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat + + +class VisualInformationFidelity(Metric): + """Compute Pixel Based Visual Information Fidelity (VIF_). + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)`` with H,W ≥ 41 + - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)`` with H,W ≥ 41 + + As output of `forward` and `compute` the metric returns the following output + + - ``vif-p`` (:class:`~torch.Tensor`): + - If ``reduction='mean'`` (default), returns a Tensor mean VIF score. + - If ``reduction='none'``, returns a tensor of shape ``(N,)`` with VIF values per sample. + + Args: + sigma_n_sq: variance of the visual noise + reduction: The reduction method for aggregating scores. + + - ``'mean'``: return the average VIF across the batch. + - ``'none'``: return a VIF score for each sample in the batch. + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import randn + >>> from torchmetrics.image import VisualInformationFidelity + >>> preds = randn([32, 3, 41, 41], generator=torch.Generator().manual_seed(42)) + >>> target = randn([32, 3, 41, 41], generator=torch.Generator().manual_seed(43)) + >>> vif_mean = VisualInformationFidelity(reduction='mean') + >>> vif_mean(preds, target) + tensor(0.0032) + >>> vif_none = VisualInformationFidelity(reduction='none') + >>> vif_none(preds, target) + tensor([0.0040, 0.0049, 0.0017, 0.0039, 0.0041, 0.0043, 0.0030, 0.0028, 0.0012, + 0.0067, 0.0010, 0.0014, 0.0030, 0.0048, 0.0050, 0.0038, 0.0037, 0.0025, + 0.0041, 0.0019, 0.0007, 0.0034, 0.0037, 0.0016, 0.0026, 0.0021, 0.0038, + 0.0033, 0.0031, 0.0020, 0.0036, 0.0057]) + + """ + + is_differentiable = True + higher_is_better = True + full_state_update = False + + vif_score: List[Tensor] + total: Tensor + + def __init__(self, sigma_n_sq: float = 2.0, reduction: Literal["mean", "none"] = "mean", **kwargs: Any) -> None: + super().__init__(**kwargs) + + if not isinstance(sigma_n_sq, (float, int)) or sigma_n_sq < 0: + raise ValueError(f"Argument `sigma_n_sq` is expected to be a positive float or int, but got {sigma_n_sq}") + + if reduction not in ("mean", "none"): + raise ValueError(f"Argument `reduction` must be 'mean' or 'none', but got {reduction}") + + self.sigma_n_sq = sigma_n_sq + self.reduction = reduction + self.add_state("vif_score", default=[], dist_reduce_fx=None) + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + channels = preds.size(1) + vif_per_channel = [ + _vif_per_channel(preds[:, i, :, :], target[:, i, :, :], self.sigma_n_sq) for i in range(channels) + ] + vif_per_channel = torch.mean(torch.stack(vif_per_channel), 0) if channels > 1 else torch.cat(vif_per_channel) + self.vif_score.append(vif_per_channel) + + def compute(self) -> Tensor: + """Compute VIF over state.""" + vif_score = dim_zero_cat(self.vif_score) + if self.reduction == "mean": + return vif_score.mean() + return vif_score diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a00661de9d77056a39b922f65727ea318bc58d91 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/__init__.py @@ -0,0 +1,23 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.multimodal.lve import LipVertexError +from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_10 + +__all__ = ["LipVertexError"] + +if _TRANSFORMERS_GREATER_EQUAL_4_10: + from torchmetrics.multimodal.clip_iqa import CLIPImageQualityAssessment + from torchmetrics.multimodal.clip_score import CLIPScore + + __all__ += ["CLIPImageQualityAssessment", "CLIPScore"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/clip_iqa.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/clip_iqa.py new file mode 100644 index 0000000000000000000000000000000000000000..ad2d525b7da362ecb0a0becc0291576a1a5fae20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/clip_iqa.py @@ -0,0 +1,273 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.multimodal.clip_iqa import ( + _clip_iqa_compute, + _clip_iqa_format_prompts, + _clip_iqa_get_anchor_vectors, + _clip_iqa_update, + _get_clip_iqa_model_and_processor, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import ( + _MATPLOTLIB_AVAILABLE, + _PIQ_GREATER_EQUAL_0_8, + _TRANSFORMERS_GREATER_EQUAL_4_10, +) +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _PIQ_GREATER_EQUAL_0_8: + __doctest_skip__ = ["CLIPImageQualityAssessment", "CLIPImageQualityAssessment.plot"] + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["CLIPImageQualityAssessment.plot"] + +if _SKIP_SLOW_DOCTEST and _TRANSFORMERS_GREATER_EQUAL_4_10: + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + + def _download_clip_iqa_metric() -> None: + _CLIPModel.from_pretrained("openai/clip-vit-large-patch14", resume_download=True) + _CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14", resume_download=True) + + if not _try_proceed_with_timeout(_download_clip_iqa_metric): + __doctest_skip__ = ["CLIPImageQualityAssessment", "CLIPImageQualityAssessment.plot"] +else: + __doctest_skip__ = ["CLIPImageQualityAssessment", "CLIPImageQualityAssessment.plot"] + + +class CLIPImageQualityAssessment(Metric): + """Calculates `CLIP-IQA`_, that can be used to measure the visual content of images. + + The metric is based on the `CLIP`_ model, which is a neural network trained on a variety of (image, text) pairs to + be able to generate a vector representation of the image and the text that is similar if the image and text are + semantically similar. + + The metric works by calculating the cosine similarity between user provided images and pre-defined prompts. The + prompts always comes in pairs of "positive" and "negative" such as "Good photo." and "Bad photo.". By calculating + the similartity between image embeddings and both the "positive" and "negative" prompt, the metric can determine + which prompt the image is more similar to. The metric then returns the probability that the image is more similar + to the first prompt than the second prompt. + + Build in prompts are: + * quality: "Good photo." vs "Bad photo." + * brightness: "Bright photo." vs "Dark photo." + * noisiness: "Clean photo." vs "Noisy photo." + * colorfullness: "Colorful photo." vs "Dull photo." + * sharpness: "Sharp photo." vs "Blurry photo." + * contrast: "High contrast photo." vs "Low contrast photo." + * complexity: "Complex photo." vs "Simple photo." + * natural: "Natural photo." vs "Synthetic photo." + * happy: "Happy photo." vs "Sad photo." + * scary: "Scary photo." vs "Peaceful photo." + * new: "New photo." vs "Old photo." + * warm: "Warm photo." vs "Cold photo." + * real: "Real photo." vs "Abstract photo." + * beautiful: "Beautiful photo." vs "Ugly photo." + * lonely: "Lonely photo." vs "Sociable photo." + * relaxing: "Relaxing photo." vs "Stressful photo." + + As input to ``forward`` and ``update`` the metric accepts the following input + + - ``images`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor with shape ``(N,C,H,W)`` + + As output of `forward` and `compute` the metric returns the following output + + - ``clip_iqa`` (:class:`~torch.Tensor` or dict of tensors): tensor with the CLIP-IQA score. If a single prompt is + provided, a single tensor with shape ``(N,)`` is returned. If a list of prompts is provided, a dict of tensors + is returned with the prompt as key and the tensor with shape ``(N,)`` as value. + + Args: + model_name_or_path: string indicating the version of the CLIP model to use. Available models are: + + - `"clip_iqa"`, model corresponding to the CLIP-IQA paper. + - `"openai/clip-vit-base-patch16"` + - `"openai/clip-vit-base-patch32"` + - `"openai/clip-vit-large-patch14-336"` + - `"openai/clip-vit-large-patch14"` + + data_range: The maximum value of the input tensor. For example, if the input images are in range [0, 255], + data_range should be 255. The images are normalized by this value. + prompts: A string, tuple of strings or nested tuple of strings. If a single string is provided, it must be one + of the available prompts (see above). Else the input is expected to be a tuple, where each element can + be one of two things: either a string or a tuple of strings. If a string is provided, it must be one of the + available prompts (see above). If tuple is provided, it must be of length 2 and the first string must be a + positive prompt and the second string must be a negative prompt. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + .. hint:: + If using the default `clip_iqa` model, the package `piq` must be installed. Either install with + `pip install piq` or `pip install torchmetrics[image]`. + + Raises: + ModuleNotFoundError: + If transformers package is not installed or version is lower than 4.10.0 + ValueError: + If `prompts` is a tuple and it is not of length 2 + ValueError: + If `prompts` is a string and it is not one of the available prompts + ValueError: + If `prompts` is a list of strings and not all strings are one of the available prompts + + Example:: + Single prompt: + + >>> from torch import randint + >>> from torchmetrics.multimodal import CLIPImageQualityAssessment + >>> imgs = randint(255, (2, 3, 224, 224)).float() + >>> metric = CLIPImageQualityAssessment() + >>> metric(imgs) + tensor([0.8894, 0.8902]) + + Example:: + Multiple prompts: + + >>> from torch import randint + >>> from torchmetrics.multimodal import CLIPImageQualityAssessment + >>> imgs = randint(255, (2, 3, 224, 224)).float() + >>> metric = CLIPImageQualityAssessment(prompts=("quality", "brightness")) + >>> metric(imgs) + {'quality': tensor([0.8693, 0.8705]), 'brightness': tensor([0.5722, 0.4762])} + + Example:: + Custom prompts. Must always be a tuple of length 2, with a positive and negative prompt. + + >>> from torch import randint + >>> from torchmetrics.multimodal import CLIPImageQualityAssessment + >>> imgs = randint(255, (2, 3, 224, 224)).float() + >>> metric = CLIPImageQualityAssessment(prompts=(("Super good photo.", "Super bad photo."), "brightness")) + >>> metric(imgs) + {'user_defined_0': tensor([0.9578, 0.9654]), 'brightness': tensor([0.5495, 0.5764])} + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = True + plot_lower_bound = 0.0 + plot_upper_bound = 100.0 + + anchors: Tensor + probs_list: List[Tensor] + feature_network: str = "model" + + def __init__( + self, + model_name_or_path: Literal[ + "clip_iqa", + "openai/clip-vit-base-patch16", + "openai/clip-vit-base-patch32", + "openai/clip-vit-large-patch14-336", + "openai/clip-vit-large-patch14", + ] = "clip_iqa", + data_range: float = 1.0, + prompts: tuple[Union[str, tuple[str, str]], ...] = ("quality",), + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not (isinstance(data_range, (int, float)) and data_range > 0): + raise ValueError("Argument `data_range` should be a positive number.") + self.data_range = data_range + + prompts_list, prompts_name = _clip_iqa_format_prompts(prompts) + self.prompts_list = prompts_list + self.prompts_name = prompts_name + + self.model, self.processor = _get_clip_iqa_model_and_processor(model_name_or_path) + self.model_name_or_path = model_name_or_path + + with torch.inference_mode(): + anchors = _clip_iqa_get_anchor_vectors( + model_name_or_path, self.model, self.processor, self.prompts_list, self.device + ) + self.register_buffer("anchors", anchors) + + self.add_state("probs_list", [], dist_reduce_fx="cat") + + def update(self, images: Tensor) -> None: + """Update metric state with new data.""" + with torch.inference_mode(): + img_features = _clip_iqa_update( + self.model_name_or_path, images, self.model, self.processor, self.data_range, self.device + ) + probs = _clip_iqa_compute(img_features, self.anchors, self.prompts_name, format_as_dict=False) + if not isinstance(probs, Tensor): + raise ValueError("Output probs should be a tensor") + self.probs_list.append(probs) + + def compute(self) -> Union[Tensor, dict[str, Tensor]]: + """Compute metric.""" + probs = dim_zero_cat(self.probs_list) + if len(self.prompts_name) == 1: + return probs.squeeze() + return {p: probs[:, i] for i, p in enumerate(self.prompts_name)} + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.multimodal.clip_iqa import CLIPImageQualityAssessment + >>> metric = CLIPImageQualityAssessment() + >>> metric.update(torch.rand(1, 3, 224, 224)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.multimodal.clip_iqa import CLIPImageQualityAssessment + >>> metric = CLIPImageQualityAssessment() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.rand(1, 3, 224, 224))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) + + +if TYPE_CHECKING: + f = CLIPImageQualityAssessment + f(prompts=("colorfullness",)) + f( + prompts=("quality", "brightness", "noisiness"), + ) + f( + prompts=("quality", "brightness", "noisiness", "colorfullness"), + ) + f(prompts=(("Photo of a cat", "Photo of a dog"), "quality", ("Colorful photo", "Black and white photo"))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/clip_score.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/clip_score.py new file mode 100644 index 0000000000000000000000000000000000000000..87c2ac6253173fc48a6c93b4534f906108dbd65a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/clip_score.py @@ -0,0 +1,263 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics import Metric +from torchmetrics.functional.multimodal.clip_score import _clip_score_update, _get_clip_model_and_processor +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TRANSFORMERS_GREATER_EQUAL_4_10 +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["CLIPScore.plot"] + +if TYPE_CHECKING and _TRANSFORMERS_GREATER_EQUAL_4_10: + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + +if _SKIP_SLOW_DOCTEST and _TRANSFORMERS_GREATER_EQUAL_4_10: + from transformers import CLIPModel as _CLIPModel + from transformers import CLIPProcessor as _CLIPProcessor + + def _download_clip_for_clip_score() -> None: + _CLIPModel.from_pretrained("openai/clip-vit-large-patch14", resume_download=True) + _CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14", resume_download=True) + + if not _try_proceed_with_timeout(_download_clip_for_clip_score): + __doctest_skip__ = ["CLIPScore", "CLIPScore.plot"] +else: + __doctest_skip__ = ["CLIPScore", "CLIPScore.plot"] + _CLIPModel = None + _CLIPProcessor = None + + +class CLIPScore(Metric): + r"""Calculates `CLIP Score`_ which is a text-to-image similarity metric. + + CLIP Score is a reference free metric that can be used to evaluate the correlation between a generated caption for + an image and the actual content of the image, as well as the similarity between texts or images. It has been found + to be highly correlated with human judgement. The metric is defined as: + + .. math:: + \text{CLIPScore(I, C)} = max(100 * cos(E_I, E_C), 0) + + which corresponds to the cosine similarity between visual `CLIP`_ embedding :math:`E_i` for an image :math:`i` and + textual CLIP embedding :math:`E_C` for an caption :math:`C`. The score is bound between 0 and 100 and the closer + to 100 the better. + + Additionally, the CLIP Score can be calculated for the same modalities: + + .. math:: + \text{CLIPScore(I_1, I_2)} = max(100 * cos(E_{I_1}, E_{I_2}), 0) + + where :math:`E_{I_1}` and :math:`E_{I_2}` are the visual embeddings for images :math:`I_1` and :math:`I_2`. + + .. math:: + \text{CLIPScore(T_1, T_2)} = max(100 * cos(E_{T_1}, E_{T_2}), 0) + + where :math:`E_{T_1}` and :math:`E_{T_2}` are the textual embeddings for texts :math:`T_1` and :math:`T_2`. + + .. caution:: + Metric is not scriptable + + .. note:: + The default CLIP and processor used in this implementation has a maximum sequence length of 77 for text + inputs. If you need to process longer captions, you can use the `zer0int/LongCLIP-L-Diffusers` model which + has a maximum sequence length of 248. + + As input to ``forward`` and ``update`` the metric accepts the following input + + - source: Source input. + + This can be: + + - Images: ``Tensor`` or list of ``Tensor`` + + If a single tensor, it should have shape ``(N, C, H, W)``. + If a list of tensors, each tensor should have shape ``(C, H, W)``. + ``C`` is the number of channels, ``H`` and ``W`` are the height and width of the image. + + - Text: ``str`` or list of ``str`` + + Either a single caption or a list of captions. + + - target: Target input. + + This can be: + + - Images: ``Tensor`` or list of ``Tensor`` + + If a single tensor, it should have shape ``(N, C, H, W)``. + If a list of tensors, each tensor should have shape ``(C, H, W)``. + ``C`` is the number of channels, ``H`` and ``W`` are the height and width of the image. + + - Text: ``str`` or list of ``str`` + + Either a single caption or a list of captions. + + As output of `forward` and `compute` the metric returns the following output + + - ``clip_score`` (:class:`~torch.Tensor`): float scalar tensor with mean CLIP score over samples + + Args: + model_name_or_path: string indicating the version of the CLIP model to use. Available models are: + + - `"openai/clip-vit-base-patch16"` + - `"openai/clip-vit-base-patch32"` + - `"openai/clip-vit-large-patch14-336"` + - `"openai/clip-vit-large-patch14"` + - `"jinaai/jina-clip-v2"` + - `"zer0int/LongCLIP-L-Diffusers"` + - `"zer0int/LongCLIP-GmP-ViT-L-14"` + + Alternatively, a callable function that returns a tuple of CLIP compatible model and processor instances + can be passed in. By compatible, we mean that the processors `__call__` method should accept a list of + strings and list of images and that the model should have a `get_image_features` and `get_text_features` + methods. + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ModuleNotFoundError: + If transformers package is not installed or version is lower than 4.10.0 + + Example: + >>> from torchmetrics.multimodal.clip_score import CLIPScore + >>> metric = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16") + >>> image = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(42)) + >>> score = metric(image, "a photo of a cat") + >>> score.detach().round() + tensor(24.) + + Example: + >>> from torchmetrics.multimodal.clip_score import CLIPScore + >>> metric = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16") + >>> image1 = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(42)) + >>> image2 = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(43)) + >>> score = metric(image1, image2) + >>> score.detach().round() + tensor(99.) + + Example: + >>> from torchmetrics.multimodal.clip_score import CLIPScore + >>> metric = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16") + >>> score = metric("28-year-old chef found dead in San Francisco mall", + ... "A 28-year-old chef who recently moved to San Francisco was found dead.") + >>> score.detach().round() + tensor(91.) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound = 100.0 + + score: Tensor + n_samples: Tensor + feature_network: str = "model" + + def __init__( + self, + model_name_or_path: Union[ + Literal[ + "openai/clip-vit-base-patch16", + "openai/clip-vit-base-patch32", + "openai/clip-vit-large-patch14-336", + "openai/clip-vit-large-patch14", + "jinaai/jina-clip-v2", + "zer0int/LongCLIP-L-Diffusers", + "zer0int/LongCLIP-GmP-ViT-L-14", + ], + Callable[[], tuple[_CLIPModel, _CLIPProcessor]], + ] = "openai/clip-vit-large-patch14", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.model, self.processor = _get_clip_model_and_processor(model_name_or_path) + self.add_state("score", torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("n_samples", torch.tensor(0, dtype=torch.long), dist_reduce_fx="sum") + + def update( + self, source: Union[Tensor, List[Tensor], List[str], str], target: Union[Tensor, List[Tensor], List[str], str] + ) -> None: + """Update CLIP score on a batch of images and text. + + Args: + source: Source input. This can be: + - Images: Either a single [N, C, H, W] tensor or a list of [C, H, W] tensors. + - Text: Either a single caption or a list of captions. + target: Target input. This can be: + - Images: Either a single [N, C, H, W] tensor or a list of [C, H, W] tensors. + - Text: Either a single caption or a list of captions. + + Raises: + ValueError: + If not all images have format [C, H, W] + ValueError: + If the number of images and captions do not match + + """ + score, n_samples = _clip_score_update(source, target, self.model, self.processor) + self.score += score.sum(0) + self.n_samples += n_samples + + def compute(self) -> Tensor: + """Compute accumulated clip score.""" + return torch.max(self.score / self.n_samples, torch.zeros_like(self.score)) + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.multimodal.clip_score import CLIPScore + >>> metric = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16") + >>> metric.update(torch.randint(255, (3, 224, 224)), "a photo of a cat") + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.multimodal.clip_score import CLIPScore + >>> metric = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16") + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.randint(255, (3, 224, 224)), "a photo of a cat")) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/lve.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/lve.py new file mode 100644 index 0000000000000000000000000000000000000000..7dba054c0ffd320eccd8ea633c56108a6274332d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/multimodal/lve.py @@ -0,0 +1,190 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, List, Optional, Sequence, Union + +from torch import Tensor + +from torchmetrics.functional.multimodal.lve import lip_vertex_error +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["LipVertexError.plot"] + + +class LipVertexError(Metric): + r"""Implements Lip Vertex Error (LVE) metric for 3D talking head evaluation. + + The Lip Vertex Error (LVE) metric evaluates the quality of lip synchronization in 3D facial animations by measuring + the maximum Euclidean distance (L2 error) between corresponding lip vertices of the generated and ground truth + meshes for each frame. The metric is defined as: + + .. math:: + \text{LVE} = \frac{1}{N} \sum_{i=1}^{N} \max_{v \in \text{lip}} \|x_{i,v} - \hat{x}_{i,v}\|_2^2 + + where :math:`N` is the number of frames, :math:`x_{i,v}` represents the 3D coordinates of vertex :math:`v` in the + lip region of the ground truth frame :math:`i`, and :math:`\hat{x}_{i,v}` represents the corresponding vertex in the + predicted frame. The metric computes the maximum squared L2 distance between corresponding lip vertices for each + frame and averages across all frames. A lower LVE value indicates better lip synchronization quality. + + As input to ``forward`` and ``update``, the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predicted vertices tensor of shape (T, V, 3) where T is number of frames, + V is number of vertices, and 3 represents XYZ coordinates + - ``target`` (:class:`~torch.Tensor`): Ground truth vertices tensor of shape (T', V, 3) where T' can be different + from T + + As output of ``forward`` and ``compute``, the metric returns the following output: + + - ``lve_score`` (:class:`~torch.Tensor`): A scalar tensor containing the mean Lip Vertex Error value across + all frames. + + Args: + mouth_map: List of vertex indices corresponding to the mouth region + validate_args: bool indicating if input arguments and tensors should be validated for correctness. + Set to ``False`` for faster computations. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If the number of dimensions of `vertices_pred` or `vertices_gt` is not 3. + If vertex dimensions (V) or coordinate dimensions (3) don't match + If ``mouth_map`` is empty or contains invalid indices + + Example: + >>> import torch + >>> from torchmetrics.functional.multimodal import lip_vertex_error + >>> vertices_pred = torch.randn(10, 100, 3, generator=torch.manual_seed(42)) + >>> vertices_gt = torch.randn(10, 100, 3, generator=torch.manual_seed(43)) + >>> mouth_map = [0, 1, 2, 3, 4] + >>> lip_vertex_error(vertices_pred, vertices_gt, mouth_map) + tensor(12.7688) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + vertices_pred_list: List[Tensor] + vertices_gt_list: List[Tensor] + + def __init__( + self, + mouth_map: List[int], + validate_args: bool = True, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.mouth_map = mouth_map + self.validate_args = validate_args + + if not self.mouth_map: + raise ValueError("mouth_map cannot be empty.") + + self.add_state("vertices_pred_list", default=[], dist_reduce_fx=None) + self.add_state("vertices_gt_list", default=[], dist_reduce_fx=None) + + def update(self, vertices_pred: Tensor, vertices_gt: Tensor) -> None: + """Update metric states with predictions and targets. + + Args: + vertices_pred: Predicted vertices tensor of shape (T, V, 3) where T is number of frames, + V is number of vertices, and 3 represents XYZ coordinates + vertices_gt: Ground truth vertices tensor of shape (T', V, 3) where T' can be different from T + + """ + if self.validate_args: + if vertices_pred.ndim != 3 or vertices_gt.ndim != 3: + raise ValueError( + f"Expected both vertices_pred and vertices_gt to have 3 dimensions but got " + f"{vertices_pred.ndim} and {vertices_gt.ndim} dimensions respectively." + ) + if vertices_pred.shape[1:] != vertices_gt.shape[1:]: + raise ValueError( + f"Expected vertices_pred and vertices_gt to have same vertex and coordinate dimensions but got " + f"shapes {vertices_pred.shape} and {vertices_gt.shape}." + ) + if max(self.mouth_map) >= vertices_pred.shape[1]: + raise ValueError( + f"mouth_map contains invalid vertex indices. Max index {max(self.mouth_map)} is larger than " + f"number of vertices {vertices_pred.shape[1]}." + ) + + min_frames = min(vertices_pred.shape[0], vertices_gt.shape[0]) + vertices_pred = vertices_pred[:min_frames] + vertices_gt = vertices_gt[:min_frames] + + self.vertices_pred_list.append(vertices_pred) + self.vertices_gt_list.append(vertices_gt) + + def compute(self) -> Tensor: + """Compute the Lip Vertex Error over all accumulated states. + + Returns: + torch.Tensor: A scalar tensor with the mean LVE value + + """ + vertices_pred = dim_zero_cat(self.vertices_pred_list) + vertices_gt = dim_zero_cat(self.vertices_gt_list) + return lip_vertex_error(vertices_pred, vertices_gt, self.mouth_map, self.validate_args) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.multimodal.lve import LipVertexError + >>> metric = LipVertexError(mouth_map=[0, 1, 2, 3, 4]) + >>> vertices_pred = torch.randn(10, 100, 3, generator=torch.manual_seed(42)) + >>> vertices_gt = torch.randn(10, 100, 3, generator=torch.manual_seed(43)) + >>> metric.update(vertices_pred, vertices_gt) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.multimodal.lve import LipVertexError + >>> metric = LipVertexError(mouth_map=[0, 1, 2, 3, 4]) + >>> values = [] + >>> for _ in range(10): + ... vertices_pred = torch.randn(10, 100, 3, generator=torch.manual_seed(42+_)) + ... vertices_gt = torch.randn(10, 100, 3, generator=torch.manual_seed(43+_)) + ... values.append(metric(vertices_pred, vertices_gt)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e36da8703084dc1ecd76d1f28f42f8297fc4b4ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/__init__.py @@ -0,0 +1,27 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from torchmetrics.nominal.cramers import CramersV +from torchmetrics.nominal.fleiss_kappa import FleissKappa +from torchmetrics.nominal.pearson import PearsonsContingencyCoefficient +from torchmetrics.nominal.theils_u import TheilsU +from torchmetrics.nominal.tschuprows import TschuprowsT + +__all__ = [ + "CramersV", + "FleissKappa", + "PearsonsContingencyCoefficient", + "TheilsU", + "TschuprowsT", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/cramers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/cramers.py new file mode 100644 index 0000000000000000000000000000000000000000..5f361bfb47788ba70cb9b905a65187a51034c05f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/cramers.py @@ -0,0 +1,155 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.nominal.cramers import _cramers_v_compute, _cramers_v_update +from torchmetrics.functional.nominal.utils import _nominal_input_validation +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["CramersV.plot"] + + +class CramersV(Metric): + r"""Compute `Cramer's V`_ statistic measuring the association between two categorical (nominal) data series. + + .. math:: + V = \sqrt{\frac{\chi^2 / n}{\min(r - 1, k - 1)}} + + where + + .. math:: + \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}} + + where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j` + represent frequencies of values in ``preds`` and ``target``, respectively. Cramer's V is a symmetric coefficient, + i.e. :math:`V(preds, target) = V(target, preds)`, so order of input arguments does not matter. The output values + lies in [0, 1] with 1 meaning the perfect association. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the first data + series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively. + - ``target`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the second data + series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively. + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``cramers_v`` (:class:`~torch.Tensor`): Scalar tensor containing the Cramer's V statistic. + + Args: + num_classes: Integer specifying the number of classes + bias_correction: Indication of whether to use bias correction. + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If `nan_strategy` is not one of `'replace'` and `'drop'` + ValueError: + If `nan_strategy` is equal to `'replace'` and `nan_replace_value` is not an `int` or `float` + + Example:: + + >>> from torch import randint, randn + >>> from torchmetrics.nominal import CramersV + >>> preds = randint(0, 4, (100,)) + >>> target = (preds + randn(100)).round().clamp(0, 4) + >>> cramers_v = CramersV(num_classes=5) + >>> cramers_v(preds, target) + tensor(0.5284) + + """ + + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + confmat: Tensor + + def __init__( + self, + num_classes: int, + bias_correction: bool = True, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.num_classes = num_classes + self.bias_correction = bias_correction + + _nominal_input_validation(nan_strategy, nan_replace_value) + self.nan_strategy = nan_strategy + self.nan_replace_value = nan_replace_value + + self.add_state("confmat", torch.zeros(num_classes, num_classes), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + confmat = _cramers_v_update(preds, target, self.num_classes, self.nan_strategy, self.nan_replace_value) + self.confmat += confmat + + def compute(self) -> Tensor: + """Compute Cramer's V statistic.""" + return _cramers_v_compute(self.confmat, self.bias_correction) + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.nominal import CramersV + >>> metric = CramersV(num_classes=5) + >>> metric.update(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.nominal import CramersV + >>> metric = CramersV(num_classes=5) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,)))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/fleiss_kappa.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/fleiss_kappa.py new file mode 100644 index 0000000000000000000000000000000000000000..254796e96c9fddc5c5c24eeba43176296b76ac93 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/fleiss_kappa.py @@ -0,0 +1,137 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.nominal.fleiss_kappa import _fleiss_kappa_compute, _fleiss_kappa_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["FleissKappa.plot"] + + +class FleissKappa(Metric): + r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters. + + .. math:: + \kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}} + + where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean + agreement probability over all raters if they were randomly assigned. If the raters are in complete agreement then + the score 1 is returned, if there is no agreement among the raters (other than what would be expected by chance) + then a score smaller than 0 is returned. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``ratings`` (:class:`~torch.Tensor`): Ratings of shape ``[n_samples, n_categories]`` or + ``[n_samples, n_categories, n_raters]`` depedenent on ``mode``. If ``mode`` is ``counts``, ``ratings`` must be + integer and contain the number of raters that chose each category. If ``mode`` is ``probs``, ``ratings`` must be + floating point and contain the probability/logits that each rater chose each category. + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``fleiss_k`` (:class:`~torch.Tensor`): A float scalar tensor with the calculated Fleiss' kappa score. + + Args: + mode: Whether `ratings` will be provided as counts or probabilities. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> # Ratings are provided as counts + >>> from torch import randint + >>> from torchmetrics.nominal import FleissKappa + >>> ratings = randint(0, 10, size=(100, 5)).long() # 100 samples, 5 categories, 10 raters + >>> metric = FleissKappa(mode='counts') + >>> metric(ratings) + tensor(0.0089) + + Example: + >>> # Ratings are provided as probabilities + >>> from torch import randn + >>> from torchmetrics.nominal import FleissKappa + >>> ratings = randn(100, 5, 10).softmax(dim=1) # 100 samples, 5 categories, 10 raters + >>> metric = FleissKappa(mode='probs') + >>> metric(ratings) + tensor(-0.0075) + + """ + + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_upper_bound: float = 1.0 + counts: List[Tensor] + + def __init__(self, mode: Literal["counts", "probs"] = "counts", **kwargs: Any) -> None: + super().__init__(**kwargs) + if mode not in ["counts", "probs"]: + raise ValueError("Argument ``mode`` must be one of 'counts' or 'probs'.") + self.mode = mode + self.add_state("counts", default=[], dist_reduce_fx="cat") + + def update(self, ratings: Tensor) -> None: + """Updates the counts for fleiss kappa metric.""" + counts = _fleiss_kappa_update(ratings, self.mode) + self.counts.append(counts) + + def compute(self) -> Tensor: + """Computes Fleiss' kappa.""" + counts = dim_zero_cat(self.counts) + return _fleiss_kappa_compute(counts) + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.nominal import FleissKappa + >>> metric = FleissKappa(mode="probs") + >>> metric.update(torch.randn(100, 5, 10).softmax(dim=1)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.nominal import FleissKappa + >>> metric = FleissKappa(mode="probs") + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.randn(100, 5, 10).softmax(dim=1))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/pearson.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/pearson.py new file mode 100644 index 0000000000000000000000000000000000000000..15be1bd43b462ecbbbadba1811829f0a5dbc5515 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/pearson.py @@ -0,0 +1,159 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.nominal.pearson import ( + _pearsons_contingency_coefficient_compute, + _pearsons_contingency_coefficient_update, +) +from torchmetrics.functional.nominal.utils import _nominal_input_validation +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["PearsonsContingencyCoefficient.plot"] + + +class PearsonsContingencyCoefficient(Metric): + r"""Compute `Pearson's Contingency Coefficient`_ statistic. + + This metric measures the association between two categorical (nominal) data series. + + .. math:: + Pearson = \sqrt{\frac{\chi^2 / n}{1 + \chi^2 / n}} + + where + + .. math:: + \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}} + + where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j` + represent frequencies of values in ``preds`` and ``target``, respectively. Pearson's Contingency Coefficient is a + symmetric coefficient, i.e. :math:`Pearson(preds, target) = Pearson(target, preds)`, so order of input arguments + does not matter. The output values lies in [0, 1] with 1 meaning the perfect association. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the first data + series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively. + - ``target`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the second data + series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively. + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``pearsons_cc`` (:class:`~torch.Tensor`): Scalar tensor containing the Pearsons Contingency Coefficient statistic. + + Args: + num_classes: Integer specifying the number of classes + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If `nan_strategy` is not one of `'replace'` and `'drop'` + ValueError: + If `nan_strategy` is equal to `'replace'` and `nan_replace_value` is not an `int` or `float` + + Example:: + + >>> from torch import randint, randn + >>> from torchmetrics.nominal import PearsonsContingencyCoefficient + >>> preds = randint(0, 4, (100,)) + >>> target = (preds + randn(100)).round().clamp(0, 4) + >>> pearsons_contingency_coefficient = PearsonsContingencyCoefficient(num_classes=5) + >>> pearsons_contingency_coefficient(preds, target) + tensor(0.6948) + + """ + + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + confmat: Tensor + + def __init__( + self, + num_classes: int, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.num_classes = num_classes + + _nominal_input_validation(nan_strategy, nan_replace_value) + self.nan_strategy = nan_strategy + self.nan_replace_value = nan_replace_value + + self.add_state("confmat", torch.zeros(num_classes, num_classes), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + confmat = _pearsons_contingency_coefficient_update( + preds, target, self.num_classes, self.nan_strategy, self.nan_replace_value + ) + self.confmat += confmat + + def compute(self) -> Tensor: + """Compute Pearson's Contingency Coefficient statistic.""" + return _pearsons_contingency_coefficient_compute(self.confmat) + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.nominal import PearsonsContingencyCoefficient + >>> metric = PearsonsContingencyCoefficient(num_classes=5) + >>> metric.update(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.nominal import PearsonsContingencyCoefficient + >>> metric = PearsonsContingencyCoefficient(num_classes=5) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,)))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/theils_u.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/theils_u.py new file mode 100644 index 0000000000000000000000000000000000000000..19695a61c2cb51e90d4defc607c26a217b191d8e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/theils_u.py @@ -0,0 +1,143 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.nominal.theils_u import _theils_u_compute, _theils_u_update +from torchmetrics.functional.nominal.utils import _nominal_input_validation +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["TheilsU.plot"] + + +class TheilsU(Metric): + r"""Compute `Theil's U`_ statistic measuring the association between two categorical (nominal) data series. + + .. math:: + U(X|Y) = \frac{H(X) - H(X|Y)}{H(X)} + + where :math:`H(X)` is entropy of variable :math:`X` while :math:`H(X|Y)` is the conditional entropy of :math:`X` + given :math:`Y`. It is also know as the Uncertainty Coefficient. Theils's U is an asymmetric coefficient, i.e. + :math:`TheilsU(preds, target) \neq TheilsU(target, preds)`, so the order of the inputs matters. The output values + lies in [0, 1], where a 0 means y has no information about x while value 1 means y has complete information about x. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the first data + series (called X in the above definition) with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, + respectively. + - ``target`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the second data + series (called Y in the above definition) with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, + respectively. + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``theils_u`` (:class:`~torch.Tensor`): Scalar tensor containing the Theil's U statistic. + + Args: + num_classes: Integer specifying the number of classes + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example:: + + >>> from torch import randint + >>> from torchmetrics.nominal import TheilsU + >>> preds = randint(10, (10,)) + >>> target = randint(10, (10,)) + >>> metric = TheilsU(num_classes=10) + >>> metric(preds, target) + tensor(0.8530) + + """ + + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + confmat: Tensor + + def __init__( + self, + num_classes: int, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.num_classes = num_classes + + _nominal_input_validation(nan_strategy, nan_replace_value) + self.nan_strategy = nan_strategy + self.nan_replace_value = nan_replace_value + + self.add_state("confmat", torch.zeros(num_classes, num_classes), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + confmat = _theils_u_update(preds, target, self.num_classes, self.nan_strategy, self.nan_replace_value) + self.confmat += confmat + + def compute(self) -> Tensor: + """Compute Theil's U statistic.""" + return _theils_u_compute(self.confmat) + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.nominal import TheilsU + >>> metric = TheilsU(num_classes=10) + >>> metric.update(torch.randint(10, (10,)), torch.randint(10, (10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.nominal import TheilsU + >>> metric = TheilsU(num_classes=10) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.randint(10, (10,)), torch.randint(10, (10,)))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/tschuprows.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/tschuprows.py new file mode 100644 index 0000000000000000000000000000000000000000..9744103f304ec8f34c4e91d82df3a8344b38bee2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/nominal/tschuprows.py @@ -0,0 +1,155 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.nominal.tschuprows import _tschuprows_t_compute, _tschuprows_t_update +from torchmetrics.functional.nominal.utils import _nominal_input_validation +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["TschuprowsT.plot"] + + +class TschuprowsT(Metric): + r"""Compute `Tschuprow's T`_ statistic measuring the association between two categorical (nominal) data series. + + .. math:: + T = \sqrt{\frac{\chi^2 / n}{\sqrt{(r - 1) * (k - 1)}}} + + where + + .. math:: + \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}} + + where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j` + represent frequencies of values in ``preds`` and ``target``, respectively. Tschuprow's T is a symmetric coefficient, + i.e. :math:`T(preds, target) = T(target, preds)`, so order of input arguments does not matter. The output values + lies in [0, 1] with 1 meaning the perfect association. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the first data + series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively. + - ``target`` (:class:`~torch.Tensor`): Either 1D or 2D tensor of categorical (nominal) data from the second data + series with shape ``(batch_size,)`` or ``(batch_size, num_classes)``, respectively. + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``tschuprows_t`` (:class:`~torch.Tensor`): Scalar tensor containing the Tschuprow's T statistic. + + Args: + num_classes: Integer specifying the number of classes + bias_correction: Indication of whether to use bias correction. + nan_strategy: Indication of whether to replace or drop ``NaN`` values + nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'`` + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If `nan_strategy` is not one of `'replace'` and `'drop'` + ValueError: + If `nan_strategy` is equal to `'replace'` and `nan_replace_value` is not an `int` or `float` + + Example:: + + >>> from torch import randint + >>> from torchmetrics.nominal import TschuprowsT + >>> preds = randint(0, 4, (100,)) + >>> target = (preds + torch.randn(100)).round().clamp(0, 4) + >>> tschuprows_t = TschuprowsT(num_classes=5) + >>> tschuprows_t(preds, target) + tensor(0.4930) + + """ + + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + confmat: Tensor + + def __init__( + self, + num_classes: int, + bias_correction: bool = True, + nan_strategy: Literal["replace", "drop"] = "replace", + nan_replace_value: Optional[float] = 0.0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.num_classes = num_classes + self.bias_correction = bias_correction + + _nominal_input_validation(nan_strategy, nan_replace_value) + self.nan_strategy = nan_strategy + self.nan_replace_value = nan_replace_value + + self.add_state("confmat", torch.zeros(num_classes, num_classes), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + confmat = _tschuprows_t_update(preds, target, self.num_classes, self.nan_strategy, self.nan_replace_value) + self.confmat += confmat + + def compute(self) -> Tensor: + """Compute Tschuprow's T statistic.""" + return _tschuprows_t_compute(self.confmat, self.bias_correction) + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.nominal import TschuprowsT + >>> metric = TschuprowsT(num_classes=5) + >>> metric.update(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.nominal import TschuprowsT + >>> metric = TschuprowsT(num_classes=5) + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.randint(0, 4, (100,)), torch.randint(0, 4, (100,)))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a644fc58897b4a704ac2bf6b6670d2d5d6668f9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/__init__.py @@ -0,0 +1,60 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.regression.concordance import ConcordanceCorrCoef +from torchmetrics.regression.cosine_similarity import CosineSimilarity +from torchmetrics.regression.crps import ContinuousRankedProbabilityScore +from torchmetrics.regression.csi import CriticalSuccessIndex +from torchmetrics.regression.explained_variance import ExplainedVariance +from torchmetrics.regression.js_divergence import JensenShannonDivergence +from torchmetrics.regression.kendall import KendallRankCorrCoef +from torchmetrics.regression.kl_divergence import KLDivergence +from torchmetrics.regression.log_cosh import LogCoshError +from torchmetrics.regression.log_mse import MeanSquaredLogError +from torchmetrics.regression.mae import MeanAbsoluteError +from torchmetrics.regression.mape import MeanAbsolutePercentageError +from torchmetrics.regression.minkowski import MinkowskiDistance +from torchmetrics.regression.mse import MeanSquaredError +from torchmetrics.regression.nrmse import NormalizedRootMeanSquaredError +from torchmetrics.regression.pearson import PearsonCorrCoef +from torchmetrics.regression.r2 import R2Score +from torchmetrics.regression.rse import RelativeSquaredError +from torchmetrics.regression.spearman import SpearmanCorrCoef +from torchmetrics.regression.symmetric_mape import SymmetricMeanAbsolutePercentageError +from torchmetrics.regression.tweedie_deviance import TweedieDevianceScore +from torchmetrics.regression.wmape import WeightedMeanAbsolutePercentageError + +__all__ = [ + "ConcordanceCorrCoef", + "ContinuousRankedProbabilityScore", + "CosineSimilarity", + "CriticalSuccessIndex", + "ExplainedVariance", + "JensenShannonDivergence", + "KLDivergence", + "KendallRankCorrCoef", + "LogCoshError", + "MeanAbsoluteError", + "MeanAbsolutePercentageError", + "MeanSquaredError", + "MeanSquaredLogError", + "MinkowskiDistance", + "NormalizedRootMeanSquaredError", + "PearsonCorrCoef", + "R2Score", + "RelativeSquaredError", + "SpearmanCorrCoef", + "SymmetricMeanAbsolutePercentageError", + "TweedieDevianceScore", + "WeightedMeanAbsolutePercentageError", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/concordance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/concordance.py new file mode 100644 index 0000000000000000000000000000000000000000..6d0be7e1d30d2c95c8f56a861c4b8807965731b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/concordance.py @@ -0,0 +1,145 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Optional, Union + +from torch import Tensor + +from torchmetrics.functional.regression.concordance import _concordance_corrcoef_compute +from torchmetrics.regression.pearson import PearsonCorrCoef, _final_aggregation +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ConcordanceCorrCoef.plot"] + + +class ConcordanceCorrCoef(PearsonCorrCoef): + r"""Compute concordance correlation coefficient that measures the agreement between two variables. + + .. math:: + \rho_c = \frac{2 \rho \sigma_x \sigma_y}{\sigma_x^2 + \sigma_y^2 + (\mu_x - \mu_y)^2} + + where :math:`\mu_x, \mu_y` is the means for the two variables, :math:`\sigma_x^2, \sigma_y^2` are the corresponding + variances and \rho is the pearson correlation coefficient between the two variables. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): either single output float tensor with shape ``(N,)`` or multioutput + float tensor of shape ``(N,d)`` + - ``target`` (:class:`~torch.Tensor`): either single output float tensor with shape ``(N,)`` or multioutput + float tensor of shape ``(N,d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``concordance`` (:class:`~torch.Tensor`): A scalar float tensor with the concordance coefficient(s) for + non-multioutput input or a float tensor with shape ``(d,)`` for multioutput input + + Args: + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example (single output regression): + >>> from torchmetrics.regression import ConcordanceCorrCoef + >>> from torch import tensor + >>> target = tensor([3, -0.5, 2, 7]) + >>> preds = tensor([2.5, 0.0, 2, 8]) + >>> concordance = ConcordanceCorrCoef() + >>> concordance(preds, target) + tensor(0.9777) + + Example (multi output regression): + >>> from torchmetrics.regression import ConcordanceCorrCoef + >>> target = tensor([[3, -0.5], [2, 7]]) + >>> preds = tensor([[2.5, 0.0], [2, 8]]) + >>> concordance = ConcordanceCorrCoef(num_outputs=2) + >>> concordance(preds, target) + tensor([0.7273, 0.9887]) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = True + + plot_lower_bound: float = -1.0 + plot_upper_bound: float = 1.0 + + def compute(self) -> Tensor: + """Compute final concordance correlation coefficient over metric states.""" + if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1): + mean_x, mean_y, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, n_total = _final_aggregation( + means_x=self.mean_x, + means_y=self.mean_y, + maxs_abs_x=self.max_abs_dev_x, + maxs_abs_y=self.max_abs_dev_y, + vars_x=self.var_x, + vars_y=self.var_y, + corrs_xy=self.corr_xy, + nbs=self.n_total, + ) + else: + mean_x = self.mean_x + mean_y = self.mean_y + max_abs_dev_x = self.max_abs_dev_x + max_abs_dev_y = self.max_abs_dev_y + var_x = self.var_x + var_y = self.var_y + corr_xy = self.corr_xy + n_total = self.n_total + return _concordance_corrcoef_compute( + max_abs_dev_x, max_abs_dev_y, mean_x, mean_y, var_x, var_y, corr_xy, n_total + ) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import ConcordanceCorrCoef + >>> metric = ConcordanceCorrCoef() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import ConcordanceCorrCoef + >>> metric = ConcordanceCorrCoef() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/cosine_similarity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/cosine_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..5c86ac00cab671e35093dedd252aa1e14f933e24 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/cosine_similarity.py @@ -0,0 +1,139 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.cosine_similarity import _cosine_similarity_compute, _cosine_similarity_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["CosineSimilarity.plot"] + + +class CosineSimilarity(Metric): + r"""Compute the `Cosine Similarity`_. + + .. math:: + cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} = + \frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}} + + where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,d)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``cosine_similarity`` (:class:`~torch.Tensor`): A float tensor with the cosine similarity + + Args: + reduction: how to reduce over the batch dimension using 'sum', 'mean' or 'none' (taking the individual scores) + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import tensor + >>> from torchmetrics.regression import CosineSimilarity + >>> target = tensor([[0, 1], [1, 1]]) + >>> preds = tensor([[0, 1], [0, 1]]) + >>> cosine_similarity = CosineSimilarity(reduction = 'mean') + >>> cosine_similarity(preds, target) + tensor(0.8536) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + reduction: Literal["mean", "sum", "none", None] = "sum", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + allowed_reduction = ("sum", "mean", "none", None) + if reduction not in allowed_reduction: + raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}") + self.reduction = reduction + + self.add_state("preds", [], dist_reduce_fx="cat") + self.add_state("target", [], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update metric states with predictions and targets.""" + preds, target = _cosine_similarity_update(preds, target) + + self.preds.append(preds) + self.target.append(target) + + def compute(self) -> Tensor: + """Compute metric.""" + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + return _cosine_similarity_compute(preds, target, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import CosineSimilarity + >>> metric = CosineSimilarity() + >>> metric.update(randn(10,2), randn(10,2)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import CosineSimilarity + >>> metric = CosineSimilarity() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,2), randn(10,2))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/crps.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/crps.py new file mode 100644 index 0000000000000000000000000000000000000000..0093bb6d6bf9b037f12ac87579653191f4bcc1b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/crps.py @@ -0,0 +1,133 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional, Sequence, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.crps import _crps_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ContinuousRankedProbabilityScore.plot"] + + +class ContinuousRankedProbabilityScore(Metric): + r"""Computes continuous ranked probability score. + + .. math:: + CRPS(F, y) = \int_{-\infty}^{\infty} (F(x) - 1_{x \geq y})^2 dx + + where :math:`F` is the predicted cumulative distribution function and :math:`y` is the true target. The metric is + usually used to evaluate probabilistic regression models, such as forecasting models. A lower CRPS indicates a + better forecast, meaning that forecasted probabilities are closer to the true observed values. CRPS can also be + seen as a generalization of the brier score for non binary classification problems. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,d)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``cosine_similarity`` (:class:`~torch.Tensor`): A float tensor with the cosine similarity + + Args: + reduction: how to reduce over the batch dimension using 'sum', 'mean' or 'none' (taking the individual scores) + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import randn + >>> from torchmetrics.regression import ContinuousRankedProbabilityScore + >>> preds = randn(10, 5) + >>> target = randn(10) + >>> crps = ContinuousRankedProbabilityScore() + >>> crps(preds, target) + tensor(0.7731) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + score: Tensor + total: Tensor + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.add_state("score", default=torch.zeros(1), dist_reduce_fx="sum") + self.add_state("total", default=torch.zeros(1), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets. + + Args: + preds: Predictions from model + target: Ground truth values + + """ + batch_size, diff, ensemble_sum = _crps_update(preds, target) + self.score += torch.sum(diff - ensemble_sum) + self.total += batch_size + + def compute(self) -> Tensor: + """Compute the continuous ranked probability score over state.""" + return self.score / self.total + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import ContinuousRankedProbabilityScore + >>> metric = ContinuousRankedProbabilityScore() + >>> metric.update(randn(10,5), randn(10)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import ContinuousRankedProbabilityScore + >>> metric = ContinuousRankedProbabilityScore() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,5), randn(10))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/csi.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/csi.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c7356aaab37f783cab36cbe4693286e2b62692 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/csi.py @@ -0,0 +1,112 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, List, Optional + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.csi import _critical_success_index_compute, _critical_success_index_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import dim_zero_cat + + +class CriticalSuccessIndex(Metric): + r"""Calculate critical success index (CSI). + + Critical success index (also known as the threat score) is a statistic used weather forecasting that measures + forecast performance over inputs binarized at a specified threshold. It is defined as: + + .. math:: \text{CSI} = \frac{\text{TP}}{\text{TP}+\text{FN}+\text{FP}} + + Where :math:`\text{TP}`, :math:`\text{FN}` and :math:`\text{FP}` represent the number of true positives, false + negatives and false positives respectively after binarizing the input tensors. + + Args: + threshold: Values above or equal to threshold are replaced with 1, below by 0 + keep_sequence_dim: Index of the sequence dimension if the inputs are sequences of images. If specified, + the score will be calculated separately for each image in the sequence. If ``None``, the score will be + calculated across all dimensions. + + Example: + >>> import torch + >>> from torchmetrics.regression import CriticalSuccessIndex + >>> x = torch.Tensor([[0.2, 0.7], [0.9, 0.3]]) + >>> y = torch.Tensor([[0.4, 0.2], [0.8, 0.6]]) + >>> csi = CriticalSuccessIndex(0.5) + >>> csi(x, y) + tensor(0.3333) + + Example: + >>> import torch + >>> from torchmetrics.regression import CriticalSuccessIndex + >>> x = torch.Tensor([[[0.2, 0.7], [0.9, 0.3]], [[0.2, 0.7], [0.9, 0.3]]]) + >>> y = torch.Tensor([[[0.4, 0.2], [0.8, 0.6]], [[0.4, 0.2], [0.8, 0.6]]]) + >>> csi = CriticalSuccessIndex(0.5, keep_sequence_dim=0) + >>> csi(x, y) + tensor([0.3333, 0.3333]) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + + hits: Tensor + misses: Tensor + false_alarms: Tensor + hits_list: List[Tensor] + misses_list: List[Tensor] + false_alarms_list: List[Tensor] + + def __init__(self, threshold: float, keep_sequence_dim: Optional[int] = None, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.threshold = float(threshold) + + if keep_sequence_dim and (not isinstance(keep_sequence_dim, int) or keep_sequence_dim < 0): + raise ValueError(f"Expected keep_sequence_dim to be a non-negative integer but got {keep_sequence_dim}") + self.keep_sequence_dim = keep_sequence_dim + + if keep_sequence_dim is None: + self.add_state("hits", default=torch.tensor(0), dist_reduce_fx="sum") + self.add_state("misses", default=torch.tensor(0), dist_reduce_fx="sum") + self.add_state("false_alarms", default=torch.tensor(0), dist_reduce_fx="sum") + else: + self.add_state("hits_list", default=[], dist_reduce_fx="cat") + self.add_state("misses_list", default=[], dist_reduce_fx="cat") + self.add_state("false_alarms_list", default=[], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + hits, misses, false_alarms = _critical_success_index_update( + preds, target, self.threshold, self.keep_sequence_dim + ) + if self.keep_sequence_dim is None: + self.hits += hits + self.misses += misses + self.false_alarms += false_alarms + else: + self.hits_list.append(hits) + self.misses_list.append(misses) + self.false_alarms_list.append(false_alarms) + + def compute(self) -> Tensor: + """Compute critical success index over state.""" + if self.keep_sequence_dim is None: + hits = self.hits + misses = self.misses + false_alarms = self.false_alarms + else: + hits = dim_zero_cat(self.hits_list) + misses = dim_zero_cat(self.misses_list) + false_alarms = dim_zero_cat(self.false_alarms_list) + return _critical_success_index_compute(hits, misses, false_alarms) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/explained_variance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/explained_variance.py new file mode 100644 index 0000000000000000000000000000000000000000..833c1609e55ac9091c18cf5c157e0ea8c9c6907d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/explained_variance.py @@ -0,0 +1,178 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.explained_variance import ( + ALLOWED_MULTIOUTPUT, + _explained_variance_compute, + _explained_variance_update, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ExplainedVariance.plot"] + + +class ExplainedVariance(Metric): + r"""Compute `explained variance`_. + + .. math:: \text{ExplainedVariance} = 1 - \frac{\text{Var}(y - \hat{y})}{\text{Var}(y)} + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor + with shape ``(N,)`` or ``(N, ...)`` (multioutput) + - ``target`` (:class:`~torch.Tensor`): Ground truth values in long tensor + with shape ``(N,)`` or ``(N, ...)`` (multioutput) + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``explained_variance`` (:class:`~torch.Tensor`): A tensor with the explained variance(s) + + In the case of multioutput, as default the variances will be uniformly averaged over the additional dimensions. + Please see argument ``multioutput`` for changing this behavior. + + Args: + multioutput: + Defines aggregation in the case of multiple output scores. Can be one + of the following strings (default is ``'uniform_average'``.): + + * ``'raw_values'`` returns full set of scores + * ``'uniform_average'`` scores are uniformly averaged + * ``'variance_weighted'`` scores are weighted by their individual variances + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``multioutput`` is not one of ``"raw_values"``, ``"uniform_average"`` or ``"variance_weighted"``. + + Example: + >>> from torch import tensor + >>> from torchmetrics.regression import ExplainedVariance + >>> target = tensor([3, -0.5, 2, 7]) + >>> preds = tensor([2.5, 0.0, 2, 8]) + >>> explained_variance = ExplainedVariance() + >>> explained_variance(preds, target) + tensor(0.9572) + + >>> target = tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = tensor([[0, 2], [-1, 2], [8, -5]]) + >>> explained_variance = ExplainedVariance(multioutput='raw_values') + >>> explained_variance(preds, target) + tensor([0.9677, 1.0000]) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + num_obs: Tensor + sum_error: Tensor + sum_squared_error: Tensor + sum_target: Tensor + sum_squared_target: Tensor + + def __init__( + self, + multioutput: Literal["raw_values", "uniform_average", "variance_weighted"] = "uniform_average", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if multioutput not in ALLOWED_MULTIOUTPUT: + raise ValueError( + f"Invalid input to argument `multioutput`. Choose one of the following: {ALLOWED_MULTIOUTPUT}" + ) + self.multioutput = multioutput + self.add_state("sum_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("sum_squared_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("sum_target", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("sum_squared_target", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("num_obs", default=tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target = _explained_variance_update( + preds, target + ) + self.num_obs = self.num_obs + num_obs + self.sum_error = self.sum_error + sum_error + self.sum_squared_error = self.sum_squared_error + sum_squared_error + self.sum_target = self.sum_target + sum_target + self.sum_squared_target = self.sum_squared_target + sum_squared_target + + def compute(self) -> Union[Tensor, Sequence[Tensor]]: + """Compute explained variance over state.""" + return _explained_variance_compute( + self.num_obs, + self.sum_error, + self.sum_squared_error, + self.sum_target, + self.sum_squared_target, + self.multioutput, + ) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import ExplainedVariance + >>> metric = ExplainedVariance() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import ExplainedVariance + >>> metric = ExplainedVariance() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/js_divergence.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/js_divergence.py new file mode 100644 index 0000000000000000000000000000000000000000..64183e80afa9dd2e481bc48138d4cd0d55d1a668 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/js_divergence.py @@ -0,0 +1,172 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from math import log +from typing import Any, List, Optional, Sequence, Union, cast + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.js_divergence import _jsd_compute, _jsd_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["JensenShannonDivergence.plot"] + + +class JensenShannonDivergence(Metric): + r"""Compute the `Jensen-Shannon divergence`_. + + .. math:: + D_{JS}(P||Q) = \frac{1}{2} D_{KL}(P||M) + \frac{1}{2} D_{KL}(Q||M) + + Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution + over data and :math:`Q` is often a prior or approximation of :math:`P`. :math:`D_{KL}` is the `KL divergence`_ and + :math:`M` is the average of the two distributions. It should be noted that the Jensen-Shannon divergence is a + symmetrical metric i.e. :math:`D_{JS}(P||Q) = D_{JS}(Q||P)`. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``p`` (:class:`~torch.Tensor`): a data distribution with shape ``(N, d)`` + - ``q`` (:class:`~torch.Tensor`): prior or approximate distribution with shape ``(N, d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``js_divergence`` (:class:`~torch.Tensor`): A tensor with the Jensen-Shannon divergence + + Args: + log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities, + will normalize to make sure the distributes sum to 1. + reduction: + Determines how to reduce over the ``N``/batch dimension: + + - ``'mean'`` [default]: Averages score across samples + - ``'sum'``: Sum score across samples + - ``'none'`` or ``None``: Returns score per sample + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + TypeError: + If ``log_prob`` is not an ``bool``. + ValueError: + If ``reduction`` is not one of ``'mean'``, ``'sum'``, ``'none'`` or ``None``. + + .. attention:: + Half precision is only support on GPU for this metric. + + Example: + >>> from torch import tensor + >>> from torchmetrics.regression import JensenShannonDivergence + >>> p = tensor([[0.1, 0.9], [0.2, 0.8], [0.3, 0.7]]) + >>> q = tensor([[0.3, 0.7], [0.4, 0.6], [0.5, 0.5]]) + >>> js_div = JensenShannonDivergence() + >>> js_div(p, q) + tensor(0.0259) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = log(2) + + measures: Union[Tensor, List[Tensor]] + total: Tensor + + def __init__( + self, + log_prob: bool = False, + reduction: Literal["mean", "sum", "none", None] = "mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(log_prob, bool): + raise TypeError(f"Expected argument `log_prob` to be bool but got {log_prob}") + self.log_prob = log_prob + + allowed_reduction = ["mean", "sum", "none", None] + if reduction not in allowed_reduction: + raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}") + self.reduction = reduction + + if self.reduction in ["mean", "sum"]: + self.add_state("measures", torch.tensor(0.0), dist_reduce_fx="sum") + else: + self.add_state("measures", [], dist_reduce_fx="cat") + self.add_state("total", torch.tensor(0), dist_reduce_fx="sum") + + def update(self, p: Tensor, q: Tensor) -> None: + """Update the metric state.""" + measures, total = _jsd_update(p, q, self.log_prob) + if self.reduction is None or self.reduction == "none": + cast(List[Tensor], self.measures).append(measures) + else: + self.measures = cast(Tensor, self.measures) + measures.sum() + self.total += total + + def compute(self) -> Tensor: + """Compute metric.""" + measures: Tensor = ( + dim_zero_cat(cast(List[Tensor], self.measures)) + if self.reduction in ["none", None] + else cast(Tensor, self.measures) + ) + return _jsd_compute(measures, self.total, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import JensenShannonDivergence + >>> metric = JensenShannonDivergence() + >>> metric.update(randn(10,3).softmax(dim=-1), randn(10,3).softmax(dim=-1)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import JensenShannonDivergence + >>> metric = JensenShannonDivergence() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,3).softmax(dim=-1), randn(10,3).softmax(dim=-1))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/kendall.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/kendall.py new file mode 100644 index 0000000000000000000000000000000000000000..8a102dee08f31ef93ba10f0c349f0ea2d108c901 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/kendall.py @@ -0,0 +1,212 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.kendall import ( + _kendall_corrcoef_compute, + _kendall_corrcoef_update, + _MetricVariant, + _TestAlternative, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["KendallRankCorrCoef.plot"] + + +class KendallRankCorrCoef(Metric): + r"""Compute `Kendall Rank Correlation Coefficient`_. + + .. math:: + tau_a = \frac{C - D}{C + D} + + where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs. + + .. math:: + tau_b = \frac{C - D}{\sqrt{(C + D + T_{preds}) * (C + D + T_{target})}} + + where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs and :math:`T` represents + a total number of ties. + + .. math:: + tau_c = 2 * \frac{C - D}{n^2 * \frac{m - 1}{m}} + + where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs, :math:`n` is a total number + of observations and :math:`m` is a ``min`` of unique values in ``preds`` and ``target`` sequence. + + Definitions according to Definition according to `The Treatment of Ties in Ranking Problems`_. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Sequence of data in float tensor of either shape ``(N,)`` or ``(N,d)`` + - ``target`` (:class:`~torch.Tensor`): Sequence of data in float tensor of either shape ``(N,)`` or ``(N,d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``kendall`` (:class:`~torch.Tensor`): A tensor with the correlation tau statistic, + and if it is not None, the p-value of corresponding statistical test. + + Args: + variant: Indication of which variant of Kendall's tau to be used + t_test: Indication whether to run t-test + alternative: Alternative hypothesis for t-test. Possible values: + - 'two-sided': the rank correlation is nonzero + - 'less': the rank correlation is negative (less than zero) + - 'greater': the rank correlation is positive (greater than zero) + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: If ``t_test`` is not of a type bool + ValueError: If ``t_test=True`` and ``alternative=None`` + + Example (single output regression): + >>> from torch import tensor + >>> from torchmetrics.regression import KendallRankCorrCoef + >>> preds = tensor([2.5, 0.0, 2, 8]) + >>> target = tensor([3, -0.5, 2, 1]) + >>> kendall = KendallRankCorrCoef() + >>> kendall(preds, target) + tensor(0.3333) + + Example (multi output regression): + >>> from torchmetrics.regression import KendallRankCorrCoef + >>> preds = tensor([[2.5, 0.0], [2, 8]]) + >>> target = tensor([[3, -0.5], [2, 1]]) + >>> kendall = KendallRankCorrCoef(num_outputs=2) + >>> kendall(preds, target) + tensor([1., 1.]) + + Example (single output regression with t-test): + >>> from torchmetrics.regression import KendallRankCorrCoef + >>> preds = tensor([2.5, 0.0, 2, 8]) + >>> target = tensor([3, -0.5, 2, 1]) + >>> kendall = KendallRankCorrCoef(t_test=True, alternative='two-sided') + >>> kendall(preds, target) + (tensor(0.3333), tensor(0.4969)) + + Example (multi output regression with t-test): + >>> from torchmetrics.regression import KendallRankCorrCoef + >>> preds = tensor([[2.5, 0.0], [2, 8]]) + >>> target = tensor([[3, -0.5], [2, 1]]) + >>> kendall = KendallRankCorrCoef(t_test=True, alternative='two-sided', num_outputs=2) + >>> kendall(preds, target) + (tensor([1., 1.]), tensor([nan, nan])) + + """ + + is_differentiable = False + higher_is_better = None + full_state_update = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + variant: Literal["a", "b", "c"] = "b", + t_test: bool = False, + alternative: Optional[Literal["two-sided", "less", "greater"]] = "two-sided", + num_outputs: int = 1, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(t_test, bool): + raise ValueError(f"Argument `t_test` is expected to be of a type `bool`, but got {type(t_test)}.") + if t_test and alternative is None: + raise ValueError("Argument `alternative` is required if `t_test=True` but got `None`.") + + self.variant = _MetricVariant.from_str(str(variant)) + self.alternative = _TestAlternative.from_str(str(alternative)) if t_test else None + self.num_outputs = num_outputs + + self.add_state("preds", [], dist_reduce_fx="cat") + self.add_state("target", [], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update variables required to compute Kendall rank correlation coefficient.""" + self.preds, self.target = _kendall_corrcoef_update( + preds, + target, + self.preds, + self.target, + num_outputs=self.num_outputs, + ) + + def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Compute Kendall rank correlation coefficient, and optionally p-value of corresponding statistical test.""" + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + tau, p_value = _kendall_corrcoef_compute( + preds, + target, + self.variant, # type: ignore[arg-type] # todo + self.alternative, # type: ignore[arg-type] # todo + ) + + if p_value is not None: + return tau, p_value + return tau + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import KendallRankCorrCoef + >>> metric = KendallRankCorrCoef() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import KendallRankCorrCoef + >>> metric = KendallRankCorrCoef() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/kl_divergence.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/kl_divergence.py new file mode 100644 index 0000000000000000000000000000000000000000..c0956e0b4f500021ebc51ff28b8a22d46814d500 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/kl_divergence.py @@ -0,0 +1,172 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union, cast + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.kl_divergence import _kld_compute, _kld_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["KLDivergence.plot"] + + +class KLDivergence(Metric): + r"""Compute the `KL divergence`_. + + .. math:: + D_{KL}(P||Q) = \sum_{x\in\mathcal{X}} P(x) \log\frac{P(x)}{Q{x}} + + Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution + over data and :math:`Q` is often a prior or approximation of :math:`P`. It should be noted that the KL divergence + is a non-symmetrical metric i.e. :math:`D_{KL}(P||Q) \neq D_{KL}(Q||P)`. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``p`` (:class:`~torch.Tensor`): a data distribution with shape ``(N, d)`` + - ``q`` (:class:`~torch.Tensor`): prior or approximate distribution with shape ``(N, d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``kl_divergence`` (:class:`~torch.Tensor`): A tensor with the KL divergence + + Args: + log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities, + will normalize to make sure the distributes sum to 1. + reduction: + Determines how to reduce over the ``N``/batch dimension: + + - ``'mean'`` [default]: Averages score across samples + - ``'sum'``: Sum score across samples + - ``'none'`` or ``None``: Returns score per sample + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + TypeError: + If ``log_prob`` is not an ``bool``. + ValueError: + If ``reduction`` is not one of ``'mean'``, ``'sum'``, ``'none'`` or ``None``. + + .. attention:: + Half precision is only support on GPU for this metric. + + Example: + >>> from torch import tensor + >>> from torchmetrics.regression import KLDivergence + >>> p = tensor([[0.36, 0.48, 0.16]]) + >>> q = tensor([[1/3, 1/3, 1/3]]) + >>> kl_divergence = KLDivergence() + >>> kl_divergence(p, q) + tensor(0.0853) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + measures: Union[Tensor, List[Tensor]] + total: Tensor + # FIXME: Apply once minimal torch is 1.10. For torch<=1.9, jit does not support Union types + # measures: Union[Tensor, List[Tensor]] + + def __init__( + self, + log_prob: bool = False, + reduction: Literal["mean", "sum", "none", None] = "mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(log_prob, bool): + raise TypeError(f"Expected argument `log_prob` to be bool but got {log_prob}") + self.log_prob = log_prob + + allowed_reduction = ["mean", "sum", "none", None] + if reduction not in allowed_reduction: + raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}") + self.reduction = reduction + + if self.reduction in ["mean", "sum"]: + self.add_state("measures", torch.tensor(0.0), dist_reduce_fx="sum") + else: + self.add_state("measures", [], dist_reduce_fx="cat") + self.add_state("total", torch.tensor(0), dist_reduce_fx="sum") + + def update(self, p: Tensor, q: Tensor) -> None: + """Update metric states with predictions and targets.""" + measures, total = _kld_update(p, q, self.log_prob) + if self.reduction is None or self.reduction == "none": + cast(List[Tensor], self.measures).append(measures) + else: + self.measures = cast(Tensor, self.measures) + measures.sum() + self.total += total + + def compute(self) -> Tensor: + """Compute metric.""" + measures: Tensor = ( + dim_zero_cat(cast(List[Tensor], self.measures)) + if self.reduction in ["none", None] + else cast(Tensor, self.measures) + ) + return _kld_compute(measures, self.total, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import KLDivergence + >>> metric = KLDivergence() + >>> metric.update(randn(10,3).softmax(dim=-1), randn(10,3).softmax(dim=-1)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import KLDivergence + >>> metric = KLDivergence() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,3).softmax(dim=-1), randn(10,3).softmax(dim=-1))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/log_cosh.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/log_cosh.py new file mode 100644 index 0000000000000000000000000000000000000000..750e5a3497e587ff7207f35c7a8acb59b60829ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/log_cosh.py @@ -0,0 +1,142 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.log_cosh import _log_cosh_error_compute, _log_cosh_error_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["LogCoshError.plot"] + + +class LogCoshError(Metric): + r"""Compute the `LogCosh Error`_. + + .. math:: \text{LogCoshError} = \log\left(\frac{\exp(\hat{y} - y) + \exp(\hat{y - y})}{2}\right) + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Estimated labels with shape ``(batch_size,)`` + or ``(batch_size, num_outputs)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth labels with shape ``(batch_size,)`` + or ``(batch_size, num_outputs)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``log_cosh_error`` (:class:`~torch.Tensor`): A tensor with the log cosh error + + Args: + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example (single output regression):: + >>> from torchmetrics.regression import LogCoshError + >>> preds = torch.tensor([3.0, 5.0, 2.5, 7.0]) + >>> target = torch.tensor([2.5, 5.0, 4.0, 8.0]) + >>> log_cosh_error = LogCoshError() + >>> log_cosh_error(preds, target) + tensor(0.3523) + + Example (multi output regression):: + >>> from torchmetrics.regression import LogCoshError + >>> preds = torch.tensor([[3.0, 5.0, 1.2], [-2.1, 2.5, 7.0]]) + >>> target = torch.tensor([[2.5, 5.0, 1.3], [0.3, 4.0, 8.0]]) + >>> log_cosh_error = LogCoshError(num_outputs=3) + >>> log_cosh_error(preds, target) + tensor([0.9176, 0.4277, 0.2194]) + + """ + + is_differentiable = True + higher_is_better = False + full_state_update = False + plot_lower_bound: float = 0.0 + + sum_log_cosh_error: Tensor + total: Tensor + + def __init__(self, num_outputs: int = 1, **kwargs: Any) -> None: + super().__init__(**kwargs) + + if not isinstance(num_outputs, int) and num_outputs < 1: + raise ValueError(f"Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}") + self.num_outputs = num_outputs + self.add_state("sum_log_cosh_error", default=torch.zeros(num_outputs), dist_reduce_fx="sum") + self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets. + + Raises: + ValueError: + If ``preds`` or ``target`` has multiple outputs when ``num_outputs=1`` + + """ + sum_log_cosh_error, num_obs = _log_cosh_error_update(preds, target, self.num_outputs) + self.sum_log_cosh_error += sum_log_cosh_error + self.total += num_obs + + def compute(self) -> Tensor: + """Compute LogCosh error over state.""" + return _log_cosh_error_compute(self.sum_log_cosh_error, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import LogCoshError + >>> metric = LogCoshError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import LogCoshError + >>> metric = LogCoshError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/log_mse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/log_mse.py new file mode 100644 index 0000000000000000000000000000000000000000..31dbba6accba565067cb2a4bec260a20f2fb16fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/log_mse.py @@ -0,0 +1,129 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.regression.log_mse import _mean_squared_log_error_compute, _mean_squared_log_error_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MeanSquaredLogError.plot"] + + +class MeanSquaredLogError(Metric): + r"""Compute `mean squared logarithmic error`_ (MSLE). + + .. math:: \text{MSLE} = \frac{1}{N}\sum_i^N (\log_e(1 + y_i) - \log_e(1 + \hat{y_i}))^2 + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``mean_squared_log_error`` (:class:`~torch.Tensor`): A tensor with the mean squared log error + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import tensor + >>> from torchmetrics.regression import MeanSquaredLogError + >>> target = tensor([2.5, 5, 4, 8]) + >>> preds = tensor([3, 5, 2.5, 7]) + >>> mean_squared_log_error = MeanSquaredLogError() + >>> mean_squared_log_error(preds, target) + tensor(0.0397) + + .. attention:: + Half precision is only support on GPU for this metric. + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + sum_squared_log_error: Tensor + total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + self.add_state("sum_squared_log_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target) + + self.sum_squared_log_error += sum_squared_log_error + self.total += num_obs + + def compute(self) -> Tensor: + """Compute mean squared logarithmic error over state.""" + return _mean_squared_log_error_compute(self.sum_squared_log_error, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import MeanSquaredLogError + >>> metric = MeanSquaredLogError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import MeanSquaredLogError + >>> metric = MeanSquaredLogError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mae.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mae.py new file mode 100644 index 0000000000000000000000000000000000000000..da95b2b2d90e316d0c2a5d2523244b71dd7cfd48 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mae.py @@ -0,0 +1,144 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.regression.mae import _mean_absolute_error_compute, _mean_absolute_error_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MeanAbsoluteError.plot"] + + +class MeanAbsoluteError(Metric): + r"""`Compute Mean Absolute Error`_ (MAE). + + .. math:: \text{MAE} = \frac{1}{N}\sum_i^N | y_i - \hat{y_i} | + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``mean_absolute_error`` (:class:`~torch.Tensor`): A tensor with the mean absolute error over the state + + Args: + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import tensor + >>> from torchmetrics.regression import MeanAbsoluteError + >>> target = tensor([3.0, -0.5, 2.0, 7.0]) + >>> preds = tensor([2.5, 0.0, 2.0, 8.0]) + >>> mean_absolute_error = MeanAbsoluteError() + >>> mean_absolute_error(preds, target) + tensor(0.5000) + + Example:: + Multioutput mse computation: + + >>> from torch import tensor + >>> from torchmetrics.regression import MeanAbsoluteError + >>> target = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) + >>> preds = tensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) + >>> mean_absolute_error = MeanAbsoluteError(num_outputs=3) + >>> mean_absolute_error(preds, target) + tensor([1., 2., 3.]) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + sum_abs_error: Tensor + total: Tensor + + def __init__( + self, + num_outputs: int = 1, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if not (isinstance(num_outputs, int) and num_outputs > 0): + raise ValueError(f"Expected num_outputs to be a positive integer but got {num_outputs}") + self.num_outputs = num_outputs + + self.add_state("sum_abs_error", default=torch.zeros(num_outputs), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_abs_error, num_obs = _mean_absolute_error_update(preds, target, num_outputs=self.num_outputs) + + self.sum_abs_error += sum_abs_error + self.total += num_obs + + def compute(self) -> Tensor: + """Compute mean absolute error over state.""" + return _mean_absolute_error_compute(self.sum_abs_error, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import MeanAbsoluteError + >>> metric = MeanAbsoluteError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import MeanAbsoluteError + >>> metric = MeanAbsoluteError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mape.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee1eaf61f7f6a91b00a96731b09c518e6603ba0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mape.py @@ -0,0 +1,135 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.regression.mape import ( + _mean_absolute_percentage_error_compute, + _mean_absolute_percentage_error_update, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MeanAbsolutePercentageError.plot"] + + +class MeanAbsolutePercentageError(Metric): + r"""Compute `Mean Absolute Percentage Error`_ (MAPE). + + .. math:: \text{MAPE} = \frac{1}{n}\sum_{i=1}^n\frac{| y_i - \hat{y_i} |}{\max(\epsilon, | y_i |)} + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``mean_abs_percentage_error`` (:class:`~torch.Tensor`): A tensor with the mean absolute percentage error over + state + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Note: + MAPE output is a non-negative floating point. Best result is ``0.0`` . But it is important to note that, + bad predictions, can lead to arbitrarily large values. Especially when some ``target`` values are close to 0. + This `MAPE implementation returns`_ a very large number instead of ``inf``. + + Example: + >>> from torch import tensor + >>> from torchmetrics.regression import MeanAbsolutePercentageError + >>> target = tensor([1, 10, 1e6]) + >>> preds = tensor([0.9, 15, 1.2e6]) + >>> mean_abs_percentage_error = MeanAbsolutePercentageError() + >>> mean_abs_percentage_error(preds, target) + tensor(0.2667) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + sum_abs_per_error: Tensor + total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + self.add_state("sum_abs_per_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_abs_per_error, num_obs = _mean_absolute_percentage_error_update(preds, target) + + self.sum_abs_per_error += sum_abs_per_error + self.total += num_obs + + def compute(self) -> Tensor: + """Compute mean absolute percentage error over state.""" + return _mean_absolute_percentage_error_compute(self.sum_abs_per_error, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import MeanAbsolutePercentageError + >>> metric = MeanAbsolutePercentageError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import MeanAbsolutePercentageError + >>> metric = MeanAbsolutePercentageError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/minkowski.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/minkowski.py new file mode 100644 index 0000000000000000000000000000000000000000..50785f5425c25124fe562328f9988cc705155729 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/minkowski.py @@ -0,0 +1,122 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.regression.minkowski import _minkowski_distance_compute, _minkowski_distance_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.exceptions import TorchMetricsUserError +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MinkowskiDistance.plot"] + + +class MinkowskiDistance(Metric): + r"""Compute `Minkowski Distance`_. + + .. math:: + d_{\text{Minkowski}} = \sum_{i}^N (| y_i - \hat{y_i} |^p)^\frac{1}{p} + + where + :math: `y` is a tensor of target values, + :math: `\hat{y}` is a tensor of predictions, + :math: `\p` is a non-negative integer or floating-point number + + This metric can be seen as generalized version of the standard euclidean distance which corresponds to minkowski + distance with p=2. + + Args: + p: int or float larger than 1, exponent to which the difference between preds and target is to be raised + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.regression import MinkowskiDistance + >>> target = tensor([1.0, 2.8, 3.5, 4.5]) + >>> preds = tensor([6.1, 2.11, 3.1, 5.6]) + >>> minkowski_distance = MinkowskiDistance(3) + >>> minkowski_distance(preds, target) + tensor(5.1220) + + """ + + is_differentiable: Optional[bool] = True + higher_is_better: Optional[bool] = False + full_state_update: Optional[bool] = False + plot_lower_bound: float = 0.0 + + minkowski_dist_sum: Tensor + + def __init__(self, p: float, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not (isinstance(p, (float, int)) and p >= 1): + raise TorchMetricsUserError(f"Argument ``p`` must be a float or int greater than 1, but got {p}") + + self.p = p + self.add_state("minkowski_dist_sum", default=tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, targets: Tensor) -> None: + """Update state with predictions and targets.""" + minkowski_dist_sum = _minkowski_distance_update(preds, targets, self.p) + self.minkowski_dist_sum += minkowski_dist_sum + + def compute(self) -> Tensor: + """Compute metric.""" + return _minkowski_distance_compute(self.minkowski_dist_sum, self.p) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import MinkowskiDistance + >>> metric = MinkowskiDistance(p=3) + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import MinkowskiDistance + >>> metric = MinkowskiDistance(p=3) + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mse.py new file mode 100644 index 0000000000000000000000000000000000000000..b82738ace4aae612694fab7a2bde2cee51699029 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/mse.py @@ -0,0 +1,152 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.regression.mse import _mean_squared_error_compute, _mean_squared_error_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MeanSquaredError.plot"] + + +class MeanSquaredError(Metric): + r"""Compute `mean squared error`_ (MSE). + + .. math:: \text{MSE} = \frac{1}{N}\sum_i^N(y_i - \hat{y_i})^2 + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``mean_squared_error`` (:class:`~torch.Tensor`): A tensor with the mean squared error + + Args: + squared: If True returns MSE value, if False returns RMSE value. + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example:: + Single output mse computation: + + >>> from torch import tensor + >>> from torchmetrics.regression import MeanSquaredError + >>> target = tensor([2.5, 5.0, 4.0, 8.0]) + >>> preds = tensor([3.0, 5.0, 2.5, 7.0]) + >>> mean_squared_error = MeanSquaredError() + >>> mean_squared_error(preds, target) + tensor(0.8750) + + Example:: + Multioutput mse computation: + + >>> from torch import tensor + >>> from torchmetrics.regression import MeanSquaredError + >>> target = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) + >>> preds = tensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) + >>> mean_squared_error = MeanSquaredError(num_outputs=3) + >>> mean_squared_error(preds, target) + tensor([1., 4., 9.]) + + """ + + is_differentiable = True + higher_is_better = False + full_state_update = False + plot_lower_bound: float = 0.0 + + sum_squared_error: Tensor + total: Tensor + + def __init__( + self, + squared: bool = True, + num_outputs: int = 1, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if not isinstance(squared, bool): + raise ValueError(f"Expected argument `squared` to be a boolean but got {squared}") + self.squared = squared + + if not (isinstance(num_outputs, int) and num_outputs > 0): + raise ValueError(f"Expected num_outputs to be a positive integer but got {num_outputs}") + self.num_outputs = num_outputs + + self.add_state("sum_squared_error", default=torch.zeros(num_outputs), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=self.num_outputs) + + self.sum_squared_error += sum_squared_error + self.total += num_obs + + def compute(self) -> Tensor: + """Compute mean squared error over state.""" + return _mean_squared_error_compute(self.sum_squared_error, self.total, squared=self.squared) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import MeanSquaredError + >>> metric = MeanSquaredError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import MeanSquaredError + >>> metric = MeanSquaredError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/nrmse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/nrmse.py new file mode 100644 index 0000000000000000000000000000000000000000..bb44ae9c905a84b73dc6eb97c8d0ab0d9676a2c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/nrmse.py @@ -0,0 +1,280 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.regression.nrmse import ( + _mean_squared_error_update, + _normalized_root_mean_squared_error_compute, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["NormalizedRootMeanSquaredError.plot"] + + +def _final_aggregation( + min_val: Tensor, + max_val: Tensor, + mean_val: Tensor, + var_val: Tensor, + target_squared: Tensor, + total: Tensor, + normalization: Literal["mean", "range", "std", "l2"] = "mean", +) -> Tensor: + """In the case of multiple devices we need to aggregate the statistics from the different devices.""" + if len(min_val) == 1: + if normalization == "mean": + return mean_val[0] + if normalization == "range": + return max_val[0] - min_val[0] + if normalization == "std": + return var_val[0] + if normalization == "l2": + return target_squared[0] + + min_val_1, max_val_1, mean_val_1, var_val_1, target_squared_1, total_1 = ( + min_val[0], + max_val[0], + mean_val[0], + var_val[0], + target_squared[0], + total[0], + ) + for i in range(1, len(min_val)): + min_val_2, max_val_2, mean_val_2, var_val_2, target_squared_2, total_2 = ( + min_val[i], + max_val[i], + mean_val[i], + var_val[i], + target_squared[i], + total[i], + ) + # update total and mean + total = total_1 + total_2 + mean = (total_1 * mean_val_1 + total_2 * mean_val_2) / total + + # update variance + _temp = (total_1 + 1) * mean - total_1 * mean_val_1 + var_val_1 += (_temp - mean_val_1) * (_temp - mean) - (_temp - mean) ** 2 + _temp = (total_2 + 1) * mean - total_2 * mean_val_2 + var_val_2 += (_temp - mean_val_2) * (_temp - mean) - (_temp - mean) ** 2 + var = var_val_1 + var_val_2 + + # update min and max and target squared + min_val = torch.min(min_val_1, min_val_2) + max_val = torch.max(max_val_1, max_val_2) + target_squared = target_squared_1 + target_squared_2 + + if normalization == "mean": + return mean + if normalization == "range": + return max_val - min_val + if normalization == "std": + return (var / total).sqrt() + return target_squared.sqrt() + + +class NormalizedRootMeanSquaredError(Metric): + r"""Calculates the `Normalized Root Mean Squared Error`_ (NRMSE) also know as scatter index. + + The metric is defined as: + + .. math:: + \text{NRMSE} = \frac{\text{RMSE}}{\text{denom}} + + where RMSE is the root mean squared error and `denom` is the normalization factor. The normalization factor can be + either be the mean, range, standard deviation or L2 norm of the target, which can be set using the `normalization` + argument. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``nrmse`` (:class:`~torch.Tensor`): A tensor with the mean squared error + + Args: + normalization: type of normalization to be applied. Choose from "mean", "range", "std", "l2" which corresponds + to normalizing the RMSE by the mean of the target, the range of the target, the standard deviation of the + target or the L2 norm of the target. + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example:: + Single output normalized root mean squared error computation: + + >>> import torch + >>> from torchmetrics import NormalizedRootMeanSquaredError + >>> target = torch.tensor([2.5, 5.0, 4.0, 8.0]) + >>> preds = torch.tensor([3.0, 5.0, 2.5, 7.0]) + >>> nrmse = NormalizedRootMeanSquaredError(normalization="mean") + >>> nrmse(preds, target) + tensor(0.1919) + >>> nrmse = NormalizedRootMeanSquaredError(normalization="range") + >>> nrmse(preds, target) + tensor(0.1701) + + Example:: + Multioutput normalized root mean squared error computation: + + >>> import torch + >>> from torchmetrics import NormalizedRootMeanSquaredError + >>> preds = torch.tensor([[0., 1], [2, 3], [4, 5], [6, 7]]) + >>> target = torch.tensor([[0., 1], [3, 3], [4, 5], [8, 9]]) + >>> nrmse = NormalizedRootMeanSquaredError(num_outputs=2) + >>> nrmse(preds, target) + tensor([0.2981, 0.2222]) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = True + plot_lower_bound: float = 0.0 + + sum_squared_error: Tensor + total: Tensor + min_val: Tensor + max_val: Tensor + target_squared: Tensor + mean_val: Tensor + var_val: Tensor + + def __init__( + self, + normalization: Literal["mean", "range", "std", "l2"] = "mean", + num_outputs: int = 1, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if normalization not in ("mean", "range", "std", "l2"): + raise ValueError( + f"Argument `normalization` should be either 'mean', 'range', 'std' or 'l2', but got {normalization}" + ) + self.normalization = normalization + + if not (isinstance(num_outputs, int) and num_outputs > 0): + raise ValueError(f"Expected num_outputs to be a positive integer but got {num_outputs}") + self.num_outputs = num_outputs + + self.add_state("sum_squared_error", default=torch.zeros(num_outputs), dist_reduce_fx="sum") + self.add_state("total", default=torch.zeros(num_outputs), dist_reduce_fx=None) + self.add_state("min_val", default=float("Inf") * torch.ones(self.num_outputs), dist_reduce_fx=None) + self.add_state("max_val", default=-float("Inf") * torch.ones(self.num_outputs), dist_reduce_fx=None) + self.add_state("mean_val", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("var_val", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("target_squared", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets. + + See `mean_squared_error_update` for details. + + """ + sum_squared_error, num_obs = _mean_squared_error_update(preds, target, self.num_outputs) + self.sum_squared_error += sum_squared_error + target = target.view(-1) if self.num_outputs == 1 else target + + # Update min and max and target squared + self.min_val = torch.minimum(target.min(dim=0).values, self.min_val) + self.max_val = torch.maximum(target.max(dim=0).values, self.max_val) + self.target_squared += (target**2).sum(dim=0) + + # Update mean and variance + new_mean = (self.total * self.mean_val + target.sum(dim=0)) / (self.total + num_obs) + self.total += num_obs + new_var = ((target - new_mean) * (target - self.mean_val)).sum(dim=0) + self.mean_val = new_mean + self.var_val += new_var + + def compute(self) -> Tensor: + """Computes NRMSE over state. + + See `mean_squared_error_compute` for details. + + """ + if (self.num_outputs == 1 and self.mean_val.numel() > 1) or (self.num_outputs > 1 and self.mean_val.ndim > 1): + denom = _final_aggregation( + min_val=self.min_val, + max_val=self.max_val, + mean_val=self.mean_val, + var_val=self.var_val, + target_squared=self.target_squared, + total=self.total, + normalization=self.normalization, + ) + total = self.total.squeeze().sum(dim=0) + else: + if self.normalization == "mean": + denom = self.mean_val + elif self.normalization == "range": + denom = self.max_val - self.min_val + elif self.normalization == "std": + denom = torch.sqrt(self.var_val / self.total) + else: + denom = torch.sqrt(self.target_squared) + total = self.total + return _normalized_root_mean_squared_error_compute(self.sum_squared_error, total, denom) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import NormalizedRootMeanSquaredError + >>> metric = NormalizedRootMeanSquaredError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import NormalizedRootMeanSquaredError + >>> metric = NormalizedRootMeanSquaredError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/pearson.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/pearson.py new file mode 100644 index 0000000000000000000000000000000000000000..4e76921788bd8cf5d045848ded37f1b5f2278216 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/pearson.py @@ -0,0 +1,264 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.pearson import _pearson_corrcoef_compute, _pearson_corrcoef_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["PearsonCorrCoef.plot"] + + +def _final_aggregation( + means_x: torch.Tensor, + means_y: torch.Tensor, + maxs_abs_x: torch.Tensor, + maxs_abs_y: torch.Tensor, + vars_x: torch.Tensor, + vars_y: torch.Tensor, + corrs_xy: torch.Tensor, + nbs: torch.Tensor, + eps: float = 1e-10, +) -> tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor +]: + """Aggregate the statistics from multiple devices. + + Formula taken from here: `Parallel algorithm for calculating variance + `_ + + We use `eps` to avoid division by zero when `n1` and `n2` are both zero. Generally, the value of `eps` should not + matter, as if `n1` and `n2` are both zero, all the states will also be zero. + + """ + if len(means_x) == 1: + return means_x[0], means_y[0], maxs_abs_x[0], maxs_abs_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0] + mx1 = means_x[0] + my1 = means_y[0] + max1 = maxs_abs_x[0] + may1 = maxs_abs_y[0] + vx1 = vars_x[0] + vy1 = vars_y[0] + cxy1 = corrs_xy[0] + n1 = nbs[0] + for i in range(1, len(means_x)): + mx2 = means_x[i] + my2 = means_y[i] + max2 = maxs_abs_x[i] + may2 = maxs_abs_y[i] + vx2 = vars_x[i] + vy2 = vars_y[i] + cxy2 = corrs_xy[i] + n2 = nbs[i] + # count + nb = torch.where(torch.logical_or(n1, n2), n1 + n2, eps) + # mean_x + mean_x = (n1 * mx1 + n2 * mx2) / nb + # mean_y + mean_y = (n1 * my1 + n2 * my2) / nb + # intermediates for running variances + n12_b = n1 * n2 / nb + delta_x = mx2 - mx1 + delta_y = my2 - my1 + # var_x + var_x = vx1 + vx2 + n12_b * delta_x**2 + # var_y + var_y = vy1 + vy2 + n12_b * delta_y**2 + # corr_xy + corr_xy = cxy1 + cxy2 + n12_b * delta_x * delta_y + max_abs_dev_x = torch.maximum(max1, max2) + max_abs_dev_y = torch.maximum(may1, may2) + + mx1 = mean_x + my1 = mean_y + max1 = max_abs_dev_x + may1 = max_abs_dev_y + vx1 = var_x + vy1 = var_y + cxy1 = corr_xy + n1 = nb + return mean_x, mean_y, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb + + +class PearsonCorrCoef(Metric): + r"""Compute `Pearson Correlation Coefficient`_. + + .. math:: + P_{corr}(x,y) = \frac{cov(x,y)}{\sigma_x \sigma_y} + + Where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): either single output float tensor with shape ``(N,)`` + or multioutput float tensor of shape ``(N,d)`` + - ``target`` (:class:`~torch.Tensor`): either single output tensor with shape ``(N,)`` + or multioutput tensor of shape ``(N,d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``pearson`` (:class:`~torch.Tensor`): A tensor with the Pearson Correlation Coefficient + + Args: + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example (single output regression): + >>> from torchmetrics.regression import PearsonCorrCoef + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> pearson = PearsonCorrCoef() + >>> pearson(preds, target) + tensor(0.9849) + + Example (multi output regression): + >>> from torchmetrics.regression import PearsonCorrCoef + >>> target = torch.tensor([[3, -0.5], [2, 7]]) + >>> preds = torch.tensor([[2.5, 0.0], [2, 8]]) + >>> pearson = PearsonCorrCoef(num_outputs=2) + >>> pearson(preds, target) + tensor([1., 1.]) + + """ + + is_differentiable: bool = True + higher_is_better: Optional[bool] = None # both -1 and 1 are optimal + full_state_update: bool = True + plot_lower_bound: float = -1.0 + plot_upper_bound: float = 1.0 + preds: List[Tensor] + target: List[Tensor] + mean_x: Tensor + mean_y: Tensor + max_abs_dev_x: Tensor + max_abs_dev_y: Tensor + var_x: Tensor + var_y: Tensor + corr_xy: Tensor + n_total: Tensor + + def __init__( + self, + num_outputs: int = 1, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(num_outputs, int) and num_outputs < 1: + raise ValueError("Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}") + self.num_outputs = num_outputs + + self.add_state("mean_x", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("mean_y", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("max_abs_dev_x", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("max_abs_dev_y", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("var_x", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("var_y", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("corr_xy", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + self.add_state("n_total", default=torch.zeros(self.num_outputs), dist_reduce_fx=None) + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + ( + self.mean_x, + self.mean_y, + self.max_abs_dev_x, + self.max_abs_dev_y, + self.var_x, + self.var_y, + self.corr_xy, + self.n_total, + ) = _pearson_corrcoef_update( + preds=preds, + target=target, + mean_x=self.mean_x, + mean_y=self.mean_y, + max_abs_dev_x=self.max_abs_dev_x, + max_abs_dev_y=self.max_abs_dev_y, + var_x=self.var_x, + var_y=self.var_y, + corr_xy=self.corr_xy, + num_prior=self.n_total, + num_outputs=self.num_outputs, + ) + + def compute(self) -> Tensor: + """Compute pearson correlation coefficient over state.""" + if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1): + # multiple devices, need further reduction + _, _, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, n_total = _final_aggregation( + means_x=self.mean_x, + means_y=self.mean_y, + maxs_abs_x=self.max_abs_dev_x, + maxs_abs_y=self.max_abs_dev_y, + vars_x=self.var_x, + vars_y=self.var_y, + corrs_xy=self.corr_xy, + nbs=self.n_total, + ) + else: + max_abs_dev_x = self.max_abs_dev_x + max_abs_dev_y = self.max_abs_dev_y + var_x = self.var_x + var_y = self.var_y + corr_xy = self.corr_xy + n_total = self.n_total + return _pearson_corrcoef_compute(max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, n_total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import PearsonCorrCoef + >>> metric = PearsonCorrCoef() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import PearsonCorrCoef + >>> metric = PearsonCorrCoef() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/r2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/r2.py new file mode 100644 index 0000000000000000000000000000000000000000..613dc69a1410cdd2df3e17f391aead71e433a28b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/r2.py @@ -0,0 +1,187 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.regression.r2 import _r2_score_compute, _r2_score_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["R2Score.plot"] + + +class R2Score(Metric): + r"""Compute r2 score also known as `R2 Score_Coefficient Determination`_. + + .. math:: R^2 = 1 - \frac{SS_{res}}{SS_{tot}} + + where :math:`SS_{res}=\sum_i (y_i - f(x_i))^2` is the sum of residual squares, and + :math:`SS_{tot}=\sum_i (y_i - \bar{y})^2` is total sum of squares. Can also calculate + adjusted r2 score given by + + .. math:: R^2_{adj} = 1 - \frac{(1-R^2)(n-1)}{n-k-1} + + where the parameter :math:`k` (the number of independent regressors) should be provided as the `adjusted` argument. + The score is only proper defined when :math:`SS_{tot}\neq 0`, which can happen for near constant targets. In this + case a score of 0 is returned. By definition the score is bounded between :math:`-inf` and 1.0, with 1.0 indicating + perfect prediction, 0 indicating constant prediction and negative values indicating worse than constant prediction. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor with shape ``(N,)`` + or ``(N, M)`` (multioutput) + - ``target`` (:class:`~torch.Tensor`): Ground truth values in float tensor with shape ``(N,)`` + or ``(N, M)`` (multioutput) + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``r2score`` (:class:`~torch.Tensor`): A tensor with the r2 score(s) + + In the case of multioutput, as default the variances will be uniformly averaged over the additional dimensions. + Please see argument ``multioutput`` for changing this behavior. + + Args: + num_outputs: Number of outputs in multioutput setting + adjusted: number of independent regressors for calculating adjusted r2 score. + multioutput: Defines aggregation in the case of multiple output scores. Can be one of the following strings: + + * ``'raw_values'`` returns full set of scores + * ``'uniform_average'`` scores are uniformly averaged + * ``'variance_weighted'`` scores are weighted by their individual variances + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + .. warning:: + Argument ``num_outputs`` in ``R2Score`` has been deprecated because it is no longer necessary and will be + removed in v1.6.0 of TorchMetrics. The number of outputs is now automatically inferred from the shape + of the input tensors. + + Raises: + ValueError: + If ``adjusted`` parameter is not an integer larger or equal to 0. + ValueError: + If ``multioutput`` is not one of ``"raw_values"``, ``"uniform_average"`` or ``"variance_weighted"``. + + Example (single output): + >>> from torch import tensor + >>> from torchmetrics.regression import R2Score + >>> target = tensor([3, -0.5, 2, 7]) + >>> preds = tensor([2.5, 0.0, 2, 8]) + >>> r2score = R2Score() + >>> r2score(preds, target) + tensor(0.9486) + + Example (multioutput): + >>> from torch import tensor + >>> from torchmetrics.regression import R2Score + >>> target = tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = tensor([[0, 2], [-1, 2], [8, -5]]) + >>> r2score = R2Score(multioutput='raw_values') + >>> r2score(preds, target) + tensor([0.9654, 0.9082]) + + """ + + is_differentiable: bool = True + higher_is_better: bool = True + full_state_update: bool = False + plot_upper_bound: float = 1.0 + + sum_squared_error: Tensor + sum_error: Tensor + residual: Tensor + total: Tensor + + def __init__( + self, + adjusted: int = 0, + multioutput: str = "uniform_average", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if adjusted < 0 or not isinstance(adjusted, int): + raise ValueError("`adjusted` parameter should be an integer larger or equal to 0.") + self.adjusted = adjusted + + allowed_multioutput = ("raw_values", "uniform_average", "variance_weighted") + if multioutput not in allowed_multioutput: + raise ValueError( + f"Invalid input to argument `multioutput`. Choose one of the following: {allowed_multioutput}" + ) + self.multioutput = multioutput + + self.add_state("sum_squared_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("sum_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("residual", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_squared_error, sum_error, residual, total = _r2_score_update(preds, target) + + self.sum_squared_error = self.sum_squared_error + sum_squared_error + self.sum_error = self.sum_error + sum_error + self.residual = self.residual + residual + self.total = self.total + total + + def compute(self) -> Tensor: + """Compute r2 score over the metric states.""" + return _r2_score_compute( + self.sum_squared_error, self.sum_error, self.residual, self.total, self.adjusted, self.multioutput + ) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import R2Score + >>> metric = R2Score() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import R2Score + >>> metric = R2Score() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/rse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/rse.py new file mode 100644 index 0000000000000000000000000000000000000000..2776f8c9fdaec3acaf864055f3a867422be65f4d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/rse.py @@ -0,0 +1,145 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.regression.r2 import _r2_score_update +from torchmetrics.functional.regression.rse import _relative_squared_error_compute +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RelativeSquaredError.plot"] + + +class RelativeSquaredError(Metric): + r"""Computes the relative squared error (RSE). + + .. math:: \text{RSE} = \frac{\sum_i^N(y_i - \hat{y_i})^2}{\sum_i^N(y_i - \overline{y})^2} + + Where :math:`y` is a tensor of target values with mean :math:`\overline{y}`, and + :math:`\hat{y}` is a tensor of predictions. + + If num_outputs > 1, the returned value is averaged over all the outputs. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor with shape ``(N,)`` + or ``(N, M)`` (multioutput) + - ``target`` (:class:`~torch.Tensor`): Ground truth values in float tensor with shape ``(N,)`` + or ``(N, M)`` (multioutput) + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``rse`` (:class:`~torch.Tensor`): A tensor with the RSE score(s) + + Args: + num_outputs: Number of outputs in multioutput setting + squared: If True returns RSE value, if False returns RRSE value. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.regression import RelativeSquaredError + >>> target = torch.tensor([3, -0.5, 2, 7]) + >>> preds = torch.tensor([2.5, 0.0, 2, 8]) + >>> relative_squared_error = RelativeSquaredError() + >>> relative_squared_error(preds, target) + tensor(0.0514) + + """ + + is_differentiable = True + higher_is_better = False + full_state_update = False + sum_squared_error: Tensor + sum_error: Tensor + residual: Tensor + total: Tensor + + def __init__( + self, + num_outputs: int = 1, + squared: bool = True, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + self.num_outputs = num_outputs + + self.add_state("sum_squared_error", default=torch.zeros(self.num_outputs), dist_reduce_fx="sum") + self.add_state("sum_error", default=torch.zeros(self.num_outputs), dist_reduce_fx="sum") + self.add_state("residual", default=torch.zeros(self.num_outputs), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0), dist_reduce_fx="sum") + self.squared = squared + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_squared_error, sum_error, residual, total = _r2_score_update(preds, target) + + self.sum_squared_error += sum_squared_error + self.sum_error += sum_error + self.residual += residual + self.total += total + + def compute(self) -> Tensor: + """Computes relative squared error over state.""" + return _relative_squared_error_compute( + self.sum_squared_error, self.sum_error, self.residual, self.total, squared=self.squared + ) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import RelativeSquaredError + >>> metric = RelativeSquaredError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import RelativeSquaredError + >>> metric = RelativeSquaredError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/spearman.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/spearman.py new file mode 100644 index 0000000000000000000000000000000000000000..de94903c8c09d4a6d48c943ba114a943ac53952d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/spearman.py @@ -0,0 +1,150 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor + +from torchmetrics.functional.regression.spearman import _spearman_corrcoef_compute, _spearman_corrcoef_update +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["SpearmanCorrCoef.plot"] + + +class SpearmanCorrCoef(Metric): + r"""Compute `spearmans rank correlation coefficient`_. + + .. math: + r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}} + + where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables :math:`x` and :math:`y`. + Spearmans correlations coefficient corresponds to the standard pearsons correlation coefficient calculated + on the rank variables. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model in float tensor with shape ``(N,d)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth values in float tensor with shape ``(N,d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``spearman`` (:class:`~torch.Tensor`): A tensor with the spearman correlation(s) + + Args: + num_outputs: Number of outputs in multioutput setting + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example (single output regression): + >>> from torch import tensor + >>> from torchmetrics.regression import SpearmanCorrCoef + >>> target = tensor([3, -0.5, 2, 7]) + >>> preds = tensor([2.5, 0.0, 2, 8]) + >>> spearman = SpearmanCorrCoef() + >>> spearman(preds, target) + tensor(1.0000) + + Example (multi output regression): + >>> from torchmetrics.regression import SpearmanCorrCoef + >>> target = tensor([[3, -0.5], [2, 7]]) + >>> preds = tensor([[2.5, 0.0], [2, 8]]) + >>> spearman = SpearmanCorrCoef(num_outputs=2) + >>> spearman(preds, target) + tensor([1.0000, 1.0000]) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = -1.0 + plot_upper_bound: float = 1.0 + + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + num_outputs: int = 1, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + rank_zero_warn( + "Metric `SpearmanCorrcoef` will save all targets and predictions in the buffer." + " For large datasets, this may lead to large memory footprint." + ) + if not isinstance(num_outputs, int) and num_outputs < 1: + raise ValueError(f"Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}") + self.num_outputs = num_outputs + + self.add_state("preds", default=[], dist_reduce_fx="cat") + self.add_state("target", default=[], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + preds, target = _spearman_corrcoef_update(preds, target, num_outputs=self.num_outputs) + self.preds.append(preds.to(self.dtype)) + self.target.append(target.to(self.dtype)) + + def compute(self) -> Tensor: + """Compute Spearman's correlation coefficient.""" + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + return _spearman_corrcoef_compute(preds, target) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import SpearmanCorrCoef + >>> metric = SpearmanCorrCoef() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import SpearmanCorrCoef + >>> metric = SpearmanCorrCoef() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/symmetric_mape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/symmetric_mape.py new file mode 100644 index 0000000000000000000000000000000000000000..a1c601a2a16009eed5d22ffb317d810594bf0db4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/symmetric_mape.py @@ -0,0 +1,129 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.regression.symmetric_mape import ( + _symmetric_mean_absolute_percentage_error_compute, + _symmetric_mean_absolute_percentage_error_update, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["SymmetricMeanAbsolutePercentageError.plot"] + + +class SymmetricMeanAbsolutePercentageError(Metric): + r"""Compute symmetric mean absolute percentage error (`SMAPE`_). + + .. math:: \text{SMAPE} = \frac{2}{n}\sum_1^n\frac{| y_i - \hat{y_i} |}{\max(| y_i | + | \hat{y_i} |, \epsilon)} + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth values + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``smape`` (:class:`~torch.Tensor`): A tensor with non-negative floating point smape value between 0 and 2 + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.regression import SymmetricMeanAbsolutePercentageError + >>> target = tensor([1, 10, 1e6]) + >>> preds = tensor([0.9, 15, 1.2e6]) + >>> smape = SymmetricMeanAbsolutePercentageError() + >>> smape(preds, target) + tensor(0.2290) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 2.0 + + sum_abs_per_error: Tensor + total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + self.add_state("sum_abs_per_error", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_abs_per_error, num_obs = _symmetric_mean_absolute_percentage_error_update(preds, target) + + self.sum_abs_per_error += sum_abs_per_error + self.total += num_obs + + def compute(self) -> Tensor: + """Compute mean absolute percentage error over state.""" + return _symmetric_mean_absolute_percentage_error_compute(self.sum_abs_per_error, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import SymmetricMeanAbsolutePercentageError + >>> metric = SymmetricMeanAbsolutePercentageError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import SymmetricMeanAbsolutePercentageError + >>> metric = SymmetricMeanAbsolutePercentageError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/tweedie_deviance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/tweedie_deviance.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd10070e7ba497c093a77f1385d5868b0078bde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/tweedie_deviance.py @@ -0,0 +1,153 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.tweedie_deviance import ( + _tweedie_deviance_score_compute, + _tweedie_deviance_score_update, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["TweedieDevianceScore.plot"] + + +class TweedieDevianceScore(Metric): + r"""Compute the `Tweedie Deviance Score`_. + + .. math:: + deviance\_score(\hat{y},y) = + \begin{cases} + (\hat{y} - y)^2, & \text{for }p=0\\ + 2 * (y * log(\frac{y}{\hat{y}}) + \hat{y} - y), & \text{for }p=1\\ + 2 * (log(\frac{\hat{y}}{y}) + \frac{y}{\hat{y}} - 1), & \text{for }p=2\\ + 2 * (\frac{(max(y,0))^{2 - p}}{(1 - p)(2 - p)} - \frac{y(\hat{y})^{1 - p}}{1 - p} + \frac{( + \hat{y})^{2 - p}}{2 - p}), & \text{otherwise} + \end{cases} + + where :math:`y` is a tensor of targets values, :math:`\hat{y}` is a tensor of predictions, and + :math:`p` is the `power`. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,...)`` + - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,...)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``deviance_score`` (:class:`~torch.Tensor`): A tensor with the deviance score + + Args: + power: + + - power < 0 : Extreme stable distribution. (Requires: preds > 0.) + - power = 0 : Normal distribution. (Requires: targets and preds can be any real numbers.) + - power = 1 : Poisson distribution. (Requires: targets >= 0 and y_pred > 0.) + - 1 < p < 2 : Compound Poisson distribution. (Requires: targets >= 0 and preds > 0.) + - power = 2 : Gamma distribution. (Requires: targets > 0 and preds > 0.) + - power = 3 : Inverse Gaussian distribution. (Requires: targets > 0 and preds > 0.) + - otherwise : Positive stable distribution. (Requires: targets > 0 and preds > 0.) + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.regression import TweedieDevianceScore + >>> targets = torch.tensor([1.0, 2.0, 3.0, 4.0]) + >>> preds = torch.tensor([4.0, 3.0, 2.0, 1.0]) + >>> deviance_score = TweedieDevianceScore(power=2) + >>> deviance_score(preds, targets) + tensor(1.2083) + + """ + + is_differentiable: bool = True + higher_is_better = None + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + sum_deviance_score: Tensor + num_observations: Tensor + + def __init__( + self, + power: float = 0.0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if 0 < power < 1: + raise ValueError(f"Deviance Score is not defined for power={power}.") + + self.power: float = power + + self.add_state("sum_deviance_score", torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("num_observations", torch.tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, targets: Tensor) -> None: + """Update metric states with predictions and targets.""" + sum_deviance_score, num_observations = _tweedie_deviance_score_update(preds, targets, self.power) + + self.sum_deviance_score += sum_deviance_score + self.num_observations += num_observations + + def compute(self) -> Tensor: + """Compute metric.""" + return _tweedie_deviance_score_compute(self.sum_deviance_score, self.num_observations) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import TweedieDevianceScore + >>> metric = TweedieDevianceScore() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import TweedieDevianceScore + >>> metric = TweedieDevianceScore() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/wmape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/wmape.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c532f145a11fc01cfa120573e48bbc722b440f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/regression/wmape.py @@ -0,0 +1,128 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.regression.wmape import ( + _weighted_mean_absolute_percentage_error_compute, + _weighted_mean_absolute_percentage_error_update, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["WeightedMeanAbsolutePercentageError.plot"] + + +class WeightedMeanAbsolutePercentageError(Metric): + r"""Compute weighted mean absolute percentage error (`WMAPE`_). + + The output of WMAPE metric is a non-negative floating point, where the optimal value is 0. It is computes as: + + .. math:: + \text{WMAPE} = \frac{\sum_{t=1}^n | y_t - \hat{y}_t | }{\sum_{t=1}^n |y_t| } + + Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Predictions from model + - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)`` + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``wmape`` (:class:`~torch.Tensor`): A tensor with non-negative floating point wmape value between 0 and 1 + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import randn + >>> preds = randn(20,) + >>> target = randn(20,) + >>> wmape = WeightedMeanAbsolutePercentageError() + >>> wmape(preds, target) + tensor(1.3967) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + sum_abs_error: Tensor + sum_scale: Tensor + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.add_state("sum_abs_error", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("sum_scale", default=torch.tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + sum_abs_error, sum_scale = _weighted_mean_absolute_percentage_error_update(preds, target) + + self.sum_abs_error += sum_abs_error + self.sum_scale += sum_scale + + def compute(self) -> Tensor: + """Compute weighted mean absolute percentage error over state.""" + return _weighted_mean_absolute_percentage_error_compute(self.sum_abs_error, self.sum_scale) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting a single value + >>> from torchmetrics.regression import WeightedMeanAbsolutePercentageError + >>> metric = WeightedMeanAbsolutePercentageError() + >>> metric.update(randn(10,), randn(10,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> from torch import randn + >>> # Example plotting multiple values + >>> from torchmetrics.regression import WeightedMeanAbsolutePercentageError + >>> metric = WeightedMeanAbsolutePercentageError() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(randn(10,), randn(10,))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b770bfe49fd5b30e5215562cddccd15e77ec066f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/__init__.py @@ -0,0 +1,37 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.retrieval.auroc import RetrievalAUROC +from torchmetrics.retrieval.average_precision import RetrievalMAP +from torchmetrics.retrieval.fall_out import RetrievalFallOut +from torchmetrics.retrieval.hit_rate import RetrievalHitRate +from torchmetrics.retrieval.ndcg import RetrievalNormalizedDCG +from torchmetrics.retrieval.precision import RetrievalPrecision +from torchmetrics.retrieval.precision_recall_curve import RetrievalPrecisionRecallCurve, RetrievalRecallAtFixedPrecision +from torchmetrics.retrieval.r_precision import RetrievalRPrecision +from torchmetrics.retrieval.recall import RetrievalRecall +from torchmetrics.retrieval.reciprocal_rank import RetrievalMRR + +__all__ = [ + "RetrievalAUROC", + "RetrievalFallOut", + "RetrievalHitRate", + "RetrievalMAP", + "RetrievalMRR", + "RetrievalNormalizedDCG", + "RetrievalPrecision", + "RetrievalPrecisionRecallCurve", + "RetrievalRPrecision", + "RetrievalRecall", + "RetrievalRecallAtFixedPrecision", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/_deprecated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..45bff9431f2d282ce21c4d48c5a37e97392763aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/_deprecated.py @@ -0,0 +1,278 @@ +from typing import Any, Optional + +from torchmetrics.retrieval.average_precision import RetrievalMAP +from torchmetrics.retrieval.fall_out import RetrievalFallOut +from torchmetrics.retrieval.hit_rate import RetrievalHitRate +from torchmetrics.retrieval.ndcg import RetrievalNormalizedDCG +from torchmetrics.retrieval.precision import RetrievalPrecision +from torchmetrics.retrieval.precision_recall_curve import RetrievalPrecisionRecallCurve, RetrievalRecallAtFixedPrecision +from torchmetrics.retrieval.r_precision import RetrievalRPrecision +from torchmetrics.retrieval.recall import RetrievalRecall +from torchmetrics.retrieval.reciprocal_rank import RetrievalMRR +from torchmetrics.utilities.prints import _deprecated_root_import_class + + +class _RetrievalFallOut(RetrievalFallOut): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> rfo = _RetrievalFallOut(top_k=2) + >>> rfo(preds, target, indexes=indexes) + tensor(0.5000) + + """ + + def __init__( + self, + empty_target_action: str = "pos", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("RetrievalFallOut", "retrieval") + super().__init__(empty_target_action=empty_target_action, ignore_index=ignore_index, top_k=top_k, **kwargs) + + +class _RetrievalHitRate(RetrievalHitRate): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([True, False, False, False, True, False, True]) + >>> hr2 = _RetrievalHitRate(top_k=2) + >>> hr2(preds, target, indexes=indexes) + tensor(0.5000) + + """ + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("RetrievalHitRate", "retrieval") + super().__init__(empty_target_action=empty_target_action, ignore_index=ignore_index, top_k=top_k, **kwargs) + + +class _RetrievalMAP(RetrievalMAP): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> rmap = _RetrievalMAP() + >>> rmap(preds, target, indexes=indexes) + tensor(0.7917) + + """ + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("RetrievalMAP", "retrieval") + super().__init__(empty_target_action=empty_target_action, ignore_index=ignore_index, top_k=top_k, **kwargs) + + +class _RetrievalRecall(RetrievalRecall): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> r2 = _RetrievalRecall(top_k=2) + >>> r2(preds, target, indexes=indexes) + tensor(0.7500) + + """ + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("RetrievalRecall", "retrieval") + super().__init__(empty_target_action=empty_target_action, ignore_index=ignore_index, top_k=top_k, **kwargs) + + +class _RetrievalRPrecision(RetrievalRPrecision): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> p2 = _RetrievalRPrecision() + >>> p2(preds, target, indexes=indexes) + tensor(0.7500) + + """ + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("RetrievalRPrecision", "retrieval") + super().__init__(empty_target_action=empty_target_action, ignore_index=ignore_index, **kwargs) + + +class _RetrievalNormalizedDCG(RetrievalNormalizedDCG): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> ndcg = _RetrievalNormalizedDCG() + >>> ndcg(preds, target, indexes=indexes) + tensor(0.8467) + + """ + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("RetrievalNormalizedDCG", "retrieval") + super().__init__(empty_target_action=empty_target_action, ignore_index=ignore_index, top_k=top_k, **kwargs) + + +class _RetrievalPrecision(RetrievalPrecision): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> p2 = _RetrievalPrecision(top_k=2) + >>> p2(preds, target, indexes=indexes) + tensor(0.5000) + + """ + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + adaptive_k: bool = False, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("", "retrieval") + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + top_k=top_k, + adaptive_k=adaptive_k, + **kwargs, + ) + + +class _RetrievalPrecisionRecallCurve(RetrievalPrecisionRecallCurve): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1]) + >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5]) + >>> target = tensor([True, False, False, True, True, False, True]) + >>> r = _RetrievalPrecisionRecallCurve(max_k=4) + >>> precisions, recalls, top_k = r(preds, target, indexes=indexes) + >>> precisions + tensor([1.0000, 0.5000, 0.6667, 0.5000]) + >>> recalls + tensor([0.5000, 0.5000, 1.0000, 1.0000]) + >>> top_k + tensor([1, 2, 3, 4]) + + """ + + def __init__( + self, + max_k: Optional[int] = None, + adaptive_k: bool = False, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("", "retrieval") + super().__init__( + max_k=max_k, + adaptive_k=adaptive_k, + empty_target_action=empty_target_action, + ignore_index=ignore_index, + **kwargs, + ) + + +class _RetrievalRecallAtFixedPrecision(RetrievalRecallAtFixedPrecision): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1]) + >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5]) + >>> target = tensor([True, False, False, True, True, False, True]) + >>> r = _RetrievalRecallAtFixedPrecision(min_precision=0.8) + >>> r(preds, target, indexes=indexes) + (tensor(0.5000), tensor(1)) + + """ + + def __init__( + self, + min_precision: float = 0.0, + max_k: Optional[int] = None, + adaptive_k: bool = False, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("RetrievalRecallAtFixedPrecision", "retrieval") + super().__init__( + min_precision=min_precision, + max_k=max_k, + adaptive_k=adaptive_k, + empty_target_action=empty_target_action, + ignore_index=ignore_index, + **kwargs, + ) + + +class _RetrievalMRR(RetrievalMRR): + """Wrapper for deprecated import. + + >>> from torch import tensor + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> mrr = _RetrievalMRR() + >>> mrr(preds, target, indexes=indexes) + tensor(0.7500) + + """ + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("", "retrieval") + super().__init__(empty_target_action=empty_target_action, ignore_index=ignore_index, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/auroc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/auroc.py new file mode 100644 index 0000000000000000000000000000000000000000..6d4382894a4c769e1530fea703e3cf3899a5fcb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/auroc.py @@ -0,0 +1,164 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.auroc import retrieval_auroc +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalAUROC.plot"] + + +class RetrievalAUROC(RetrievalMetric): + """Compute area under the receiver operating characteristic curve (AUROC) for information retrieval. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``auroc@k`` (:class:`~torch.Tensor`): A single-value tensor with the auroc value + of the predictions ``preds`` w.r.t. the labels ``target``. + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: ``None``, which considers them all) + max_fpr: If not ``None``, calculates standardized partial AUC over the range ``[0, max_fpr]``. + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalAUROC + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> rmap = RetrievalAUROC() + >>> rmap(preds, target, indexes=indexes) + tensor(0.7500) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: Literal["error", "skip", "neg", "pos"] = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + max_fpr: Optional[float] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + if top_k is not None and not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + self.top_k = top_k + if max_fpr is not None and not isinstance(max_fpr, float) and 0 < max_fpr <= 1: + raise ValueError(f"Arguments `max_fpr` should be a float in range (0, 1], but got: {max_fpr}") + self.max_fpr = max_fpr + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_auroc(preds, target, top_k=self.top_k, max_fpr=self.max_fpr) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalAUROC + >>> # Example plotting a single value + >>> metric = RetrievalAUROC() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalAUROC + >>> # Example plotting multiple values + >>> metric = RetrievalAUROC() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/average_precision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/average_precision.py new file mode 100644 index 0000000000000000000000000000000000000000..93ecc38cb51c169621c5beb3bbd72f16970d65a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/average_precision.py @@ -0,0 +1,160 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalMAP.plot"] + + +class RetrievalMAP(RetrievalMetric): + """Compute `Mean Average Precision`_. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``map@k`` (:class:`~torch.Tensor`): A single-value tensor with the mean average precision (MAP) + of the predictions ``preds`` w.r.t. the labels ``target``. + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: ``None``, which considers them all) + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalMAP + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> rmap = RetrievalMAP() + >>> rmap(preds, target, indexes=indexes) + tensor(0.7917) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + + if top_k is not None and not isinstance(top_k, int) and top_k <= 0: + raise ValueError(f"Argument ``top_k`` has to be a positive integer or None, but got {top_k}") + self.k = top_k + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_average_precision(preds, target, top_k=self.k) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalMAP + >>> # Example plotting a single value + >>> metric = RetrievalMAP() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalMAP + >>> # Example plotting multiple values + >>> metric = RetrievalMAP() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a0a4f8cc4b2e3ed182813a4ea0641da15b4224 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/base.py @@ -0,0 +1,191 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from abc import ABC, abstractmethod +from typing import Any, Callable, List, Optional, Union + +import torch +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics import Metric +from torchmetrics.utilities.checks import _check_retrieval_inputs +from torchmetrics.utilities.data import _flexible_bincount, dim_zero_cat + + +def _retrieval_aggregate( + values: Tensor, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + dim: Optional[int] = None, +) -> Tensor: + """Aggregate the final retrieval values into a single value.""" + if aggregation == "mean": + return values.mean() if dim is None else values.mean(dim=dim) + if aggregation == "median": + return values.median() if dim is None else values.median(dim=dim).values + if aggregation == "min": + return values.min() if dim is None else values.min(dim=dim).values + if aggregation == "max": + return values.max() if dim is None else values.max(dim=dim).values + return aggregation(values, dim=dim) + + +class RetrievalMetric(Metric, ABC): + """Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + .. hint:: + The ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flattened + to single dimension once provided. + + .. attention:: + Predictions will be first grouped by ``indexes`` and then the real metric, defined by overriding + the `_metric` method, will be computed as the mean of the scores over each query. + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``metric`` (:class:`~torch.Tensor`): A tensor as computed by ``_metric`` if the number of positive targets is + at least 1, otherwise behave as specified by ``self.empty_target_action``. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive + or negative (depend on metric) target. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: + Ignore predictions where the target is equal to this number. + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + + indexes: List[Tensor] + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.allow_non_binary_target = False + + empty_target_action_options = ("error", "skip", "neg", "pos") + if empty_target_action not in empty_target_action_options: + raise ValueError(f"Argument `empty_target_action` received a wrong value `{empty_target_action}`.") + self.empty_target_action = empty_target_action + + if ignore_index is not None and not isinstance(ignore_index, int): + raise ValueError("Argument `ignore_index` must be an integer or None.") + self.ignore_index = ignore_index + + if not (aggregation in ("mean", "median", "min", "max") or callable(aggregation)): + raise ValueError( + "Argument `aggregation` must be one of `mean`, `median`, `min`, `max` or a custom callable function" + f"which takes tensor of values, but got {aggregation}." + ) + self.aggregation = aggregation + + self.add_state("indexes", default=[], dist_reduce_fx=None) + self.add_state("preds", default=[], dist_reduce_fx=None) + self.add_state("target", default=[], dist_reduce_fx=None) + + def update(self, preds: Tensor, target: Tensor, indexes: Tensor) -> None: + """Check shape, check and convert dtypes, flatten and add to accumulators.""" + if indexes is None: + raise ValueError("Argument `indexes` cannot be None") + + indexes, preds, target = _check_retrieval_inputs( + indexes, preds, target, allow_non_binary_target=self.allow_non_binary_target, ignore_index=self.ignore_index + ) + + self.indexes.append(indexes) + self.preds.append(preds) + self.target.append(target) + + def compute(self) -> Tensor: + """First concat state ``indexes``, ``preds`` and ``target`` since they were stored as lists. + + After that, compute list of groups that will help in keeping together predictions about the same query. Finally, + for each group compute the ``_metric`` if the number of positive targets is at least 1, otherwise behave as + specified by ``self.empty_target_action``. + + """ + indexes = dim_zero_cat(self.indexes) + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + + indexes, indices = torch.sort(indexes) + preds = preds[indices] + target = target[indices] + + split_sizes = _flexible_bincount(indexes).detach().cpu().tolist() + + res = [] + for mini_preds, mini_target in zip( + torch.split(preds, split_sizes, dim=0), torch.split(target, split_sizes, dim=0) + ): + if not mini_target.sum(): + if self.empty_target_action == "error": + raise ValueError("`compute` method was provided with a query with no positive target.") + if self.empty_target_action == "pos": + res.append(tensor(1.0)) + elif self.empty_target_action == "neg": + res.append(tensor(0.0)) + else: + # ensure list contains only float tensors + res.append(self._metric(mini_preds, mini_target)) + + if res: + return _retrieval_aggregate(torch.stack([x.to(preds) for x in res]), self.aggregation) + return tensor(0.0).to(preds) + + @abstractmethod + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + """Compute a metric over a predictions and target of a single group. + + This method should be overridden by subclasses. + + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/fall_out.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/fall_out.py new file mode 100644 index 0000000000000000000000000000000000000000..9660f0613702b899b1542acb39f3123fd7f738a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/fall_out.py @@ -0,0 +1,199 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import torch +from torch import Tensor, tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out +from torchmetrics.retrieval.base import RetrievalMetric, _retrieval_aggregate +from torchmetrics.utilities.data import _flexible_bincount, dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalFallOut.plot"] + + +class RetrievalFallOut(RetrievalMetric): + """Compute `Fall-out`_. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``fallout@k`` (:class:`~torch.Tensor`): A tensor with the computed metric + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a negative ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: `None`, which considers them all) + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + + Example: + >>> from torchmetrics.retrieval import RetrievalFallOut + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> rfo = RetrievalFallOut(top_k=2) + >>> rfo(preds, target, indexes=indexes) + tensor(0.5000) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: str = "pos", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + + if top_k is not None and not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + self.top_k = top_k + + def compute(self) -> Tensor: + """First concat state ``indexes``, ``preds`` and ``target`` since they were stored as lists. + + After that, compute list of groups that will help in keeping together predictions about the same query. Finally, + for each group compute the `_metric` if the number of negative targets is at least 1, otherwise behave as + specified by `self.empty_target_action`. + + """ + indexes = dim_zero_cat(self.indexes) + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + + indexes, indices = torch.sort(indexes) + preds = preds[indices] + target = target[indices] + + split_sizes = _flexible_bincount(indexes).detach().cpu().tolist() + + res = [] + for mini_preds, mini_target in zip( + torch.split(preds, split_sizes, dim=0), torch.split(target, split_sizes, dim=0) + ): + if not (1 - mini_target).sum(): + if self.empty_target_action == "error": + raise ValueError("`compute` method was provided with a query with no negative target.") + if self.empty_target_action == "pos": + res.append(tensor(1.0)) + elif self.empty_target_action == "neg": + res.append(tensor(0.0)) + else: + # ensure list contains only float tensors + res.append(self._metric(mini_preds, mini_target)) + + return ( + _retrieval_aggregate(torch.stack([x.to(preds) for x in res]), aggregation=self.aggregation) + if res + else tensor(0.0).to(preds) + ) + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_fall_out(preds, target, top_k=self.top_k) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalFallOut + >>> # Example plotting a single value + >>> metric = RetrievalFallOut() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalFallOut + >>> # Example plotting multiple values + >>> metric = RetrievalFallOut() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/hit_rate.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/hit_rate.py new file mode 100644 index 0000000000000000000000000000000000000000..c04ff3ad14d51e399d31d9c4c080b4b39746cd84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/hit_rate.py @@ -0,0 +1,161 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.hit_rate import retrieval_hit_rate +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalHitRate.plot"] + + +class RetrievalHitRate(RetrievalMetric): + """Compute `IR HitRate`. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``hr@k`` (:class:`~torch.Tensor`): A single-value tensor with the hit rate (at ``top_k``) of the predictions + ``preds`` w.r.t. the labels ``target`` + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: ``None``, which considers them all) + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalHitRate + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([True, False, False, False, True, False, True]) + >>> hr2 = RetrievalHitRate(top_k=2) + >>> hr2(preds, target, indexes=indexes) + tensor(0.5000) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + + if top_k is not None and not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + self.top_k = top_k + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_hit_rate(preds, target, top_k=self.top_k) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalHitRate + >>> # Example plotting a single value + >>> metric = RetrievalHitRate() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalHitRate + >>> # Example plotting multiple values + >>> metric = RetrievalHitRate() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/ndcg.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/ndcg.py new file mode 100644 index 0000000000000000000000000000000000000000..afd211cb142f6eb6c4674a9dfaa6337a6fa89e49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/ndcg.py @@ -0,0 +1,162 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.ndcg import retrieval_normalized_dcg +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalNormalizedDCG.plot"] + + +class RetrievalNormalizedDCG(RetrievalMetric): + """Compute `Normalized Discounted Cumulative Gain`_. + + Works with binary or positive integer target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``ndcg@k`` (:class:`~torch.Tensor`): A single-value tensor with the nDCG of the predictions + ``preds`` w.r.t. the labels ``target`` + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: ``None``, which considers them all) + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalNormalizedDCG + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> ndcg = RetrievalNormalizedDCG() + >>> ndcg(preds, target, indexes=indexes) + tensor(0.8467) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + + if top_k is not None and not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + self.top_k = top_k + self.allow_non_binary_target = True + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_normalized_dcg(preds, target, top_k=self.top_k) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalNormalizedDCG + >>> # Example plotting a single value + >>> metric = RetrievalNormalizedDCG() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalNormalizedDCG + >>> # Example plotting multiple values + >>> metric = RetrievalNormalizedDCG() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/precision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..70bf4d9794aa6381b29218f5b8c860970e03e52e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/precision.py @@ -0,0 +1,167 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.precision import retrieval_precision +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalPrecision.plot"] + + +class RetrievalPrecision(RetrievalMetric): + """Compute `IR Precision`_. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``p@k`` (:class:`~torch.Tensor`): A single-value tensor with the precision (at ``top_k``) of the predictions + ``preds`` w.r.t. the labels ``target`` + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: ``None``, which considers them all) + adaptive_k: Adjust ``top_k`` to ``min(k, number of documents)`` for each query + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + ValueError: + If ``adaptive_k`` is not boolean. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalPrecision + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> p2 = RetrievalPrecision(top_k=2) + >>> p2(preds, target, indexes=indexes) + tensor(0.5000) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + adaptive_k: bool = False, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + + if top_k is not None and not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + if not isinstance(adaptive_k, bool): + raise ValueError("`adaptive_k` has to be a boolean") + self.top_k = top_k + self.adaptive_k = adaptive_k + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_precision(preds, target, top_k=self.top_k, adaptive_k=self.adaptive_k) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalPrecision + >>> # Example plotting a single value + >>> metric = RetrievalPrecision() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalPrecision + >>> # Example plotting multiple values + >>> metric = RetrievalPrecision() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/precision_recall_curve.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/precision_recall_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..9eef71c154edc796553c9f90e18ac30151b0710e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/precision_recall_curve.py @@ -0,0 +1,431 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, List, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics import Metric +from torchmetrics.functional.retrieval.precision_recall_curve import retrieval_precision_recall_curve +from torchmetrics.retrieval.base import _retrieval_aggregate +from torchmetrics.utilities.checks import _check_retrieval_inputs +from torchmetrics.utilities.data import _flexible_bincount, dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE, plot_curve + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalPrecisionRecallCurve.plot", "RetrievalRecallAtFixedPrecision.plot"] + + +def _retrieval_recall_at_fixed_precision( + precision: Tensor, + recall: Tensor, + top_k: Tensor, + min_precision: float, +) -> tuple[Tensor, Tensor]: + """Compute maximum recall with condition that corresponding precision >= `min_precision`. + + Args: + top_k: tensor with all possible k + precision: tensor with all values precisions@k for k from top_k tensor + recall: tensor with all values recall@k for k from top_k tensor + min_precision: float value specifying minimum precision threshold. + + Returns: + Maximum recall value, corresponding it best k + + """ + try: + max_recall, best_k = max((r, k) for p, r, k in zip(precision, recall, top_k) if p >= min_precision) + + except ValueError: + max_recall = torch.tensor(0.0, device=recall.device, dtype=recall.dtype) + best_k = torch.tensor(len(top_k)) + + if max_recall == 0.0: + best_k = torch.tensor(len(top_k), device=top_k.device, dtype=top_k.dtype) + + return max_recall, best_k + + +class RetrievalPrecisionRecallCurve(Metric): + """Compute precision-recall pairs for different k (from 1 to `max_k`). + + In a ranked retrieval context, appropriate sets of retrieved documents are naturally given by the top k retrieved + documents. Recall is the fraction of relevant documents retrieved among all the relevant documents. Precision is the + fraction of relevant documents among all the retrieved documents. For each such set, precision and recall values + can be plotted to give a recall-precision curve. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``precisions`` (:class:`~torch.Tensor`): A tensor with the fraction of relevant documents among all the + retrieved documents. + - ``recalls`` (:class:`~torch.Tensor`): A tensor with the fraction of relevant documents retrieved among all the + relevant documents + - ``top_k`` (:class:`~torch.Tensor`): A tensor with k from 1 to `max_k` + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + max_k: Calculate recall and precision for all possible top k from 1 to max_k + (default: `None`, which considers all possible top k) + adaptive_k: adjust `k` to `min(k, number of documents)` for each query + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: + Ignore predictions where the target is equal to this number. + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: + Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``max_k`` parameter is not `None` or not an integer larger than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalPrecisionRecallCurve + >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1]) + >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5]) + >>> target = tensor([True, False, False, True, True, False, True]) + >>> r = RetrievalPrecisionRecallCurve(max_k=4) + >>> precisions, recalls, top_k = r(preds, target, indexes=indexes) + >>> precisions + tensor([1.0000, 0.5000, 0.6667, 0.5000]) + >>> recalls + tensor([0.5000, 0.5000, 1.0000, 1.0000]) + >>> top_k + tensor([1, 2, 3, 4]) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + + indexes: List[Tensor] + preds: List[Tensor] + target: List[Tensor] + + def __init__( + self, + max_k: Optional[int] = None, + adaptive_k: bool = False, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.allow_non_binary_target = False + + empty_target_action_options = ("error", "skip", "neg", "pos") + if empty_target_action not in empty_target_action_options: + raise ValueError(f"Argument `empty_target_action` received a wrong value `{empty_target_action}`.") + + self.empty_target_action = empty_target_action + + if ignore_index is not None and not isinstance(ignore_index, int): + raise ValueError("Argument `ignore_index` must be an integer or None.") + + self.ignore_index = ignore_index + + if (max_k is not None) and not (isinstance(max_k, int) and max_k > 0): + raise ValueError("`max_k` has to be a positive integer or None") + self.max_k = max_k + + if not isinstance(adaptive_k, bool): + raise ValueError("`adaptive_k` has to be a boolean") + self.adaptive_k = adaptive_k + + if not (aggregation in ("mean", "median", "min", "max") or callable(aggregation)): + raise ValueError( + "Argument `aggregation` must be one of `mean`, `median`, `min`, `max` or a custom callable function" + f"which takes tensor of values, but got {aggregation}." + ) + self.aggregation = aggregation + + self.add_state("indexes", default=[], dist_reduce_fx=None) + self.add_state("preds", default=[], dist_reduce_fx=None) + self.add_state("target", default=[], dist_reduce_fx=None) + + def update(self, preds: Tensor, target: Tensor, indexes: Tensor) -> None: + """Check shape, check and convert dtypes, flatten and add to accumulators.""" + if indexes is None: + raise ValueError("Argument `indexes` cannot be None") + + indexes, preds, target = _check_retrieval_inputs( + indexes, preds, target, allow_non_binary_target=self.allow_non_binary_target, ignore_index=self.ignore_index + ) + + self.indexes.append(indexes) + self.preds.append(preds) + self.target.append(target) + + def compute(self) -> tuple[Tensor, Tensor, Tensor]: + """Compute metric.""" + # concat all data + indexes = dim_zero_cat(self.indexes) + preds = dim_zero_cat(self.preds) + target = dim_zero_cat(self.target) + + indexes, indices = torch.sort(indexes) + preds = preds[indices] + target = target[indices] + + split_sizes = _flexible_bincount(indexes).detach().cpu().tolist() + + # don't want to change self.max_k + max_k = self.max_k + if max_k is None: + # set max_k as size of max group by size + max_k = max(split_sizes) + + precisions, recalls = [], [] + + for mini_preds, mini_target in zip( + torch.split(preds, split_sizes, dim=0), torch.split(target, split_sizes, dim=0) + ): + if not mini_target.sum(): + if self.empty_target_action == "error": + raise ValueError("`compute` method was provided with a query with no positive target.") + if self.empty_target_action == "pos": + recalls.append(torch.ones(max_k, device=preds.device)) + precisions.append(torch.ones(max_k, device=preds.device)) + elif self.empty_target_action == "neg": + recalls.append(torch.zeros(max_k, device=preds.device)) + precisions.append(torch.zeros(max_k, device=preds.device)) + else: + precision, recall, _ = retrieval_precision_recall_curve(mini_preds, mini_target, max_k, self.adaptive_k) + + precisions.append(precision) + recalls.append(recall) + + precision = ( + _retrieval_aggregate(torch.stack([x.to(preds) for x in precisions]), aggregation=self.aggregation, dim=0) + if precisions + else torch.zeros(max_k).to(preds) + ) + recall = ( + _retrieval_aggregate(torch.stack([x.to(preds) for x in recalls]), aggregation=self.aggregation, dim=0) + if recalls + else torch.zeros(max_k).to(preds) + ) + top_k = torch.arange(1, max_k + 1, device=preds.device) + + return precision, recall, top_k + + def plot( + self, + curve: Optional[tuple[Tensor, Tensor, Tensor]] = None, + ax: Optional[_AX_TYPE] = None, + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + curve: the output of either `metric.compute` or `metric.forward`. If no value is provided, will + automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalPrecisionRecallCurve + >>> # Example plotting a single value + >>> metric = RetrievalPrecisionRecallCurve() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + """ + curve = curve or self.compute() + return plot_curve( + curve, + ax=ax, + label_names=("False positive rate", "True positive rate"), + name=self.__class__.__name__, + ) + + +class RetrievalRecallAtFixedPrecision(RetrievalPrecisionRecallCurve): + """Compute `IR Recall at fixed Precision`_. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + .. important:: + All ``indexes``, ``preds`` and ``target`` must have the same dimension. + + .. attention:: + Predictions will be first grouped by ``indexes`` and then `RetrievalRecallAtFixedPrecision` + will be computed as the mean of the `RetrievalRecallAtFixedPrecision` over each query. + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``max_recall`` (:class:`~torch.Tensor`): A tensor with the maximum recall value + retrieved documents. + - ``best_k`` (:class:`~torch.Tensor`): A tensor with the best k corresponding to the maximum recall value + + Args: + min_precision: float value specifying minimum precision threshold. + max_k: Calculate recall and precision for all possible top k from 1 to max_k + (default: `None`, which considers all possible top k) + adaptive_k: adjust `k` to `min(k, number of documents)` for each query + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: + Ignore predictions where the target is equal to this number. + kwargs: + Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``min_precision`` parameter is not float or between 0 and 1. + ValueError: + If ``max_k`` parameter is not `None` or an integer larger than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision + >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1]) + >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5]) + >>> target = tensor([True, False, False, True, True, False, True]) + >>> r = RetrievalRecallAtFixedPrecision(min_precision=0.8) + >>> r(preds, target, indexes=indexes) + (tensor(0.5000), tensor(1)) + + """ + + higher_is_better = True + + def __init__( + self, + min_precision: float = 0.0, + max_k: Optional[int] = None, + adaptive_k: bool = False, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + **kwargs: Any, + ) -> None: + super().__init__( + max_k=max_k, + adaptive_k=adaptive_k, + empty_target_action=empty_target_action, + ignore_index=ignore_index, + **kwargs, + ) + + if not (isinstance(min_precision, float) and 0.0 <= min_precision <= 1.0): + raise ValueError("`min_precision` has to be a positive float between 0 and 1") + + self.min_precision = min_precision + + def compute(self) -> tuple[Tensor, Tensor]: # type: ignore[override] + """Compute metric.""" + precisions, recalls, top_k = super().compute() + + return _retrieval_recall_at_fixed_precision(precisions, recalls, top_k, self.min_precision) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision + >>> # Example plotting a single value + >>> metric = RetrievalRecallAtFixedPrecision(min_precision=0.5) + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision + >>> # Example plotting multiple values + >>> metric = RetrievalRecallAtFixedPrecision(min_precision=0.5) + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))[0]) + >>> fig, ax = metric.plot(values) + + """ + val = val or self.compute()[0] + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/r_precision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/r_precision.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2466af4307618533c2743327b883cc603aedd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/r_precision.py @@ -0,0 +1,137 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Optional, Union + +from torch import Tensor + +from torchmetrics.functional.retrieval.r_precision import retrieval_r_precision +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalRPrecision.plot"] + + +class RetrievalRPrecision(RetrievalMetric): + """Compute `IR R-Precision`_. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``rp`` (:class:`~torch.Tensor`): A single-value tensor with the r-precision of the predictions ``preds`` + w.r.t. the labels ``target``. + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalRPrecision + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> p2 = RetrievalRPrecision() + >>> p2(preds, target, indexes=indexes) + tensor(0.7500) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_r_precision(preds, target) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalRPrecision + >>> # Example plotting a single value + >>> metric = RetrievalRPrecision() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalRPrecision + >>> # Example plotting multiple values + >>> metric = RetrievalRPrecision() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/recall.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/recall.py new file mode 100644 index 0000000000000000000000000000000000000000..04fe881bc9961b4405010b1584581444f1bb6056 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/recall.py @@ -0,0 +1,160 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.recall import retrieval_recall +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalRecall.plot"] + + +class RetrievalRecall(RetrievalMetric): + """Compute `IR Recall`_. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``r@k`` (:class:`~torch.Tensor`): A single-value tensor with the recall (at ``top_k``) of the predictions + ``preds`` w.r.t. the labels ``target`` + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: `None`, which considers them all) + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalRecall + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> r2 = RetrievalRecall(top_k=2) + >>> r2(preds, target, indexes=indexes) + tensor(0.7500) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + + if top_k is not None and not (isinstance(top_k, int) and top_k > 0): + raise ValueError("`top_k` has to be a positive integer or None") + self.top_k = top_k + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_recall(preds, target, top_k=self.top_k) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalRecall + >>> # Example plotting a single value + >>> metric = RetrievalRecall() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalRecall + >>> # Example plotting multiple values + >>> metric = RetrievalRecall() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/reciprocal_rank.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/reciprocal_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..01ea27ae12be55f17c5c71ff0d40e3d2d6089249 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/retrieval/reciprocal_rank.py @@ -0,0 +1,160 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.retrieval.reciprocal_rank import retrieval_reciprocal_rank +from torchmetrics.retrieval.base import RetrievalMetric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["RetrievalMRR.plot"] + + +class RetrievalMRR(RetrievalMetric): + """Compute `Mean Reciprocal Rank`_. + + Works with binary target data. Accepts float predictions from a model output. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`` + - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)`` + - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a + prediction belongs + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``mrr@k`` (:class:`~torch.Tensor`): A single-value tensor with the reciprocal rank (RR) + of the predictions ``preds`` w.r.t. the labels ``target``. + + All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning, + so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by + ``indexes`` and then will be computed as the mean of the metric over each query. + + Args: + empty_target_action: + Specify what to do with queries that do not have at least a positive ``target``. Choose from: + + - ``'neg'``: those queries count as ``0.0`` (default) + - ``'pos'``: those queries count as ``1.0`` + - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned + - ``'error'``: raise a ``ValueError`` + + ignore_index: Ignore predictions where the target is equal to this number. + top_k: Consider only the top k elements for each query (default: ``None``, which considers them all) + aggregation: + Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor + and returns a scalar value or one of the following strings: + + - ``'mean'``: average value is returned + - ``'median'``: median value is returned + - ``'max'``: max value is returned + - ``'min'``: min value is returned + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``. + ValueError: + If ``ignore_index`` is not `None` or an integer. + ValueError: + If ``top_k`` is not ``None`` or not an integer greater than 0. + + Example: + >>> from torch import tensor + >>> from torchmetrics.retrieval import RetrievalMRR + >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) + >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) + >>> target = tensor([False, False, True, False, True, False, True]) + >>> mrr = RetrievalMRR() + >>> mrr(preds, target, indexes=indexes) + tensor(0.7500) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + empty_target_action: str = "neg", + ignore_index: Optional[int] = None, + top_k: Optional[int] = None, + aggregation: Union[Literal["mean", "median", "min", "max"], Callable] = "mean", + **kwargs: Any, + ) -> None: + super().__init__( + empty_target_action=empty_target_action, + ignore_index=ignore_index, + aggregation=aggregation, + **kwargs, + ) + + if top_k is not None and not isinstance(top_k, int) and top_k <= 0: + raise ValueError(f"Argument ``top_k`` has to be a positive integer or None, but got {top_k}") + self.top_k = top_k + + def _metric(self, preds: Tensor, target: Tensor) -> Tensor: + return retrieval_reciprocal_rank(preds, target, top_k=self.top_k) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalMRR + >>> # Example plotting a single value + >>> metric = RetrievalMRR() + >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> import torch + >>> from torchmetrics.retrieval import RetrievalMRR + >>> # Example plotting multiple values + >>> metric = RetrievalMRR() + >>> values = [] + >>> for _ in range(10): + ... values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))) + >>> fig, ax = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7513963ca862a4977874ececc54ca78ba44d87a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/__init__.py @@ -0,0 +1,19 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.segmentation.dice import DiceScore +from torchmetrics.segmentation.generalized_dice import GeneralizedDiceScore +from torchmetrics.segmentation.hausdorff_distance import HausdorffDistance +from torchmetrics.segmentation.mean_iou import MeanIoU + +__all__ = ["DiceScore", "GeneralizedDiceScore", "HausdorffDistance", "MeanIoU"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/dice.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/dice.py new file mode 100644 index 0000000000000000000000000000000000000000..6d631c032d60d8955893605eed0b447edf4b5f84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/dice.py @@ -0,0 +1,200 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.segmentation.dice import ( + _dice_score_compute, + _dice_score_update, + _dice_score_validate_args, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["DiceScore.plot"] + + +class DiceScore(Metric): + r"""Compute `Dice Score`_. + + The metric can be used to evaluate the performance of image segmentation models. The Dice Score is defined as: + + .. math:: + DS = \frac{2 \sum_{i=1}^{N} t_i p_i}{\sum_{i=1}^{N} t_i + \sum_{i=1}^{N} p_i} + + where :math:`N` is the number of classes, :math:`t_i` is the target tensor, and :math:`p_i` is the prediction + tensor. In general the Dice Score can be interpreted as the overlap between the prediction and target tensors + divided by the total number of elements in the tensors. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``gds`` (:class:`~torch.Tensor`): The dice score. If ``average`` is set to ``None`` or ``"none"`` the output + will be a tensor of shape ``(C,)`` with the dice score for each class. If ``average`` is set to + ``"micro"``, ``"macro"``, or ``"weighted"`` the output will be a scalar tensor. The score is an average over + all samples. + + Args: + num_classes: The number of classes in the segmentation problem. + include_background: Whether to include the background class in the computation. + average: The method to average the dice score. Options are ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"`` + or ``None``. This determines how to average the dice score across different classes. + aggregation_level: The level at which to aggregate the dice score. Options are ``"samplewise"`` or ``"global"``. + For ``"samplewise"`` the dice score is computed for each sample and then averaged. For ``"global"`` the dice + score is computed globally over all samples. + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``num_classes`` is not a positive integer + ValueError: + If ``include_background`` is not a boolean + ValueError: + If ``average`` is not one of ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"`` or ``None`` + ValueError: + If ``input_format`` is not one of ``"one-hot"``, ``"index"`` or ``"mixed"`` + + Example: + >>> from torch import randint + >>> from torchmetrics.segmentation import DiceScore + >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> dice_score = DiceScore(num_classes=5, average="micro") + >>> dice_score(preds, target) + tensor(0.4941) + >>> dice_score = DiceScore(num_classes=5, average="none") + >>> dice_score(preds, target) + tensor([0.4860, 0.4999, 0.5014, 0.4885, 0.4915]) + + """ + + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + numerator: List[Tensor] + denominator: List[Tensor] + support: List[Tensor] + + def __init__( + self, + num_classes: int, + include_background: bool = True, + average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro", + aggregation_level: Optional[Literal["samplewise", "global"]] = "samplewise", + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if average == "micro": + rank_zero_warn( + "DiceScore metric currently defaults to `average=micro`, but will change to" + "`average=macro` in the v1.9 release." + " If you've explicitly set this parameter, you can ignore this warning.", + UserWarning, + ) + _dice_score_validate_args(num_classes, include_background, average, input_format, aggregation_level) + self.num_classes = num_classes + self.include_background = include_background + self.average = average + self.aggregation_level = aggregation_level + self.input_format = input_format + + num_classes = num_classes - 1 if not include_background else num_classes + self.add_state("numerator", [], dist_reduce_fx="cat") + self.add_state("denominator", [], dist_reduce_fx="cat") + self.add_state("support", [], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update the state with new data.""" + numerator, denominator, support = _dice_score_update( + preds, target, self.num_classes, self.include_background, self.input_format + ) + self.numerator.append(numerator) + self.denominator.append(denominator) + self.support.append(support) + + def compute(self) -> Tensor: + """Computes the Dice Score.""" + return _dice_score_compute( + dim_zero_cat(self.numerator), + dim_zero_cat(self.denominator), + self.average, + self.aggregation_level, + support=dim_zero_cat(self.support) if self.average == "weighted" else None, + ).nanmean(dim=0) + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.segmentation import DiceScore + >>> metric = DiceScore(num_classes=3) + >>> metric.update(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.segmentation import DiceScore + >>> metric = DiceScore(num_classes=3) + >>> values = [ ] + >>> for _ in range(10): + ... values.append( + ... metric(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128))) + ... ) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/generalized_dice.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/generalized_dice.py new file mode 100644 index 0000000000000000000000000000000000000000..a047ecf2b188e5ba477c08bc99ccec74676db89e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/generalized_dice.py @@ -0,0 +1,191 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.segmentation.generalized_dice import ( + _generalized_dice_compute, + _generalized_dice_update, + _generalized_dice_validate_args, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["GeneralizedDiceScore.plot"] + + +class GeneralizedDiceScore(Metric): + r"""Compute `Generalized Dice Score`_. + + The metric can be used to evaluate the performance of image segmentation models. The Generalized Dice Score is + defined as: + + .. math:: + GDS = \frac{2 \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} p_{ij}}{ + \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} + \\sum_{i=1}^{N} w_i \\sum_{j} p_{ij}} + + where :math:`N` is the number of classes, :math:`t_{ij}` is the target tensor, :math:`p_{ij}` is the prediction + tensor, and :math:`w_i` is the weight for class :math:`i`. The weight can be computed in three different ways: + + - `square`: :math:`w_i = 1 / (\\sum_{j} t_{ij})^2` + - `simple`: :math:`w_i = 1 / \\sum_{j} t_{ij}` + - `linear`: :math:`w_i = 1` + + Note that the generalized dice loss can be computed as one minus the generalized dice score. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``gds`` (:class:`~torch.Tensor`): The generalized dice score. If ``per_class`` is set to ``True``, the output + will be a tensor of shape ``(C,)`` with the generalized dice score for each class. If ``per_class`` is + set to ``False``, the output will be a scalar tensor. + + Args: + num_classes: The number of classes in the segmentation problem. + include_background: Whether to include the background class in the computation + per_class: Whether to compute the metric for each class separately. + weight_type: The type of weight to apply to each class. Can be one of ``"square"``, ``"simple"``, or + ``"linear"``. + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``num_classes`` is not a positive integer + ValueError: + If ``include_background`` is not a boolean + ValueError: + If ``per_class`` is not a boolean + ValueError: + If ``weight_type`` is not one of ``"square"``, ``"simple"``, or ``"linear"`` + ValueError: + If ``input_format`` is not one of ``"one-hot"``, ``"index"`` or ``"mixed"`` + + Example: + >>> from torch import randint + >>> from torchmetrics.segmentation import GeneralizedDiceScore + >>> gds = GeneralizedDiceScore(num_classes=3) + >>> preds = randint(0, 2, (10, 3, 128, 128)) + >>> target = randint(0, 2, (10, 3, 128, 128)) + >>> gds(preds, target) + tensor(0.4992) + >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True) + >>> gds(preds, target) + tensor([0.5001, 0.4993, 0.4982]) + >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True, include_background=False) + >>> gds(preds, target) + tensor([0.4993, 0.4982]) + + """ + + score: Tensor + samples: Tensor + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + num_classes: int, + include_background: bool = True, + per_class: bool = False, + weight_type: Literal["square", "simple", "linear"] = "square", + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + _generalized_dice_validate_args(num_classes, include_background, per_class, weight_type, input_format) + self.num_classes = num_classes + self.include_background = include_background + self.per_class = per_class + self.weight_type = weight_type + self.input_format = input_format + + num_classes = num_classes - 1 if not include_background else num_classes + self.add_state("score", default=torch.zeros(num_classes if per_class else 1), dist_reduce_fx="sum") + self.add_state("samples", default=torch.zeros(1), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update the state with new data.""" + numerator, denominator = _generalized_dice_update( + preds, target, self.num_classes, self.include_background, self.weight_type, self.input_format + ) + self.score += _generalized_dice_compute(numerator, denominator, self.per_class).sum(dim=0) + self.samples += preds.shape[0] + + def compute(self) -> Tensor: + """Compute the final generalized dice score.""" + return self.score / self.samples + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.segmentation import GeneralizedDiceScore + >>> metric = GeneralizedDiceScore(num_classes=3) + >>> metric.update(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.segmentation import GeneralizedDiceScore + >>> metric = GeneralizedDiceScore(num_classes=3) + >>> values = [ ] + >>> for _ in range(10): + ... values.append( + ... metric(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128))) + ... ) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/hausdorff_distance.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/hausdorff_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..602d20db3ed71c4745c7e5eeb493ce0e38ce7150 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/hausdorff_distance.py @@ -0,0 +1,159 @@ +# Copyright The Lightning team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Literal, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.segmentation.hausdorff_distance import ( + _hausdorff_distance_validate_args, + hausdorff_distance, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["HausdorffDistance.plot"] + + +class HausdorffDistance(Metric): + r"""Compute the `Hausdorff Distance`_ between two subsets of a metric space for semantic segmentation. + + .. math:: + d_{\Pi}(X,Y) = \max{/sup_{x\in X} {d(x,Y)}, /sup_{y\in Y} {d(X,y)}} + + where :math:`\X, \Y` are two subsets of a metric space with distance metric :math:`d`. The Hausdorff distance is + the maximum distance from a point in one set to the closest point in the other set. The Hausdorff distance is a + measure of the degree of mismatch between two sets. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``hausdorff_distance`` (:class:`~torch.Tensor`): A scalar float tensor with the Hausdorff distance averaged over + classes and samples + + Args: + num_classes: number of classes + include_background: whether to include background class in calculation + distance_metric: distance metric to calculate surface distance. Choose one of `"euclidean"`, + `"chessboard"` or `"taxicab"` + spacing: spacing between pixels along each spatial dimension. If not provided the spacing is assumed to be 1 + directed: whether to calculate directed or undirected Hausdorff distance + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torch import randint + >>> from torchmetrics.segmentation import HausdorffDistance + >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> hausdorff_distance = HausdorffDistance(distance_metric="euclidean", num_classes=5) + >>> hausdorff_distance(preds, target) + tensor(1.9567) + + """ + + is_differentiable: bool = True + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + score: Tensor + total: Tensor + + def __init__( + self, + num_classes: int, + include_background: bool = False, + distance_metric: Literal["euclidean", "chessboard", "taxicab"] = "euclidean", + spacing: Optional[Union[Tensor, list[float]]] = None, + directed: bool = False, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + _hausdorff_distance_validate_args( + num_classes, include_background, distance_metric, spacing, directed, input_format + ) + self.num_classes = num_classes + self.include_background = include_background + self.distance_metric = distance_metric + self.spacing = spacing + self.directed = directed + self.input_format = input_format + self.add_state("score", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + score = hausdorff_distance( + preds, + target, + self.num_classes, + include_background=self.include_background, + distance_metric=self.distance_metric, + spacing=self.spacing, + directed=self.directed, + input_format=self.input_format, + ) + self.score += score.sum() + self.total += score.numel() + + def compute(self) -> Tensor: + """Compute final Hausdorff distance over states.""" + return self.score / self.total + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> from torch import randint + >>> from torchmetrics.segmentation import HausdorffDistance + >>> preds = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 prediction + >>> target = randint(0, 2, (4, 5, 16, 16)) # 4 samples, 5 classes, 16x16 target + >>> metric = HausdorffDistance(num_classes=5) + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/mean_iou.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/mean_iou.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb06964ed71881310420846603f82f2e799fd29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/segmentation/mean_iou.py @@ -0,0 +1,226 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.functional.segmentation.mean_iou import _mean_iou_compute, _mean_iou_update, _mean_iou_validate_args +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MeanIoU.plot"] + + +class MeanIoU(Metric): + """Computes Mean Intersection over Union (mIoU) for semantic segmentation. + + The metric is defined by the overlap between the predicted segmentation and the ground truth, divided by the + total area covered by the union of the two. The metric can be computed for each class separately or for all + classes at once. The metric is optimal at a value of 1 and worst at a value of 0, -1 is returned if class + is completely absent both from prediction and the ground truth labels. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being + the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)`` + can be provided, where the integer values correspond to the class index. The input type can be controlled + with the ``input_format`` argument. + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``miou`` (:class:`~torch.Tensor`): The mean Intersection over Union (mIoU) score. If ``per_class`` is set to + ``True``, the output will be a tensor of shape ``(C,)`` with the IoU score for each class. If ``per_class`` is + set to ``False``, the output will be a scalar tensor. + + Args: + num_classes: The number of classes in the segmentation problem. Required when input_format="index", + optional when input_format="one-hot" or "mixed". + include_background: Whether to include the background class in the computation + per_class: Whether to compute the IoU for each class separately. If set to ``False``, the metric will + compute the mean IoU over all classes. + input_format: What kind of input the function receives. + Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors + or ``"mixed"`` for one one-hot encoded and one index tensor + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``num_classes`` is not ``None`` or a positive integer + ValueError: + If ``num_classes`` is not provided when ``input_format`` is ``"index"`` + ValueError: + If ``include_background`` is not a boolean + ValueError: + If ``per_class`` is not a boolean + ValueError: + If ``input_format`` is not one of ``"one-hot"``, ``"index"`` or ``"mixed"`` + + Example: + >>> import torch + >>> from torch import randint + >>> from torchmetrics.segmentation import MeanIoU + >>> miou = MeanIoU() + >>> preds = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(42)) + >>> target = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(43)) + >>> miou(preds, target) + tensor(0.3336) + >>> miou = MeanIoU(num_classes=3, per_class=True) + >>> miou(preds, target) + tensor([0.3361, 0.3340, 0.3308]) + >>> miou = MeanIoU(per_class=True, include_background=False) + >>> miou(preds, target) + tensor([0.3340, 0.3308]) + >>> miou = MeanIoU(num_classes=3, per_class=True, include_background=True, input_format="index") + >>> miou(preds, target) + tensor([ 0.3334, 0.3336, -1.0000]) + + """ + + score: Tensor + num_batches: Tensor + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + num_classes: Optional[int] = None, + include_background: bool = True, + per_class: bool = False, + input_format: Literal["one-hot", "index", "mixed"] = "one-hot", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + _mean_iou_validate_args(num_classes, include_background, per_class, input_format) + self.num_classes = num_classes + self.include_background = include_background + self.per_class = per_class + self.input_format = input_format + self._is_initialized = False + if num_classes is not None: + num_classes = num_classes - 1 if not include_background else num_classes + self.add_state("score", default=torch.zeros(num_classes if per_class else 1), dist_reduce_fx="sum") + self.add_state("num_batches", default=torch.zeros(num_classes), dist_reduce_fx="sum") + self._is_initialized = True + else: + self.add_state("score", default=torch.zeros(1), dist_reduce_fx="sum") + self.add_state("num_batches", default=torch.zeros(1), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update the state with the new data.""" + if not self._is_initialized: + try: + if self.input_format == "one-hot": + self.num_classes = preds.shape[1] + elif self.input_format == "mixed": + if preds.dim() == (target.dim() + 1): + self.num_classes = preds.shape[1] + elif (preds.dim() + 1) == target.dim(): + self.num_classes = target.shape[1] + else: + raise ValueError( + "Predictions and targets are expected to have the same shape,", + f"got {preds.shape} and {target.shape}.", + ) + else: + raise ValueError("Argument `num_classes` must be provided when `input_format` is 'index'.") + except IndexError as err: + raise IndexError(f"Cannot determine `num_classes` from `preds` tensor: {preds}.") from err + + if self.num_classes == 0: + raise ValueError( + f"Expected argument `num_classes` to be a positive integer, but got {self.num_classes}." + ) + + num_out_classes = self.num_classes - 1 if not self.include_background else self.num_classes + self.add_state( + "score", + default=torch.zeros(num_out_classes, device=self.device, dtype=self.dtype), + dist_reduce_fx="sum", + ) + self.add_state( + "num_batches", + default=torch.zeros(num_out_classes, device=self.device, dtype=torch.int32), + dist_reduce_fx="sum", + ) + self._is_initialized = True + + intersection, union = _mean_iou_update( + preds, target, self.num_classes, self.include_background, self.input_format + ) + score = _mean_iou_compute(intersection, union, zero_division=0.0) + # only update for classes that are present (i.e. union > 0) + valid_classes = union > 0 + if self.per_class: + self.score += (score * valid_classes).sum(dim=0) + self.num_batches += valid_classes.sum(dim=0) + else: + self.score += (score * valid_classes).sum() + self.num_batches += valid_classes.sum() + + def compute(self) -> Tensor: + """Compute the final Mean Intersection over Union (mIoU).""" + output_score = self.score / self.num_batches + return output_score.nan_to_num(-1.0) if self.per_class else output_score.nanmean() + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality + >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb') + >>> metric.update(torch.rand(8000), torch.rand(8000)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality + >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb') + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.rand(8000), torch.rand(8000))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/shape/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/shape/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..263a1e395a201da4c5fb492ccf852ef466725b32 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/shape/__init__.py @@ -0,0 +1,16 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.shape.procrustes import ProcrustesDisparity + +__all__ = ["ProcrustesDisparity"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/shape/procrustes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/shape/procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..1d8396c7afb9f9bea51d5e19721d1f70f6435f41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/shape/procrustes.py @@ -0,0 +1,138 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics import Metric +from torchmetrics.functional.shape.procrustes import procrustes_disparity +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ProcrustesDisparity.plot"] + + +class ProcrustesDisparity(Metric): + r"""Compute the `Procrustes Disparity`_. + + The Procrustes Disparity is defined as the sum of the squared differences between two datasets after + applying a Procrustes transformation. The Procrustes Disparity is useful to compare two datasets + that are similar but not aligned. + + The metric works similar to ``scipy.spatial.procrustes`` but for batches of data points. The disparity is + aggregated over the batch, thus to get the individual disparities please use the functional version of this + metric: ``torchmetrics.functional.shape.procrustes.procrustes_disparity``. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``point_cloud1`` (torch.Tensor): A tensor of shape ``(N, M, D)`` with ``N`` being the batch size, + ``M`` the number of data points and ``D`` the dimensionality of the data points. + - ``point_cloud2`` (torch.Tensor): A tensor of shape ``(N, M, D)`` with ``N`` being the batch size, + ``M`` the number of data points and ``D`` the dimensionality of the data points. + + + As output to ``forward`` and ``compute`` the metric returns the following output: + + - ``gds`` (:class:`~torch.Tensor`): A scalar tensor with the Procrustes Disparity. + + Args: + reduction: Determines whether to return the mean disparity or the sum of the disparities. + Can be one of ``"mean"`` or ``"sum"``. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: If ``average`` is not one of ``"mean"`` or ``"sum"``. + + Example: + >>> from torch import randn + >>> from torchmetrics.shape import ProcrustesDisparity + >>> metric = ProcrustesDisparity() + >>> point_cloud1 = randn(10, 50, 2) + >>> point_cloud2 = randn(10, 50, 2) + >>> metric(point_cloud1, point_cloud2) + tensor(0.9770) + + """ + + disparity: Tensor + total: Tensor + full_state_update: bool = False + is_differentiable: bool = False + higher_is_better: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__(self, reduction: Literal["mean", "sum"] = "mean", **kwargs: Any) -> None: + super().__init__(**kwargs) + if reduction not in ("mean", "sum"): + raise ValueError(f"Argument `reduction` must be one of ['mean', 'sum'], got {reduction}") + self.reduction = reduction + self.add_state("disparity", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") + + def update(self, point_cloud1: torch.Tensor, point_cloud2: torch.Tensor) -> None: + """Update the Procrustes Disparity with the given datasets.""" + disparity: Tensor = procrustes_disparity(point_cloud1, point_cloud2) # type: ignore[assignment] + self.disparity += disparity.sum() + self.total += disparity.numel() + + def compute(self) -> torch.Tensor: + """Computes the Procrustes Disparity.""" + if self.reduction == "mean": + return self.disparity / self.total + return self.disparity + + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.shape import ProcrustesDisparity + >>> metric = ProcrustesDisparity() + >>> metric.update(torch.randn(10, 50, 2), torch.randn(10, 50, 2)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.shape import ProcrustesDisparity + >>> metric = ProcrustesDisparity() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.randn(10, 50, 2), torch.randn(10, 50, 2))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6af056246cd4a28e6389c3fda286523a4cd53757 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/__init__.py @@ -0,0 +1,51 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.text.bleu import BLEUScore +from torchmetrics.text.cer import CharErrorRate +from torchmetrics.text.chrf import CHRFScore +from torchmetrics.text.edit import EditDistance +from torchmetrics.text.eed import ExtendedEditDistance +from torchmetrics.text.mer import MatchErrorRate +from torchmetrics.text.perplexity import Perplexity +from torchmetrics.text.rouge import ROUGEScore +from torchmetrics.text.sacre_bleu import SacreBLEUScore +from torchmetrics.text.squad import SQuAD +from torchmetrics.text.ter import TranslationEditRate +from torchmetrics.text.wer import WordErrorRate +from torchmetrics.text.wil import WordInfoLost +from torchmetrics.text.wip import WordInfoPreserved +from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_4 + +__all__ = [ + "BLEUScore", + "CHRFScore", + "CharErrorRate", + "EditDistance", + "ExtendedEditDistance", + "MatchErrorRate", + "Perplexity", + "ROUGEScore", + "SQuAD", + "SacreBLEUScore", + "TranslationEditRate", + "WordErrorRate", + "WordInfoLost", + "WordInfoPreserved", +] + +if _TRANSFORMERS_GREATER_EQUAL_4_4: + from torchmetrics.text.bert import BERTScore + from torchmetrics.text.infolm import InfoLM + + __all__ += ["BERTScore", "InfoLM"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/_deprecated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..50c5091de287ec0d083d45f82b36d570ab2a3158 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/_deprecated.py @@ -0,0 +1,285 @@ +from collections.abc import Sequence +from typing import Any, Literal, Optional + +from torchmetrics.text.bleu import BLEUScore +from torchmetrics.text.cer import CharErrorRate +from torchmetrics.text.chrf import CHRFScore +from torchmetrics.text.eed import ExtendedEditDistance +from torchmetrics.text.mer import MatchErrorRate +from torchmetrics.text.perplexity import Perplexity +from torchmetrics.text.sacre_bleu import SacreBLEUScore +from torchmetrics.text.squad import SQuAD +from torchmetrics.text.ter import TranslationEditRate +from torchmetrics.text.wer import WordErrorRate +from torchmetrics.text.wil import WordInfoLost +from torchmetrics.text.wip import WordInfoPreserved +from torchmetrics.utilities.prints import _deprecated_root_import_class + + +class _BLEUScore(BLEUScore): + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> bleu = _BLEUScore() + >>> bleu(preds, target) + tensor(0.7598) + + """ + + def __init__( + self, + n_gram: int = 4, + smooth: bool = False, + weights: Optional[Sequence[float]] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("BLEUScore", "text") + super().__init__(n_gram=n_gram, smooth=smooth, weights=weights, **kwargs) + + +class _CharErrorRate(CharErrorRate): + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> cer = _CharErrorRate() + >>> cer(preds, target) + tensor(0.3415) + + """ + + def __init__( + self, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("CharErrorRate", "text") + super().__init__(**kwargs) + + +class _CHRFScore(CHRFScore): + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> chrf = _CHRFScore() + >>> chrf(preds, target) + tensor(0.8640) + + """ + + def __init__( + self, + n_char_order: int = 6, + n_word_order: int = 2, + beta: float = 2.0, + lowercase: bool = False, + whitespace: bool = False, + return_sentence_level_score: bool = False, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("CHRFScore", "text") + super().__init__( + n_char_order=n_char_order, + n_word_order=n_word_order, + beta=beta, + lowercase=lowercase, + whitespace=whitespace, + return_sentence_level_score=return_sentence_level_score, + **kwargs, + ) + + +class _ExtendedEditDistance(ExtendedEditDistance): + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "here is an other sample"] + >>> target = ["this is the reference", "here is another one"] + >>> eed = _ExtendedEditDistance() + >>> eed(preds=preds, target=target) + tensor(0.3078) + + """ + + def __init__( + self, + language: Literal["en", "ja"] = "en", + return_sentence_level_score: bool = False, + alpha: float = 2.0, + rho: float = 0.3, + deletion: float = 0.2, + insertion: float = 1.0, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("ExtendedEditDistance", "text") + super().__init__( + language=language, + return_sentence_level_score=return_sentence_level_score, + alpha=alpha, + rho=rho, + deletion=deletion, + insertion=insertion, + **kwargs, + ) + + +class _MatchErrorRate(MatchErrorRate): + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> mer = _MatchErrorRate() + >>> mer(preds, target) + tensor(0.4444) + + """ + + def __init__( + self, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("MatchErrorRate", "text") + super().__init__(**kwargs) + + +class _Perplexity(Perplexity): + """Wrapper for deprecated import. + + >>> from torch import rand, randint + >>> preds = rand(2, 8, 5) + >>> target = randint(5, (2, 8)) + >>> target[0, 6:] = -100 + >>> perp = _Perplexity(ignore_index=-100) + >>> perp(preds, target) + tensor(5.8540) + + """ + + def __init__( + self, + ignore_index: Optional[int] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("Perplexity", "text") + super().__init__(ignore_index=ignore_index, **kwargs) + + +class _SacreBLEUScore(SacreBLEUScore): + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> sacre_bleu = _SacreBLEUScore() + >>> sacre_bleu(preds, target) + tensor(0.7598) + + """ + + def __init__( + self, + n_gram: int = 4, + smooth: bool = False, + tokenize: Literal["none", "13a", "zh", "intl", "char"] = "13a", + lowercase: bool = False, + weights: Optional[Sequence[float]] = None, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("SacreBLEUScore", "text") + super().__init__( + n_gram=n_gram, smooth=smooth, tokenize=tokenize, lowercase=lowercase, weights=weights, **kwargs + ) + + +class _SQuAD(SQuAD): + """Wrapper for deprecated import. + + >>> preds = [{"prediction_text": "1976", "id": "56e10a3be3433e1400422b22"}] + >>> target = [{"answers": {"answer_start": [97], "text": ["1976"]}, "id": "56e10a3be3433e1400422b22"}] + >>> squad = _SQuAD() + >>> squad(preds, target) + {'exact_match': tensor(100.), 'f1': tensor(100.)} + + """ + + def __init__(self, **kwargs: Any) -> None: + _deprecated_root_import_class("SQuAD", "text") + super().__init__(**kwargs) + + +class _TranslationEditRate(TranslationEditRate): + """Wrapper for deprecated import. + + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> ter = _TranslationEditRate() + >>> ter(preds, target) + tensor(0.1538) + + """ + + def __init__( + self, + normalize: bool = False, + no_punctuation: bool = False, + lowercase: bool = True, + asian_support: bool = False, + return_sentence_level_score: bool = False, + **kwargs: Any, + ) -> None: + _deprecated_root_import_class("TranslationEditRate", "text") + super().__init__( + normalize=normalize, + no_punctuation=no_punctuation, + lowercase=lowercase, + asian_support=asian_support, + return_sentence_level_score=return_sentence_level_score, + **kwargs, + ) + + +class _WordErrorRate(WordErrorRate): + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> wer = _WordErrorRate() + >>> wer(preds, target) + tensor(0.5000) + + """ + + def __init__(self, **kwargs: Any) -> None: + _deprecated_root_import_class("WordErrorRate", "text") + super().__init__(**kwargs) + + +class _WordInfoLost(WordInfoLost): + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> wil = _WordInfoLost() + >>> wil(preds, target) + tensor(0.6528) + + """ + + def __init__(self, **kwargs: Any) -> None: + _deprecated_root_import_class("WordInfoLost", "text") + super().__init__(**kwargs) + + +class _WordInfoPreserved(WordInfoPreserved): + """Wrapper for deprecated import. + + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> wip = WordInfoPreserved() + >>> wip(preds, target) + tensor(0.3472) + + """ + + def __init__(self, **kwargs: Any) -> None: + _deprecated_root_import_class("WordInfoPreserved", "text") + super().__init__(**kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/bert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/bert.py new file mode 100644 index 0000000000000000000000000000000000000000..fda073f72e6eed6da397fc0b7a5e54b5b729bb35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/bert.py @@ -0,0 +1,366 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, List, Optional, Tuple, Union, cast + +import torch +from torch import Tensor +from torch.nn import Module + +from torchmetrics.functional.text.bert import ( + _postprocess_multiple_references, + _preprocess_multiple_references, + bert_score, +) +from torchmetrics.functional.text.helper_embedding_metric import _preprocess_text +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn +from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TRANSFORMERS_GREATER_EQUAL_4_4 +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["BERTScore.plot"] + +# Default model recommended in the original implementation. +_DEFAULT_MODEL: str = "roberta-large" + +if _SKIP_SLOW_DOCTEST and _TRANSFORMERS_GREATER_EQUAL_4_4: + from transformers import AutoModel, AutoTokenizer + + def _download_model_for_bert_score() -> None: + """Download intensive operations.""" + AutoTokenizer.from_pretrained(_DEFAULT_MODEL, resume_download=True) + AutoModel.from_pretrained(_DEFAULT_MODEL, resume_download=True) + + if not _try_proceed_with_timeout(_download_model_for_bert_score): + __doctest_skip__ = ["BERTScore", "BERTScore.plot"] +else: + __doctest_skip__ = ["BERTScore", "BERTScore.plot"] + + +def _get_input_dict(input_ids: List[Tensor], attention_mask: List[Tensor]) -> dict[str, Tensor]: + """Create an input dictionary of ``input_ids`` and ``attention_mask`` for BERTScore calculation.""" + return {"input_ids": torch.cat(input_ids), "attention_mask": torch.cat(attention_mask)} + + +class BERTScore(Metric): + """`Bert_score Evaluating Text Generation`_ for measuring text similarity. + + BERT leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference + sentences by cosine similarity. It has been shown to correlate with human judgment on sentence-level and + system-level evaluation. Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for + evaluating different language generation tasks. This implementation follows the original implementation from + `BERT_score`_. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds``: Predicted sentence(s). Can be one of: + + * A single predicted sentence as a string (``str``) + * A sequence of predicted sentences (``Sequence[str]``) + + - ``target``: Target/reference sentence(s). Can be one of: + + * A single reference sentence as a string (``str``) + * A sequence of reference sentences (``Sequence[str]``) + * A sequence of sequences of reference sentences for multi-reference evaluation (``Sequence[Sequence[str]]``) + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``score`` (:class:`~Dict`): A dictionary containing the keys ``precision``, ``recall`` and ``f1`` with + corresponding values + + Args: + preds (Union[str, Sequence[str]]): A single predicted sentence or a sequence of predicted sentences. + target (Union[str, Sequence[str], Sequence[Sequence[str]]]): A single target sentence, a sequence of target + sentences, or a sequence of sequences of target sentences for multiple references per prediction. + model_type: A name or a model path used to load ``transformers`` pretrained model. + num_layers: A layer of representation to use. + all_layers: + An indication of whether the representation from all model's layers should be used. + If ``all_layers=True``, the argument ``num_layers`` is ignored. + model: A user's own model. Must be of `torch.nn.Module` instance. + user_tokenizer: + A user's own tokenizer used with the own model. This must be an instance with the ``__call__`` method. + This method must take an iterable of sentences (`List[str]`) and must return a python dictionary + containing `"input_ids"` and `"attention_mask"` represented by :class:`~torch.Tensor`. + It is up to the user's model of whether `"input_ids"` is a :class:`~torch.Tensor` of input ids or embedding + vectors. This tokenizer must prepend an equivalent of ``[CLS]`` token and append an equivalent of ``[SEP]`` + token as ``transformers`` tokenizer does. + user_forward_fn: + A user's own forward function used in a combination with ``user_model``. This function must take + ``user_model`` and a python dictionary of containing ``"input_ids"`` and ``"attention_mask"`` represented + by :class:`~torch.Tensor` as an input and return the model's output represented by the single + :class:`~torch.Tensor`. + verbose: An indication of whether a progress bar to be displayed during the embeddings' calculation. + idf: An indication whether normalization using inverse document frequencies should be used. + device: A device to be used for calculation. + max_length: A maximum length of input sequences. Sequences longer than ``max_length`` are to be trimmed. + batch_size: A batch size used for model processing. + num_threads: A number of threads to use for a dataloader. + return_hash: An indication of whether the correspodning ``hash_code`` should be returned. + lang: A language of input sentences. + rescale_with_baseline: + An indication of whether bertscore should be rescaled with a pre-computed baseline. + When a pretrained model from ``transformers`` model is used, the corresponding baseline is downloaded + from the original ``bert-score`` package from `BERT_score`_ if available. + In other cases, please specify a path to the baseline csv/tsv file, which must follow the formatting + of the files from `BERT_score`_. + baseline_path: A path to the user's own local csv/tsv file with the baseline scale. + baseline_url: A url path to the user's own csv/tsv file with the baseline scale. + truncation: An indication of whether the input sequences should be truncated to the ``max_length``. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from pprint import pprint + >>> from torchmetrics.text.bert import BERTScore + >>> preds = ["hello there", "general kenobi"] + >>> target = ["hello there", "master kenobi"] + >>> bertscore = BERTScore() + >>> pprint(bertscore(preds, target)) + {'f1': tensor([1.0000, 0.9961]), 'precision': tensor([1.0000, 0.9961]), 'recall': tensor([1.0000, 0.9961])} + + Example: + >>> from pprint import pprint + >>> from torchmetrics.text.bert import BERTScore + >>> preds = ["hello there", "general kenobi"] + >>> target = [["hello there", "master kenobi"], ["hello there", "master kenobi"]] + >>> bertscore = BERTScore() + >>> pprint(bertscore(preds, target)) + {'f1': tensor([1.0000, 0.9961]), 'precision': tensor([1.0000, 0.9961]), 'recall': tensor([1.0000, 0.9961])} + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds_input_ids: List[Tensor] + preds_attention_mask: List[Tensor] + target_input_ids: List[Tensor] + target_attention_mask: List[Tensor] + + def __init__( + self, + model_name_or_path: Optional[str] = None, + num_layers: Optional[int] = None, + all_layers: bool = False, + model: Optional[Module] = None, + user_tokenizer: Optional[Any] = None, + user_forward_fn: Optional[Callable[[Module, dict[str, Tensor]], Tensor]] = None, + verbose: bool = False, + idf: bool = False, + device: Optional[Union[str, torch.device]] = None, + max_length: int = 512, + batch_size: int = 64, + num_threads: int = 0, + return_hash: bool = False, + lang: str = "en", + rescale_with_baseline: bool = False, + baseline_path: Optional[str] = None, + baseline_url: Optional[str] = None, + truncation: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.model_name_or_path = model_name_or_path or _DEFAULT_MODEL + self.num_layers = num_layers + self.all_layers = all_layers + self.model = model + self.user_forward_fn = user_forward_fn + self.verbose = verbose + self.idf = idf + self.embedding_device = device + self.max_length = max_length + self.batch_size = batch_size + self.num_threads = num_threads + self.return_hash = return_hash + self.lang = lang + self.rescale_with_baseline = rescale_with_baseline + self.baseline_path = baseline_path + self.baseline_url = baseline_url + self.truncation = truncation + self.ref_group_boundaries: Optional[List[Tuple[int, int]]] = None + + if user_tokenizer: + self.tokenizer = user_tokenizer + self.user_tokenizer = True + else: + if not _TRANSFORMERS_GREATER_EQUAL_4_4: + raise ModuleNotFoundError( + "`BERTScore` metric with default tokenizers requires `transformers` package be installed." + " Either install with `pip install transformers>=4.4` or `pip install torchmetrics[text]`." + ) + from transformers import AutoTokenizer + + if model_name_or_path is None: + rank_zero_warn( + "The argument `model_name_or_path` was not specified while it is required when the default" + " `transformers` model is used." + f" It will use the default recommended model - {_DEFAULT_MODEL!r}." + ) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path) + self.user_tokenizer = False + + self.add_state("preds_input_ids", [], dist_reduce_fx="cat") + self.add_state("preds_attention_mask", [], dist_reduce_fx="cat") + self.add_state("target_input_ids", [], dist_reduce_fx="cat") + self.add_state("target_attention_mask", [], dist_reduce_fx="cat") + + def update( + self, preds: Union[str, Sequence[str]], target: Union[str, Sequence[str], Sequence[Sequence[str]]] + ) -> None: + """Store predictions/references for computing BERT scores. + + It is necessary to store sentences in a tokenized form to ensure the DDP mode working. + + """ + if isinstance(preds, str): + preds = [preds] + if isinstance(target, str): + target = [target] + if not isinstance(preds, list): + preds = list(preds) + if not isinstance(target, list): + target = list(target) + + if len(preds) != len(target): + raise ValueError( + "Expected number of predicted and reference sentences to be the same, but got" + f"{len(preds)} and {len(target)}" + ) + + if isinstance(preds, list) and len(preds) > 0 and isinstance(target, list) and len(target) > 0: + preds, target, self.ref_group_boundaries = _preprocess_multiple_references(preds, target) + + preds_dict, _ = _preprocess_text( + preds, + self.tokenizer, + self.max_length, + truncation=self.truncation, + sort_according_length=False, + own_tokenizer=self.user_tokenizer, + ) + target_dict, _ = _preprocess_text( + cast(List[str], target), + self.tokenizer, + self.max_length, + truncation=self.truncation, + sort_according_length=False, + own_tokenizer=self.user_tokenizer, + ) + + self.preds_input_ids.append(preds_dict["input_ids"]) + self.preds_attention_mask.append(preds_dict["attention_mask"]) + self.target_input_ids.append(target_dict["input_ids"]) + self.target_attention_mask.append(target_dict["attention_mask"]) + + def compute(self) -> dict[str, Union[Tensor, List[float], str]]: + """Calculate BERT scores.""" + preds = { + "input_ids": dim_zero_cat(self.preds_input_ids), + "attention_mask": dim_zero_cat(self.preds_attention_mask), + } + target = { + "input_ids": dim_zero_cat(self.target_input_ids), + "attention_mask": dim_zero_cat(self.target_attention_mask), + } + + output_dict = bert_score( + preds=preds, + target=target, + model_name_or_path=self.model_name_or_path, + num_layers=self.num_layers, + all_layers=self.all_layers, + model=self.model, + user_tokenizer=self.tokenizer if self.user_tokenizer else None, + user_forward_fn=self.user_forward_fn, + verbose=self.verbose, + idf=self.idf, + device=self.embedding_device, + max_length=self.max_length, + batch_size=self.batch_size, + num_threads=self.num_threads, + return_hash=self.return_hash, + lang=self.lang, + rescale_with_baseline=self.rescale_with_baseline, + baseline_path=self.baseline_path, + baseline_url=self.baseline_url, + ) + + if ( + self.ref_group_boundaries is not None + and isinstance(output_dict["precision"], Tensor) + and isinstance(output_dict["recall"], Tensor) + and isinstance(output_dict["f1"], Tensor) + ): + output_dict["precision"], output_dict["recall"], output_dict["f1"] = _postprocess_multiple_references( + output_dict["precision"], output_dict["recall"], output_dict["f1"], self.ref_group_boundaries + ) + + return output_dict + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text.bert import BERTScore + >>> preds = ["hello there", "general kenobi"] + >>> target = ["hello there", "master kenobi"] + >>> metric = BERTScore() + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torch import tensor + >>> from torchmetrics.text.bert import BERTScore + >>> preds = ["hello there", "general kenobi"] + >>> target = ["hello there", "master kenobi"] + >>> metric = BERTScore() + >>> values = [] + >>> for _ in range(10): + ... val = metric(preds, target) + ... val = {k: tensor(v).mean() for k,v in val.items()} # convert into single value per key + ... values.append(val) + >>> fig_, ax_ = metric.plot(values) + + """ + if val is None: # default average score across sentences + val = self.compute() # type: ignore + val = {k: torch.tensor(v).mean() for k, v in val.items()} # type: ignore + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/bleu.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/bleu.py new file mode 100644 index 0000000000000000000000000000000000000000..a40525bbe0c1724b9ac2f09e77685447a85288f0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/bleu.py @@ -0,0 +1,158 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# referenced from +# Library Name: torchtext +# Authors: torchtext authors and @sluks +# Date: 2020-07-18 +# Link: https://pytorch.org/text/_modules/torchtext/data/metrics.html#bleu_score +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics import Metric +from torchmetrics.functional.text.bleu import _bleu_score_compute, _bleu_score_update, _tokenize_fn +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["BLEUScore.plot"] + + +class BLEUScore(Metric): + """Calculate `BLEU score`_ of machine translated text with one or more references. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of machine translated corpus + - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus + + As output of ``forward`` and ``update`` the metric returns the following output: + + - ``bleu`` (:class:`~torch.Tensor`): A tensor with the BLEU Score + + Args: + n_gram: Gram value ranged from 1 to 4 + smooth: Whether or not to apply smoothing, see `Machine Translation Evolution`_ + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + weights: + Weights used for unigrams, bigrams, etc. to calculate BLEU score. + If not provided, uniform weights are used. + + Raises: + ValueError: If a length of a list of weights is not ``None`` and not equal to ``n_gram``. + + Example: + >>> from torchmetrics.text import BLEUScore + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> bleu = BLEUScore() + >>> bleu(preds, target) + tensor(0.7598) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + preds_len: Tensor + target_len: Tensor + numerator: Tensor + denominator: Tensor + + def __init__( + self, + n_gram: int = 4, + smooth: bool = False, + weights: Optional[Sequence[float]] = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.n_gram = n_gram + self.smooth = smooth + if weights is not None and len(weights) != n_gram: + raise ValueError(f"List of weights has different weights than `n_gram`: {len(weights)} != {n_gram}") + self.weights = weights if weights is not None else [1.0 / n_gram] * n_gram + + self.add_state("preds_len", tensor(0.0), dist_reduce_fx="sum") + self.add_state("target_len", tensor(0.0), dist_reduce_fx="sum") + self.add_state("numerator", torch.zeros(self.n_gram), dist_reduce_fx="sum") + self.add_state("denominator", torch.zeros(self.n_gram), dist_reduce_fx="sum") + + def update(self, preds: Sequence[str], target: Sequence[Sequence[str]]) -> None: + """Update state with predictions and targets.""" + self.preds_len, self.target_len = _bleu_score_update( + preds, + target, + self.numerator, + self.denominator, + self.preds_len, + self.target_len, + self.n_gram, + _tokenize_fn, + ) + + def compute(self) -> Tensor: + """Calculate BLEU score.""" + return _bleu_score_compute( + self.preds_len, self.target_len, self.numerator, self.denominator, self.n_gram, self.weights, self.smooth + ) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import BLEUScore + >>> metric = BLEUScore() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import BLEUScore + >>> metric = BLEUScore() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/cer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/cer.py new file mode 100644 index 0000000000000000000000000000000000000000..e0337801916e2c7fb43540b5f184bf8502318b46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/cer.py @@ -0,0 +1,140 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.cer import _cer_compute, _cer_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["CharErrorRate.plot"] + + +class CharErrorRate(Metric): + r"""Character Error Rate (`CER`_) is a metric of the performance of an automatic speech recognition (ASR) system. + + This value indicates the percentage of characters that were incorrectly predicted. + The lower the value, the better the performance of the ASR system with a CharErrorRate of 0 being + a perfect score. + Character error rate can then be computed as: + + .. math:: + CharErrorRate = \frac{S + D + I}{N} = \frac{S + D + I}{S + D + C} + + where: + - :math:`S` is the number of substitutions, + - :math:`D` is the number of deletions, + - :math:`I` is the number of insertions, + - :math:`C` is the number of correct characters, + - :math:`N` is the number of characters in the reference (N=S+D+C). + + Compute CharErrorRate score of transcribed segments against references. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~str`): Transcription(s) to score as a string or list of strings + - ``target`` (:class:`~str`): Reference(s) for each speech input as a string or list of strings + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``cer`` (:class:`~torch.Tensor`): A tensor with the Character Error Rate score + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Examples: + >>> from torchmetrics.text import CharErrorRate + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> cer = CharErrorRate() + >>> cer(preds, target) + tensor(0.3415) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + errors: Tensor + total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.add_state("errors", tensor(0, dtype=torch.float), dist_reduce_fx="sum") + self.add_state("total", tensor(0, dtype=torch.float), dist_reduce_fx="sum") + + def update(self, preds: Union[str, list[str]], target: Union[str, list[str]]) -> None: + """Update state with predictions and targets.""" + errors, total = _cer_update(preds, target) + self.errors += errors + self.total += total + + def compute(self) -> Tensor: + """Calculate the character error rate.""" + return _cer_compute(self.errors, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import CharErrorRate + >>> metric = CharErrorRate() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import CharErrorRate + >>> metric = CharErrorRate() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/chrf.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/chrf.py new file mode 100644 index 0000000000000000000000000000000000000000..64eb7c6b1d4bea0d9b3318b578a3d9e0c478aef7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/chrf.py @@ -0,0 +1,250 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# referenced from +# Library Name: torchtext +# Authors: torchtext authors and @sluks +# Date: 2021-11-25 +# Link: + +import itertools +from collections.abc import Iterator, Sequence +from typing import Any, List, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics import Metric +from torchmetrics.functional.text.chrf import _chrf_score_compute, _chrf_score_update, _prepare_n_grams_dicts +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["CHRFScore.plot"] + + +_N_GRAM_LEVELS = ("char", "word") +_TEXT_LEVELS = ("preds", "target", "matching") + +_DICT_STATES_NAMES = ( + "total_preds_char_n_grams", + "total_preds_word_n_grams", + "total_target_char_n_grams", + "total_target_word_n_grams", + "total_matching_char_n_grams", + "total_matching_word_n_grams", +) + +_DICT_STATES_TYPES = tuple[ + dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor] +] + + +class CHRFScore(Metric): + """Calculate `chrf score`_ of machine translated text with one or more references. + + This implementation supports both ChrF score computation introduced in `chrF score`_ and `chrF++ score`_ introduced + in `chrF++ score`_. This implementation follows the implementations from https://github.com/m-popovic/chrF and + https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus + - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``chrf`` (:class:`~torch.Tensor`): If `return_sentence_level_score=True` return a list of sentence-level + chrF/chrF++ scores, else return a corpus-level chrF/chrF++ score + + Args: + n_char_order: A character n-gram order. If ``n_char_order=6``, the metrics refers to the official chrF/chrF++. + n_word_order: A word n-gram order. If ``n_word_order=2``, the metric refers to the official chrF++. + If ``n_word_order=0``, the metric is equivalent to the original ChrF. + beta: parameter determining an importance of recall w.r.t. precision. If ``beta=1``, their importance is equal. + lowercase: An indication whether to enable case-insensitivity. + whitespace: An indication whether keep whitespaces during n-gram extraction. + return_sentence_level_score: An indication whether a sentence-level chrF/chrF++ score to be returned. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError: + If ``n_char_order`` is not an integer greater than or equal to 1. + ValueError: + If ``n_word_order`` is not an integer greater than or equal to 0. + ValueError: + If ``beta`` is smaller than 0. + + Example: + >>> from torchmetrics.text import CHRFScore + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> chrf = CHRFScore() + >>> chrf(preds, target) + tensor(0.8640) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + sentence_chrf_score: Optional[List[Tensor]] = None + + def __init__( + self, + n_char_order: int = 6, + n_word_order: int = 2, + beta: float = 2.0, + lowercase: bool = False, + whitespace: bool = False, + return_sentence_level_score: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if not isinstance(n_char_order, int) or n_char_order < 1: + raise ValueError("Expected argument `n_char_order` to be an integer greater than or equal to 1.") + self.n_char_order = n_char_order + if not isinstance(n_word_order, int) or n_word_order < 0: + raise ValueError("Expected argument `n_word_order` to be an integer greater than or equal to 0.") + self.n_word_order = n_word_order + if beta < 0: + raise ValueError("Expected argument `beta` to be greater than 0.") + self.beta = beta + self.lowercase = lowercase + self.whitespace = whitespace + self.return_sentence_level_score = return_sentence_level_score + + self.n_order = float(n_char_order + n_word_order) + + # Adding state dynamically + for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator(): + for n in range(1, n_gram_order + 1): + state_name = self._get_state_name(text, n_gram_level, n) + self.add_state(state_name, tensor(0.0), dist_reduce_fx="sum") + + if self.return_sentence_level_score: + self.add_state("sentence_chrf_score", [], dist_reduce_fx="cat") + + def update(self, preds: Sequence[str], target: Sequence[Sequence[str]]) -> None: + """Update state with predictions and targets.""" + n_grams_dicts_tuple = _chrf_score_update( + preds, + target, + *self._convert_states_to_dicts(), + self.n_char_order, + self.n_word_order, + self.n_order, + self.beta, + self.lowercase, + self.whitespace, + self.sentence_chrf_score if self.return_sentence_level_score else None, + ) + self._update_states_from_dicts(n_grams_dicts_tuple[:-1]) + if self.sentence_chrf_score is not None: + self.sentence_chrf_score = n_grams_dicts_tuple[-1] + + def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Calculate chrF/chrF++ score.""" + if self.sentence_chrf_score is not None: + return ( + _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta), + torch.cat(self.sentence_chrf_score), + ) + return _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta) + + def _convert_states_to_dicts(self) -> _DICT_STATES_TYPES: + """Convert global metric states to the n-gram dictionaries to be passed in ``_chrf_score_update``.""" + n_grams_dicts: dict[str, dict[int, Tensor]] = dict( + zip(_DICT_STATES_NAMES, _prepare_n_grams_dicts(self.n_char_order, self.n_word_order)) + ) + + for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator(): + for n in range(1, n_gram_order + 1): + dict_name = self._get_dict_name(text, n_gram_level) + state_name = self._get_state_name(text, n_gram_level, n) + + n_grams_dicts[dict_name][n] = getattr(self, state_name) + + return tuple(n_grams_dicts.values()) # type: ignore + + def _update_states_from_dicts(self, n_grams_dicts_tuple: _DICT_STATES_TYPES) -> None: + """Update global metric states based on the n-gram dictionaries calculated on the current batch.""" + n_grams_dicts = dict(zip(_DICT_STATES_NAMES, n_grams_dicts_tuple)) + for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator(): + for n in range(1, n_gram_order + 1): + dict_name = self._get_dict_name(text, n_gram_level) + state_name = self._get_state_name(text, n_gram_level, n) + + setattr(self, state_name, n_grams_dicts[dict_name][n]) + + @staticmethod + def _get_dict_name(text: str, n_gram_level: str) -> str: + """Return a dictionary name w.r.t input args.""" + return f"total_{text}_{n_gram_level}_n_grams" + + @staticmethod + def _get_state_name(text: str, n_gram_level: str, n: int) -> str: + """Return a metric state name w.r.t input args.""" + return f"total_{text}_{n_gram_level}_{n}_grams" + + def _get_text_n_gram_iterator(self) -> Iterator[tuple[tuple[str, int], str]]: + """Get iterator over char/word and reference/hypothesis/matching n-gram level.""" + return itertools.product(zip(_N_GRAM_LEVELS, [self.n_char_order, self.n_word_order]), _TEXT_LEVELS) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import CHRFScore + >>> metric = CHRFScore() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import CHRFScore + >>> metric = CHRFScore() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/edit.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/edit.py new file mode 100644 index 0000000000000000000000000000000000000000..947fc79cd6cad4ebbf72936b2ff4cf6ea407a810 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/edit.py @@ -0,0 +1,175 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Literal, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.text.edit import _edit_distance_compute, _edit_distance_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["EditDistance.plot"] + + +class EditDistance(Metric): + """Calculates the Levenshtein edit distance between two sequences. + + The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform the + predicted text into the reference text. The lower the distance, the more accurate the model is considered to be. + + Implementation is similar to `nltk.edit_distance `_. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus + - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``eed`` (:class:`~torch.Tensor`): A tensor with the extended edit distance score. If `reduction` is set to + ``'none'`` or ``None``, this has shape ``(N, )``, where ``N`` is the batch size. Otherwise, this is a scalar. + + Args: + substitution_cost: The cost of substituting one character for another. + reduction: a method to reduce metric score over samples. + + - ``'mean'``: takes the mean over samples + - ``'sum'``: takes the sum over samples + - ``None`` or ``'none'``: return the score per sample + + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example:: + Basic example with two strings. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits: + + >>> from torchmetrics.text import EditDistance + >>> metric = EditDistance() + >>> metric(["rain"], ["shine"]) + tensor(3.) + + Example:: + Basic example with two strings and substitution cost of 2. Going from “rain” -> “sain” -> “shin” -> “shine” + takes 3 edits, where two of them are substitutions: + + >>> from torchmetrics.text import EditDistance + >>> metric = EditDistance(substitution_cost=2) + >>> metric(["rain"], ["shine"]) + tensor(5.) + + Example:: + Multiple strings example: + + >>> from torchmetrics.text import EditDistance + >>> metric = EditDistance(reduction=None) + >>> metric(["rain", "lnaguaeg"], ["shine", "language"]) + tensor([3, 4], dtype=torch.int32) + >>> metric = EditDistance(reduction="mean") + >>> metric(["rain", "lnaguaeg"], ["shine", "language"]) + tensor(3.5000) + + """ + + higher_is_better: bool = False + is_differentiable: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + + edit_scores_list: List[Tensor] + edit_scores: Tensor + num_elements: Tensor + + def __init__( + self, substitution_cost: int = 1, reduction: Optional[Literal["mean", "sum", "none"]] = "mean", **kwargs: Any + ) -> None: + super().__init__(**kwargs) + if not (isinstance(substitution_cost, int) and substitution_cost >= 0): + raise ValueError( + f"Expected argument `substitution_cost` to be a positive integer, but got {substitution_cost}" + ) + self.substitution_cost = substitution_cost + + allowed_reduction = (None, "mean", "sum", "none") + if reduction not in allowed_reduction: + raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction}, but got {reduction}") + self.reduction = reduction + + if self.reduction == "none" or self.reduction is None: + self.add_state("edit_scores_list", default=[], dist_reduce_fx="cat") + else: + self.add_state("edit_scores", default=torch.tensor(0), dist_reduce_fx="sum") + self.add_state("num_elements", default=torch.tensor(0), dist_reduce_fx="sum") + + def update(self, preds: Union[str, Sequence[str]], target: Union[str, Sequence[str]]) -> None: + """Update state with predictions and targets.""" + distance = _edit_distance_update(preds, target, self.substitution_cost) + if self.reduction == "none" or self.reduction is None: + self.edit_scores_list.append(distance) + else: + self.edit_scores += distance.sum() + self.num_elements += distance.shape[0] + + def compute(self) -> torch.Tensor: + """Compute the edit distance over state.""" + if self.reduction == "none" or self.reduction is None: + return _edit_distance_compute(dim_zero_cat(self.edit_scores_list), 1, self.reduction) + return _edit_distance_compute(self.edit_scores, self.num_elements, self.reduction) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import EditDistance + >>> metric = EditDistance() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import EditDistance + >>> metric = EditDistance() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/eed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/eed.py new file mode 100644 index 0000000000000000000000000000000000000000..86f366c84cc51cd92b942969d3eaeb0b6cd8c393 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/eed.py @@ -0,0 +1,166 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +from torch import Tensor, stack +from typing_extensions import Literal + +from torchmetrics.functional.text.eed import _eed_compute, _eed_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ExtendedEditDistance.plot"] + + +class ExtendedEditDistance(Metric): + """Compute extended edit distance score (`ExtendedEditDistance`_) for strings or list of strings. + + The metric utilises the Levenshtein distance and extends it by adding a jump operation. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus + - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``eed`` (:class:`~torch.Tensor`): A tensor with the extended edit distance score + + Args: + language: Language used in sentences. Only supports English (en) and Japanese (ja) for now. + return_sentence_level_score: An indication of whether sentence-level EED score is to be returned + alpha: optimal jump penalty, penalty for jumps between characters + rho: coverage cost, penalty for repetition of characters + deletion: penalty for deletion of character + insertion: penalty for insertion or substitution of character + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.text import ExtendedEditDistance + >>> preds = ["this is the prediction", "here is an other sample"] + >>> target = ["this is the reference", "here is another one"] + >>> eed = ExtendedEditDistance() + >>> eed(preds=preds, target=target) + tensor(0.3078) + + """ + + higher_is_better: bool = False + is_differentiable: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + sentence_eed: List[Tensor] + + def __init__( + self, + language: Literal["en", "ja"] = "en", + return_sentence_level_score: bool = False, + alpha: float = 2.0, + rho: float = 0.3, + deletion: float = 0.2, + insertion: float = 1.0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + if language not in ("en", "ja"): + raise ValueError(f"Expected argument `language` to either be `en` or `ja` but got {language}") + self.language: Literal["en", "ja"] = language + self.return_sentence_level_score = return_sentence_level_score + + # input validation for parameters + for param_name, param in zip(["alpha", "rho", "deletion", "insertion"], [alpha, rho, deletion, insertion]): + if not isinstance(param, float) or (isinstance(param, float) and param < 0): + raise ValueError(f"Parameter `{param_name}` is expected to be a non-negative float.") + + self.alpha = alpha + self.rho = rho + self.deletion = deletion + self.insertion = insertion + + self.add_state("sentence_eed", [], dist_reduce_fx="cat") + + def update( + self, + preds: Union[str, Sequence[str]], + target: Sequence[Union[str, Sequence[str]]], + ) -> None: + """Update state with predictions and targets.""" + self.sentence_eed = _eed_update( + preds, + target, + self.language, + self.alpha, + self.rho, + self.deletion, + self.insertion, + self.sentence_eed, + ) + + def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Calculate extended edit distance score.""" + average = _eed_compute(self.sentence_eed) + + if self.return_sentence_level_score: + return average, stack(self.sentence_eed) + return average + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import ExtendedEditDistance + >>> metric = ExtendedEditDistance() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import ExtendedEditDistance + >>> metric = ExtendedEditDistance() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/infolm.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/infolm.py new file mode 100644 index 0000000000000000000000000000000000000000..74e931c7cba3a8ede844866c0eb11c4ea6510f37 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/infolm.py @@ -0,0 +1,267 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +from collections.abc import Sequence +from typing import Any, ClassVar, List, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.functional.text.helper_embedding_metric import _load_tokenizer_and_model +from torchmetrics.functional.text.infolm import ( + _ALLOWED_INFORMATION_MEASURE_LITERAL, + _get_dataloader, + _get_special_tokens_map, + _infolm_compute, + _infolm_update, + _InformationMeasure, +) +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TRANSFORMERS_GREATER_EQUAL_4_4 +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["InfoLM.plot"] + +if not _TRANSFORMERS_GREATER_EQUAL_4_4: + __doctest_skip__ = ["InfoLM", "InfoLM.plot"] + + +class InfoLM(Metric): + """Calculate `InfoLM`_. + + InfoLM measures a distance/divergence between predicted and reference sentence discrete distribution using one of + the following information measures: + + - `KL divergence`_ + - `alpha divergence`_ + - `beta divergence`_ + - `AB divergence`_ + - `Rényi divergence`_ + - L1 distance + - L2 distance + - L-infinity distance + - `Fisher-Rao distance`_ + + `InfoLM`_ is a family of untrained embedding-based metrics which addresses some famous flaws of standard + string-based metrics thanks to the usage of pre-trained masked language models. This family of metrics is mainly + designed for summarization and data-to-text tasks. + + The implementation of this metric is fully based HuggingFace ``transformers``' package. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus + - ``target`` (:class:`~Sequence`): An iterable of reference corpus + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``infolm`` (:class:`~torch.Tensor`): If `return_sentence_level_score=True` return a tuple with a tensor + with the corpus-level InfoLM score and a list of sentence-level InfoLM scores, else return a corpus-level + InfoLM score + + Args: + model_name_or_path: + A name or a model path used to load ``transformers`` pretrained model. + By default the `"bert-base-uncased"` model is used. + temperature: + A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper. + information_measure: + A name of information measure to be used. Please use one of: ['kl_divergence', 'alpha_divergence', + 'beta_divergence', 'ab_divergence', 'renyi_divergence', 'l1_distance', 'l2_distance', 'l_infinity_distance', + 'fisher_rao_distance'] + idf: + An indication of whether normalization using inverse document frequencies should be used. + alpha: + Alpha parameter of the divergence used for alpha, AB and Rényi divergence measures. + beta: + Beta parameter of the divergence used for beta and AB divergence measures. + device: + A device to be used for calculation. + max_length: + A maximum length of input sequences. Sequences longer than ``max_length`` are to be trimmed. + batch_size: + A batch size used for model processing. + num_threads: + A number of threads to use for a dataloader. + verbose: + An indication of whether a progress bar to be displayed during the embeddings calculation. + return_sentence_level_score: + An indication whether a sentence-level InfoLM score to be returned. + + Example: + >>> from torchmetrics.text.infolm import InfoLM + >>> preds = ['he read the book because he was interested in world history'] + >>> target = ['he was interested in world history because he read the book'] + >>> infolm = InfoLM('google/bert_uncased_L-2_H-128_A-2', idf=False) + >>> infolm(preds, target) + tensor(-0.1784) + + """ + + is_differentiable = False + preds_input_ids: List[Tensor] + preds_attention_mask: List[Tensor] + target_input_ids: List[Tensor] + target_attention_mask: List[Tensor] + + _information_measure_higher_is_better: ClassVar = { + # following values are <0 + "kl_divergence": True, + "alpha_divergence": True, + # following values are >0 + "beta_divergence": False, + "ab_divergence": False, + "renyi_divergence": False, + "l1_distance": False, + "l2_distance": False, + "l_infinity_distance": False, + "fisher_rao_distance": False, + } + + def __init__( + self, + model_name_or_path: Union[str, os.PathLike] = "bert-base-uncased", + temperature: float = 0.25, + information_measure: _ALLOWED_INFORMATION_MEASURE_LITERAL = "kl_divergence", + idf: bool = True, + alpha: Optional[float] = None, + beta: Optional[float] = None, + device: Optional[Union[str, torch.device]] = None, + max_length: Optional[int] = None, + batch_size: int = 64, + num_threads: int = 0, + verbose: bool = True, + return_sentence_level_score: bool = False, + **kwargs: dict[str, Any], + ) -> None: + super().__init__(**kwargs) + self.model_name_or_path = model_name_or_path + self.temperature = temperature + self.information_measure = information_measure + self.idf = idf + self.alpha = alpha + self.beta = beta + self._device = torch.device(device or "cpu") + self.batch_size = batch_size + self.num_threads = num_threads + self.verbose = verbose + self.return_sentence_level_score = return_sentence_level_score + + self.tokenizer, self.model = _load_tokenizer_and_model(model_name_or_path, device) + self.information_measure_cls = _InformationMeasure(information_measure, alpha, beta) + self.max_length = max_length or self.model.config.max_length + self.special_tokens_map = _get_special_tokens_map(self.tokenizer) + + self.add_state("preds_input_ids", [], dist_reduce_fx="cat") + self.add_state("preds_attention_mask", [], dist_reduce_fx="cat") + self.add_state("target_input_ids", [], dist_reduce_fx="cat") + self.add_state("target_attention_mask", [], dist_reduce_fx="cat") + + @property + def higher_is_better(self) -> bool: # type: ignore[override] + """Returns a bool indicating whether a higher value of the information measure is better. + + Done this way as depends on if the information measure is positive or negative. + + """ + return self._information_measure_higher_is_better[self.information_measure] + + def update(self, preds: Union[str, Sequence[str]], target: Union[str, Sequence[str]]) -> None: + """Update state with predictions and targets.""" + preds_input_ids, preds_attention_mask, target_input_ids, target_attention_mask = _infolm_update( + preds, target, self.tokenizer, self.max_length + ) + self.preds_input_ids.append(preds_input_ids) + self.preds_attention_mask.append(preds_attention_mask) + self.target_input_ids.append(target_input_ids) + self.target_attention_mask.append(target_attention_mask) + + def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Calculate selected information measure using the pre-trained language model.""" + preds_dataloader = _get_dataloader( + input_ids=dim_zero_cat(self.preds_input_ids), + attention_mask=dim_zero_cat(self.preds_attention_mask), + idf=self.idf, + batch_size=self.batch_size, + num_workers=self.num_threads, + ) + target_dataloader = _get_dataloader( + input_ids=dim_zero_cat(self.target_input_ids), + attention_mask=dim_zero_cat(self.target_attention_mask), + idf=self.idf, + batch_size=self.batch_size, + num_workers=self.num_threads, + ) + + info_lm_score = _infolm_compute( + self.model, + preds_dataloader, + target_dataloader, + self.temperature, + self.idf, + self.information_measure_cls, + self.special_tokens_map, + self.verbose, + ) + + if self.return_sentence_level_score: + return info_lm_score.mean(), info_lm_score + + return info_lm_score.mean() + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text.infolm import InfoLM + >>> metric = InfoLM('google/bert_uncased_L-2_H-128_A-2', idf=False) + >>> preds = ['he read the book because he was interested in world history'] + >>> target = ['he was interested in world history because he read the book'] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text.infolm import InfoLM + >>> metric = InfoLM('google/bert_uncased_L-2_H-128_A-2', idf=False) + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/mer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/mer.py new file mode 100644 index 0000000000000000000000000000000000000000..a898c9c475824d222832b58b1fd34f004eb389c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/mer.py @@ -0,0 +1,141 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.mer import _mer_compute, _mer_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MatchErrorRate.plot"] + + +class MatchErrorRate(Metric): + r"""Match Error Rate (`MER`_) is a common metric of the performance of an automatic speech recognition system. + + This value indicates the percentage of words that were incorrectly predicted and inserted. + The lower the value, the better the performance of the ASR system with a MatchErrorRate of 0 being a perfect score. + Match error rate can then be computed as: + + .. math:: + mer = \frac{S + D + I}{N + I} = \frac{S + D + I}{S + D + C + I} + + where: + - :math:`S` is the number of substitutions, + - :math:`D` is the number of deletions, + - :math:`I` is the number of insertions, + - :math:`C` is the number of correct words, + - :math:`N` is the number of words in the reference (:math:`N=S+D+C`). + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~List`): Transcription(s) to score as a string or list of strings + - ``target`` (:class:`~List`): Reference(s) for each speech input as a string or list of strings + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``mer`` (:class:`~torch.Tensor`): A tensor with the match error rate + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Examples: + >>> from torchmetrics.text import MatchErrorRate + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> mer = MatchErrorRate() + >>> mer(preds, target) + tensor(0.4444) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + errors: Tensor + total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.add_state("errors", tensor(0, dtype=torch.float), dist_reduce_fx="sum") + self.add_state("total", tensor(0, dtype=torch.float), dist_reduce_fx="sum") + + def update( + self, + preds: Union[str, list[str]], + target: Union[str, list[str]], + ) -> None: + """Update state with predictions and targets.""" + errors, total = _mer_update(preds, target) + self.errors += errors + self.total += total + + def compute(self) -> Tensor: + """Calculate the Match error rate.""" + return _mer_compute(self.errors, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import MatchErrorRate + >>> metric = MatchErrorRate() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import MatchErrorRate + >>> metric = MatchErrorRate() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/perplexity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/perplexity.py new file mode 100644 index 0000000000000000000000000000000000000000..af8d9e70795a549c1ca6b5d05c0a0d4910ed264f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/perplexity.py @@ -0,0 +1,131 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.text.perplexity import _perplexity_compute, _perplexity_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["Perplexity.plot"] + + +class Perplexity(Metric): + r"""Perplexity measures how well a language model predicts a text sample. + + It's calculated as the average number of bits per word a model needs to represent the sample. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Logits or a unnormalized score assigned to each token in a sequence with shape + [batch_size, seq_len, vocab_size], which is the output of a language model. Scores will be normalized internally + using softmax. + - ``target`` (:class:`~torch.Tensor`): Ground truth values with a shape [batch_size, seq_len] + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``perp`` (:class:`~torch.Tensor`): A tensor with the perplexity score + + Args: + ignore_index: Integer specifying a target class to ignore. + If given, this class index does not contribute to the returned score. + kwargs: + Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Examples: + >>> from torch import rand, randint + >>> from torchmetrics.text import Perplexity + >>> preds = rand(2, 8, 5) + >>> target = randint(5, (2, 8)) + >>> target[0, 6:] = -100 + >>> perp = Perplexity(ignore_index=-100) + >>> perp(preds, target) + tensor(5.8540) + + """ + + is_differentiable = True + higher_is_better = False + full_state_update = False + total_log_probs: Tensor + count: Tensor + + def __init__( + self, + ignore_index: Optional[int] = None, + **kwargs: dict[str, Any], + ) -> None: + super().__init__(**kwargs) + if ignore_index is not None and not isinstance(ignore_index, int): + raise ValueError(f"Argument `ignore_index` expected to either be `None` or an `int` but got {ignore_index}") + self.ignore_index = ignore_index + self.add_state("total_log_probs", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("count", default=tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + total_log_probs, count = _perplexity_update(preds, target, self.ignore_index) + self.total_log_probs += total_log_probs + self.count += count + + def compute(self) -> Tensor: + """Compute the Perplexity.""" + return _perplexity_compute(self.total_log_probs, self.count) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.text import Perplexity + >>> metric = Perplexity() + >>> metric.update(torch.rand(2, 8, 5), torch.randint(5, (2, 8))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.text import Perplexity + >>> metric = Perplexity() + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(torch.rand(2, 8, 5), torch.randint(5, (2, 8)))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/rouge.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/rouge.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1ef711afcfd233057b1be7207bcb17d9c7d72e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/rouge.py @@ -0,0 +1,237 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics import Metric +from torchmetrics.functional.text.rouge import ( + ALLOWED_ACCUMULATE_VALUES, + ALLOWED_ROUGE_KEYS, + _rouge_score_compute, + _rouge_score_update, +) +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _NLTK_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ROUGEScore.plot"] + + +__doctest_requires__ = {("ROUGEScore",): ["nltk"]} + + +class ROUGEScore(Metric): + """`Calculate Rouge Score`_, used for automatic summarization. + + This implementation should imitate the behaviour of the ``rouge-score`` package `Python ROUGE Implementation` + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of predicted sentences or a single predicted sentence + - ``target`` (:class:`~Sequence`): An iterable of target sentences + or an iterable of interables of target sentences + or a single target sentence + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``rouge`` (:class:`~Dict`): A dictionary of tensor rouge scores for each input str rouge key + + Args: + use_stemmer: Use Porter stemmer to strip word suffixes to improve matching. + normalizer: A user's own normalizer function. + If this is ``None``, replacing any non-alpha-numeric characters with spaces is default. + This function must take a ``str`` and return a ``str``. + tokenizer: + A user's own tokenizer function. If this is ``None``, splitting by spaces is default + This function must take a ``str`` and return ``Sequence[str]`` + accumulate: + Useful in case of multi-reference rouge score. + + - ``avg`` takes the avg of all references with respect to predictions + - ``best`` takes the best fmeasure score obtained between prediction and multiple corresponding references. + + rouge_keys: A list of rouge types to calculate. + Keys that are allowed are ``rougeL``, ``rougeLsum``, and ``rouge1`` through ``rouge9``. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.text.rouge import ROUGEScore + >>> preds = "My name is John" + >>> target = "Is your name John" + >>> rouge = ROUGEScore() + >>> from pprint import pprint + >>> pprint(rouge(preds, target)) + {'rouge1_fmeasure': tensor(0.7500), + 'rouge1_precision': tensor(0.7500), + 'rouge1_recall': tensor(0.7500), + 'rouge2_fmeasure': tensor(0.), + 'rouge2_precision': tensor(0.), + 'rouge2_recall': tensor(0.), + 'rougeL_fmeasure': tensor(0.5000), + 'rougeL_precision': tensor(0.5000), + 'rougeL_recall': tensor(0.5000), + 'rougeLsum_fmeasure': tensor(0.5000), + 'rougeLsum_precision': tensor(0.5000), + 'rougeLsum_recall': tensor(0.5000)} + + + Raises: + ValueError: + If the python packages ``nltk`` is not installed. + ValueError: + If any of the ``rouge_keys`` does not belong to the allowed set of keys. + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + use_stemmer: bool = False, + normalizer: Optional[Callable[[str], str]] = None, + tokenizer: Optional[Callable[[str], Sequence[str]]] = None, + accumulate: Literal["avg", "best"] = "best", + rouge_keys: Union[str, tuple[str, ...]] = ("rouge1", "rouge2", "rougeL", "rougeLsum"), + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if use_stemmer or "rougeLsum" in rouge_keys: + if not _NLTK_AVAILABLE: + raise ModuleNotFoundError( + "Stemmer and/or `rougeLsum` requires that `nltk` is installed. Use `pip install nltk`." + ) + import nltk + + if not isinstance(rouge_keys, tuple): + rouge_keys = (rouge_keys,) + for key in rouge_keys: + if key not in ALLOWED_ROUGE_KEYS: + raise ValueError(f"Got unknown rouge key {key}. Expected to be one of {ALLOWED_ROUGE_KEYS}") + + if accumulate not in ALLOWED_ACCUMULATE_VALUES: + raise ValueError( + f"Got unknown accumulate value {accumulate}. Expected to be one of {ALLOWED_ACCUMULATE_VALUES}" + ) + + self.rouge_keys = rouge_keys + self.rouge_keys_values = [ALLOWED_ROUGE_KEYS[key] for key in rouge_keys] + self.stemmer = nltk.stem.porter.PorterStemmer() if use_stemmer else None + self.normalizer = normalizer + self.tokenizer = tokenizer + self.accumulate = accumulate + + # Adding stated dynamically to prevent IndexError during sync function as some lists can be empty. + for rouge_key in self.rouge_keys: + for score in ["fmeasure", "precision", "recall"]: + self.add_state(f"{rouge_key}_{score}", [], dist_reduce_fx=None) + + def update( + self, preds: Union[str, Sequence[str]], target: Union[str, Sequence[str], Sequence[Sequence[str]]] + ) -> None: + """Update state with predictions and targets.""" + if isinstance(target, list) and all(isinstance(tgt, str) for tgt in target): + target = [target] if isinstance(preds, str) else [[tgt] for tgt in target] + + if isinstance(preds, str): + preds = [preds] + + if isinstance(target, str): + target = [[target]] + + output: dict[Union[int, str], list[dict[str, Tensor]]] = _rouge_score_update( + preds, + target, + self.rouge_keys_values, + stemmer=self.stemmer, + normalizer=self.normalizer, + tokenizer=self.tokenizer, + accumulate=self.accumulate, + ) + for rouge_key, metrics in output.items(): + for metric in metrics: + for tp, value in metric.items(): + getattr(self, f"rouge{rouge_key}_{tp}").append(value.to(self.device)) # todo + + def compute(self) -> dict[str, Tensor]: + """Calculate (Aggregate and provide confidence intervals) ROUGE score.""" + update_output = {} + for rouge_key in self.rouge_keys_values: + for tp in ["fmeasure", "precision", "recall"]: + update_output[f"rouge{rouge_key}_{tp}"] = getattr(self, f"rouge{rouge_key}_{tp}") + + return _rouge_score_compute(update_output) + + def __hash__(self) -> int: + """Return a unique hash for the specific instance of this metric.""" + # override to hash list objects. + # this is a bug in the upstream pytorch release. + hash_vals = [self.__class__.__name__] + for key in self._defaults: + value = getattr(self, key) + if isinstance(value, list): + value = tuple(value) + hash_vals.append(value) + + return hash(tuple(hash_vals)) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text.rouge import ROUGEScore + >>> metric = ROUGEScore() + >>> preds = "My name is John" + >>> target = "Is your name John" + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text.rouge import ROUGEScore + >>> metric = ROUGEScore() + >>> preds = "My name is John" + >>> target = "Is your name John" + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/sacre_bleu.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/sacre_bleu.py new file mode 100644 index 0000000000000000000000000000000000000000..13e61ebe07f6c56275bc23a24c6fd897b0483dc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/sacre_bleu.py @@ -0,0 +1,180 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# referenced from +# Library Name: torchtext +# Authors: torchtext authors and @sluks +# Date: 2020-07-18 +# Link: https://pytorch.org/text/_modules/torchtext/data/metrics.html#bleu_score +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor + +from torchmetrics.functional.text.bleu import _bleu_score_update +from torchmetrics.functional.text.sacre_bleu import _SacreBLEUTokenizer, _TokenizersLiteral +from torchmetrics.text.bleu import BLEUScore +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["SacreBLEUScore.plot"] + + +class SacreBLEUScore(BLEUScore): + """Calculate `BLEU score`_ of machine translated text with one or more references. + + This implementation follows the behaviour of `SacreBLEU`_. The SacreBLEU implementation differs from the NLTK BLEU + implementation in tokenization techniques. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of machine translated corpus + - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``sacre_bleu`` (:class:`~torch.Tensor`): A tensor with the SacreBLEU Score + + .. note:: + In the original SacreBLEU, references are passed as a list of reference sets (grouped by reference index). + In TorchMetrics, references are passed grouped per prediction (each prediction has its own list of references). + + For example:: + + # Predictions + preds = ['The dog bit the man.', "It wasn't surprising.", 'The man had just bitten him.'] + + # Original SacreBLEU: + refs = [ + ['The dog bit the man.', 'It was not unexpected.', 'The man bit him first.'], # First set + ['The dog had bit the man.', 'No one was surprised.', 'The man had bitten the dog.'], # Second set + ] + + # TorchMetrics SacreBLEU: + target = [ + ['The dog bit the man.', 'The dog had bit the man.'], # References for first prediction + ['It was not unexpected.', 'No one was surprised.'], # References for second prediction + ['The man bit him first.', 'The man had bitten the dog.'], # References for third prediction + ] + + Args: + n_gram: Gram value ranged from 1 to 4 + smooth: Whether to apply smoothing, see `SacreBLEU`_ + tokenize: Tokenization technique to be used. Choose between ``'none'``, ``'13a'``, ``'zh'``, ``'intl'``, + ``'char'``, ``'ja-mecab'``, ``'ko-mecab'``, ``'flores101'`` and ``'flores200'``. + lowercase: If ``True``, BLEU score over lowercased text is calculated. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + weights: + Weights used for unigrams, bigrams, etc. to calculate BLEU score. + If not provided, uniform weights are used. + + Raises: + ValueError: + If ``tokenize`` not one of 'none', '13a', 'zh', 'intl' or 'char' + ValueError: + If ``tokenize`` is set to 'intl' and `regex` is not installed + ValueError: + If a length of a list of weights is not ``None`` and not equal to ``n_gram``. + + + Example: + >>> from torchmetrics.text import SacreBLEUScore + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> sacre_bleu = SacreBLEUScore() + >>> sacre_bleu(preds, target) + tensor(0.7598) + + Additional References: + + - Automatic Evaluation of Machine Translation Quality Using Longest Common Subsequence + and Skip-Bigram Statistics by Chin-Yew Lin and Franz Josef Och `Machine Translation Evolution`_ + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = True + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + def __init__( + self, + n_gram: int = 4, + smooth: bool = False, + tokenize: _TokenizersLiteral = "13a", + lowercase: bool = False, + weights: Optional[Sequence[float]] = None, + **kwargs: Any, + ) -> None: + super().__init__(n_gram=n_gram, smooth=smooth, weights=weights, **kwargs) + self.tokenizer = _SacreBLEUTokenizer(tokenize, lowercase) + + def update(self, preds: Sequence[str], target: Sequence[Sequence[str]]) -> None: + """Update state with predictions and targets.""" + self.preds_len, self.target_len = _bleu_score_update( + preds, + target, + self.numerator, + self.denominator, + self.preds_len, + self.target_len, + self.n_gram, + self.tokenizer, + ) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import SacreBLEUScore + >>> metric = SacreBLEUScore() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import SacreBLEUScore + >>> metric = SacreBLEUScore() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/squad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/squad.py new file mode 100644 index 0000000000000000000000000000000000000000..a545da95803ef039607251a475e0d467f45e8950 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/squad.py @@ -0,0 +1,168 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics import Metric +from torchmetrics.functional.text.squad import ( + PREDS_TYPE, + TARGETS_TYPE, + _squad_compute, + _squad_input_check, + _squad_update, +) +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["SQuAD.plot"] + + +class SQuAD(Metric): + """Calculate `SQuAD Metric`_ which is a metric for evaluating question answering models. + + This metric corresponds to the scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD). + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Dict`): A Dictionary or List of Dictionary-s that map ``id`` and ``prediction_text`` to + the respective values + + Example ``prediction``: + + .. code-block:: python + + {"prediction_text": "TorchMetrics is awesome", "id": "123"} + + + - ``target`` (:class:`~Dict`): A Dictionary or List of Dictionary-s that contain the ``answers`` and ``id`` in + the SQuAD Format. + + Example ``target``: + + .. code-block:: python + + { + 'answers': [{'answer_start': [1], 'text': ['This is a test answer']}], + 'id': '1', + } + + Reference SQuAD Format: + + .. code-block:: python + + { + 'answers': {'answer_start': [1], 'text': ['This is a test text']}, + 'context': 'This is a test context.', + 'id': '1', + 'question': 'Is this a test?', + 'title': 'train test' + } + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``squad`` (:class:`~Dict`): A dictionary containing the F1 score (key: "f1"), + and Exact match score (key: "exact_match") for the batch. + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.text import SQuAD + >>> preds = [{"prediction_text": "1976", "id": "56e10a3be3433e1400422b22"}] + >>> target = [{"answers": {"answer_start": [97], "text": ["1976"]}, "id": "56e10a3be3433e1400422b22"}] + >>> squad = SQuAD() + >>> squad(preds, target) + {'exact_match': tensor(100.), 'f1': tensor(100.)} + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 100.0 + + f1_score: Tensor + exact_match: Tensor + total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + self.add_state(name="f1_score", default=torch.tensor(0, dtype=torch.float), dist_reduce_fx="sum") + self.add_state(name="exact_match", default=torch.tensor(0, dtype=torch.float), dist_reduce_fx="sum") + self.add_state(name="total", default=torch.tensor(0, dtype=torch.int), dist_reduce_fx="sum") + + def update(self, preds: PREDS_TYPE, target: TARGETS_TYPE) -> None: + """Update state with predictions and targets.""" + preds_dict, target_dict = _squad_input_check(preds, target) + f1_score, exact_match, total = _squad_update(preds_dict, target_dict) + self.f1_score += f1_score + self.exact_match += exact_match + self.total += total + + def compute(self) -> dict[str, Tensor]: + """Aggregate the F1 Score and Exact match for the batch.""" + return _squad_compute(self.f1_score, self.exact_match, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import SQuAD + >>> metric = SQuAD() + >>> preds = [{"prediction_text": "1976", "id": "56e10a3be3433e1400422b22"}] + >>> target = [{"answers": {"answer_start": [97], "text": ["1976"]}, "id": "56e10a3be3433e1400422b22"}] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import SQuAD + >>> metric = SQuAD() + >>> preds = [{"prediction_text": "1976", "id": "56e10a3be3433e1400422b22"}] + >>> target = [{"answers": {"answer_start": [97], "text": ["1976"]}, "id": "56e10a3be3433e1400422b22"}] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/ter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/ter.py new file mode 100644 index 0000000000000000000000000000000000000000..6cdd1d02118b8a608c644894cca9e97ffb02cc1c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/ter.py @@ -0,0 +1,161 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.ter import _ter_compute, _ter_update, _TercomTokenizer +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["TranslationEditRate.plot"] + + +class TranslationEditRate(Metric): + """Calculate Translation edit rate (`TER`_) of machine translated text with one or more references. + + This implementation follows the one from `SacreBleu_ter`_, which is a + near-exact reimplementation of the Tercom algorithm, produces identical results on all "sane" outputs. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus + - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``ter`` (:class:`~torch.Tensor`): if ``return_sentence_level_score=True`` return a corpus-level translation + edit rate with a list of sentence-level translation_edit_rate, else return a corpus-level translation edit rate + + Args: + normalize: An indication whether a general tokenization to be applied. + no_punctuation: An indication whteher a punctuation to be removed from the sentences. + lowercase: An indication whether to enable case-insensitivity. + asian_support: An indication whether asian characters to be processed. + return_sentence_level_score: An indication whether a sentence-level TER to be returned. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example: + >>> from torchmetrics.text import TranslationEditRate + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> ter = TranslationEditRate() + >>> ter(preds, target) + tensor(0.1538) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + total_num_edits: Tensor + total_tgt_len: Tensor + sentence_ter: Optional[List[Tensor]] = None + + def __init__( + self, + normalize: bool = False, + no_punctuation: bool = False, + lowercase: bool = True, + asian_support: bool = False, + return_sentence_level_score: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(normalize, bool): + raise ValueError(f"Expected argument `normalize` to be of type boolean but got {normalize}.") + if not isinstance(no_punctuation, bool): + raise ValueError(f"Expected argument `no_punctuation` to be of type boolean but got {no_punctuation}.") + if not isinstance(lowercase, bool): + raise ValueError(f"Expected argument `lowercase` to be of type boolean but got {lowercase}.") + if not isinstance(asian_support, bool): + raise ValueError(f"Expected argument `asian_support` to be of type boolean but got {asian_support}.") + + self.tokenizer = _TercomTokenizer(normalize, no_punctuation, lowercase, asian_support) + self.return_sentence_level_score = return_sentence_level_score + + self.add_state("total_num_edits", tensor(0.0), dist_reduce_fx="sum") + self.add_state("total_tgt_len", tensor(0.0), dist_reduce_fx="sum") + if self.return_sentence_level_score: + self.add_state("sentence_ter", [], dist_reduce_fx="cat") + + def update(self, preds: Union[str, Sequence[str]], target: Sequence[Union[str, Sequence[str]]]) -> None: + """Update state with predictions and targets.""" + self.total_num_edits, self.total_tgt_len, self.sentence_ter = _ter_update( + preds, + target, + self.tokenizer, + self.total_num_edits, + self.total_tgt_len, + self.sentence_ter, + ) + + def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]: + """Calculate the translate error rate (TER).""" + ter = _ter_compute(self.total_num_edits, self.total_tgt_len) + if self.sentence_ter is not None: + return ter, torch.cat(self.sentence_ter) + return ter + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import TranslationEditRate + >>> metric = TranslationEditRate() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import TranslationEditRate + >>> metric = TranslationEditRate() + >>> preds = ['the cat is on the mat'] + >>> target = [['there is a cat on the mat', 'a cat is on the mat']] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wer.py new file mode 100644 index 0000000000000000000000000000000000000000..93bc7b8da136979f4632e8437292af362dad6a5c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wer.py @@ -0,0 +1,139 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor, tensor + +from torchmetrics.functional.text.wer import _wer_compute, _wer_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["WordErrorRate.plot"] + + +class WordErrorRate(Metric): + r"""Word error rate (`WordErrorRate`_) is a common metric of the performance of an automatic speech recognition. + + This value indicates the percentage of words that were incorrectly predicted. The lower the value, the + better the performance of the ASR system with a WER of 0 being a perfect score. Word error rate can then be + computed as: + + .. math:: + WER = \frac{S + D + I}{N} = \frac{S + D + I}{S + D + C} + + where: + - :math:`S` is the number of substitutions, + - :math:`D` is the number of deletions, + - :math:`I` is the number of insertions, + - :math:`C` is the number of correct words, + - :math:`N` is the number of words in the reference (:math:`N=S+D+C`). + + Compute WER score of transcribed segments against references. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~List`): Transcription(s) to score as a string or list of strings + - ``target`` (:class:`~List`): Reference(s) for each speech input as a string or list of strings + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``wer`` (:class:`~torch.Tensor`): A tensor with the Word Error Rate score + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Examples: + >>> from torchmetrics.text import WordErrorRate + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> wer = WordErrorRate() + >>> wer(preds, target) + tensor(0.5000) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + errors: Tensor + total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.add_state("errors", tensor(0, dtype=torch.float), dist_reduce_fx="sum") + self.add_state("total", tensor(0, dtype=torch.float), dist_reduce_fx="sum") + + def update(self, preds: Union[str, list[str]], target: Union[str, list[str]]) -> None: + """Update state with predictions and targets.""" + errors, total = _wer_update(preds, target) + self.errors += errors + self.total += total + + def compute(self) -> Tensor: + """Calculate the word error rate.""" + return _wer_compute(self.errors, self.total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import WordErrorRate + >>> metric = WordErrorRate() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import WordErrorRate + >>> metric = WordErrorRate() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wil.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wil.py new file mode 100644 index 0000000000000000000000000000000000000000..edd00b7f6572ca78a8994dc1be0a8811d5dc3dc7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wil.py @@ -0,0 +1,138 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.text.wil import _word_info_lost_compute, _word_info_lost_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["WordInfoLost.plot"] + + +class WordInfoLost(Metric): + r"""Word Information Lost (`WIL`_) is a metric of the performance of an automatic speech recognition system. + + This value indicates the percentage of words that were incorrectly predicted between a set of ground-truth + sentences and a set of hypothesis sentences. The lower the value, the better the performance of the ASR system + with a WordInfoLost of 0 being a perfect score. Word Information Lost rate can then be computed as: + + .. math:: + wil = 1 - \frac{C}{N} + \frac{C}{P} + + where: + + - :math:`C` is the number of correct words, + - :math:`N` is the number of words in the reference + - :math:`P` is the number of words in the prediction + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~List`): Transcription(s) to score as a string or list of strings + - ``target`` (:class:`~List`): Reference(s) for each speech input as a string or list of strings + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``wil`` (:class:`~torch.Tensor`): A tensor with the Word Information Lost score + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Examples: + >>> from torchmetrics.text import WordInfoLost + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> wil = WordInfoLost() + >>> wil(preds, target) + tensor(0.6528) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + errors: Tensor + target_total: Tensor + preds_total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.add_state("errors", tensor(0.0), dist_reduce_fx="sum") + self.add_state("target_total", tensor(0.0), dist_reduce_fx="sum") + self.add_state("preds_total", tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Union[str, list[str]], target: Union[str, list[str]]) -> None: + """Update state with predictions and targets.""" + errors, target_total, preds_total = _word_info_lost_update(preds, target) + self.errors += errors + self.target_total += target_total + self.preds_total += preds_total + + def compute(self) -> Tensor: + """Calculate the Word Information Lost.""" + return _word_info_lost_compute(self.errors, self.target_total, self.preds_total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import WordInfoLost + >>> metric = WordInfoLost() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import WordInfoLost + >>> metric = WordInfoLost() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wip.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wip.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b4351f5484a811cf915ca2224edf730b7b5bb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/text/wip.py @@ -0,0 +1,139 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor, tensor + +from torchmetrics.functional.text.wip import _wip_compute, _wip_update +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["WordInfoPreserved.plot"] + + +class WordInfoPreserved(Metric): + r"""Word Information Preserved (`WIP`_) is a metric of the performance of an automatic speech recognition system. + + This value indicates the percentage of words that were correctly predicted between a set of ground- + truth sentences and a set of hypothesis sentences. The higher the value, the better the performance of the ASR + system with a WordInfoPreserved of 1 being a perfect score. Word Information Preserved rate can then be + computed as: + + .. math:: + wip = \frac{C}{N} * \frac{C}{P} + + where: + + - :math:`C` is the number of correct words, + - :math:`N` is the number of words in the reference + - :math:`P` is the number of words in the prediction + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~List`): Transcription(s) to score as a string or list of strings + - ``target`` (:class:`~List`): Reference(s) for each speech input as a string or list of strings + + As output of ``forward`` and ``compute`` the metric returns the following output: + + - ``wip`` (:class:`~torch.Tensor`): A tensor with the Word Information Preserved score + + Args: + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Examples: + >>> from torchmetrics.text import WordInfoPreserved + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> wip = WordInfoPreserved() + >>> wip(preds, target) + tensor(0.3472) + + """ + + is_differentiable: bool = False + higher_is_better: bool = False + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 1.0 + + errors: Tensor + preds_total: Tensor + target_total: Tensor + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.add_state("errors", tensor(0.0), dist_reduce_fx="sum") + self.add_state("target_total", tensor(0.0), dist_reduce_fx="sum") + self.add_state("preds_total", tensor(0.0), dist_reduce_fx="sum") + + def update(self, preds: Union[str, list[str]], target: Union[str, list[str]]) -> None: + """Update state with predictions and targets.""" + errors, target_total, preds_total = _wip_update(preds, target) + self.errors += errors + self.target_total += target_total + self.preds_total += preds_total + + def compute(self) -> Tensor: + """Calculate the Word Information Preserved.""" + return _wip_compute(self.errors, self.target_total, self.preds_total) + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> from torchmetrics.text import WordInfoPreserved + >>> metric = WordInfoPreserved() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> metric.update(preds, target) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> from torchmetrics.text import WordInfoPreserved + >>> metric = WordInfoPreserved() + >>> preds = ["this is the prediction", "there is an other sample"] + >>> target = ["this is the reference", "there is another one"] + >>> values = [ ] + >>> for _ in range(10): + ... values.append(metric(preds, target)) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3225491739b756ca7832b4ef7dc92d81489de577 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/__init__.py @@ -0,0 +1,37 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.utilities.checks import check_forward_full_state_property +from torchmetrics.utilities.data import ( + dim_zero_cat, + dim_zero_max, + dim_zero_mean, + dim_zero_min, + dim_zero_sum, +) +from torchmetrics.utilities.distributed import class_reduce, reduce +from torchmetrics.utilities.prints import rank_zero_debug, rank_zero_info, rank_zero_warn + +__all__ = [ + "check_forward_full_state_property", + "class_reduce", + "dim_zero_cat", + "dim_zero_max", + "dim_zero_mean", + "dim_zero_min", + "dim_zero_sum", + "rank_zero_debug", + "rank_zero_info", + "rank_zero_warn", + "reduce", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/checks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/checks.py new file mode 100644 index 0000000000000000000000000000000000000000..daabd20e8b2e3862726084aaabf15109dd4163c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/checks.py @@ -0,0 +1,335 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import multiprocessing +import os +import sys +from collections.abc import Mapping, Sequence +from functools import partial +from time import perf_counter +from typing import Any, Callable, Optional, no_type_check +from unittest.mock import Mock + +import torch +from torch import Tensor + +from torchmetrics.metric import Metric + +_DOCTEST_DOWNLOAD_TIMEOUT = int(os.environ.get("DOCTEST_DOWNLOAD_TIMEOUT", 120)) +_SKIP_SLOW_DOCTEST = bool(os.environ.get("SKIP_SLOW_DOCTEST", 0)) + + +def _check_for_empty_tensors(preds: Tensor, target: Tensor) -> bool: + return preds.numel() == target.numel() == 0 + + +def _check_same_shape(preds: Tensor, target: Tensor) -> None: + """Check that predictions and target have the same shape, else raise error.""" + if preds.shape != target.shape: + raise RuntimeError( + f"Predictions and targets are expected to have the same shape, but got {preds.shape} and {target.shape}." + ) + + +def _check_retrieval_functional_inputs( + preds: Tensor, + target: Tensor, + allow_non_binary_target: bool = False, +) -> tuple[Tensor, Tensor]: + """Check ``preds`` and ``target`` tensors are of the same shape and of the correct data type. + + Args: + preds: either tensor with scores/logits + target: tensor with ground true labels + allow_non_binary_target: whether to allow target to contain non-binary values + + Raises: + ValueError: + If ``preds`` and ``target`` don't have the same shape, if they are empty + or not of the correct ``dtypes``. + + Returns: + preds: as torch.float32 + target: as torch.long if not floating point else torch.float32 + + """ + if preds.shape != target.shape: + raise ValueError("`preds` and `target` must be of the same shape") + + if not preds.numel() or not preds.size(): + raise ValueError("`preds` and `target` must be non-empty and non-scalar tensors") + + return _check_retrieval_target_and_prediction_types(preds, target, allow_non_binary_target=allow_non_binary_target) + + +def _check_retrieval_inputs( + indexes: Tensor, + preds: Tensor, + target: Tensor, + allow_non_binary_target: bool = False, + ignore_index: Optional[int] = None, +) -> tuple[Tensor, Tensor, Tensor]: + """Check ``indexes``, ``preds`` and ``target`` tensors are of the same shape and of the correct data type. + + Args: + indexes: tensor with queries indexes + preds: tensor with scores/logits + target: tensor with ground true labels + allow_non_binary_target: whether to allow target to contain non-binary values + ignore_index: ignore predictions where targets are equal to this number + + Raises: + ValueError: + If ``preds`` and ``target`` don't have the same shape, if they are empty or not of the correct ``dtypes``. + + Returns: + indexes: as ``torch.long`` + preds: as ``torch.float32`` + target: as ``torch.long`` + + """ + if indexes.shape != preds.shape or preds.shape != target.shape: + raise ValueError("`indexes`, `preds` and `target` must be of the same shape") + + if indexes.dtype is not torch.long: + raise ValueError("`indexes` must be a tensor of long integers") + + # remove predictions where target is equal to `ignore_index` + if ignore_index is not None: + valid_positions = target != ignore_index + indexes, preds, target = indexes[valid_positions], preds[valid_positions], target[valid_positions] + + if not indexes.numel() or not indexes.size(): + raise ValueError( + "`indexes`, `preds` and `target` must be non-empty and non-scalar tensors", + ) + + preds, target = _check_retrieval_target_and_prediction_types( + preds, target, allow_non_binary_target=allow_non_binary_target + ) + + return indexes.long().flatten(), preds, target + + +def _check_retrieval_target_and_prediction_types( + preds: Tensor, + target: Tensor, + allow_non_binary_target: bool = False, +) -> tuple[Tensor, Tensor]: + """Check ``preds`` and ``target`` tensors are of the same shape and of the correct data type. + + Args: + preds: either tensor with scores/logits + target: tensor with ground true labels + allow_non_binary_target: whether to allow target to contain non-binary values + + Raises: + ValueError: + If ``preds`` and ``target`` don't have the same shape, if they are empty or not of the correct ``dtypes``. + + """ + if target.dtype not in (torch.bool, torch.long, torch.int) and not torch.is_floating_point(target): + raise ValueError("`target` must be a tensor of booleans, integers or floats") + + if not preds.is_floating_point(): + raise ValueError("`preds` must be a tensor of floats") + + if not allow_non_binary_target and (target.max() > 1 or target.min() < 0): + raise ValueError("`target` must contain `binary` values") + + target = target.float() if target.is_floating_point() else target.long() + preds = preds.float() + + return preds.flatten(), target.flatten() + + +def _allclose_recursive(res1: Any, res2: Any, atol: float = 1e-6) -> bool: + """Recursively asserting that two results are within a certain tolerance.""" + # single output compare + if isinstance(res1, Tensor): + return torch.allclose(res1, res2, atol=atol) + if isinstance(res1, str): + return res1 == res2 + if isinstance(res1, Sequence): + return all(_allclose_recursive(r1, r2) for r1, r2 in zip(res1, res2)) + if isinstance(res1, Mapping): + return all(_allclose_recursive(res1[k], res2[k]) for k in res1) + return res1 == res2 + + +@no_type_check +def check_forward_full_state_property( + metric_class: Metric, + init_args: Optional[dict[str, Any]] = None, + input_args: Optional[dict[str, Any]] = None, + num_update_to_compare: Sequence[int] = [10, 100, 1000], + reps: int = 5, +) -> None: + """Check if the new ``full_state_update`` property works as intended. + + This function checks if the property can safely be set to ``False`` which will for most metrics results in a + speedup when using ``forward``. + + Args: + metric_class: metric class object that should be checked + init_args: dict containing arguments for initializing the metric class + input_args: dict containing arguments to pass to ``forward`` + num_update_to_compare: if we successfully detect that the flag is safe to set to ``False`` + we will run some speedup test. This arg should be a list of integers for how many + steps to compare over. + reps: number of repetitions of speedup test + + Example (states in ``update`` are independent, save to set ``full_state_update=False``) + >>> from torchmetrics.classification import MulticlassConfusionMatrix + >>> check_forward_full_state_property( # doctest: +SKIP + ... MulticlassConfusionMatrix, + ... init_args = {'num_classes': 3}, + ... input_args = {'preds': torch.randint(3, (100,)), 'target': torch.randint(3, (100,))}, + ... ) + Full state for 10 steps took: ... + Partial state for 10 steps took: ... + Full state for 100 steps took: ... + Partial state for 100 steps took: ... + Full state for 1000 steps took: ... + Partial state for 1000 steps took: ... + Recommended setting `full_state_update=False` + + Example (states in ``update`` are dependent meaning that ``full_state_update=True``): + >>> from torchmetrics.classification import MulticlassConfusionMatrix + >>> class MyMetric(MulticlassConfusionMatrix): + ... def update(self, preds, target): + ... super().update(preds, target) + ... # by construction make future states dependent on prior states + ... if self.confmat.sum() > 20: + ... self.reset() + >>> check_forward_full_state_property( + ... MyMetric, + ... init_args = {'num_classes': 3}, + ... input_args = {'preds': torch.randint(3, (10,)), 'target': torch.randint(3, (10,))}, + ... ) + Recommended setting `full_state_update=True` + + """ + init_args = init_args or {} + input_args = input_args or {} + + class FullState(metric_class): + full_state_update = True + + class PartState(metric_class): + full_state_update = False + + fullstate = FullState(**init_args) + partstate = PartState(**init_args) + + equal = True + try: # if it fails, the code most likely need access to the full state + for _ in range(num_update_to_compare[0]): + equal = equal & _allclose_recursive(fullstate(**input_args), partstate(**input_args)) + except RuntimeError: + equal = False + res1 = fullstate.compute() + try: # if it fails, the code most likely need access to the full state + res2 = partstate.compute() + except RuntimeError: + equal = False + equal = equal & _allclose_recursive(res1, res2) + + if not equal: # we can stop early because the results did not match + print("Recommended setting `full_state_update=True`") + return + + # Do timings + res = torch.zeros(2, len(num_update_to_compare), reps) + for i, metric in enumerate([fullstate, partstate]): + for j, t in enumerate(num_update_to_compare): + for r in range(reps): + start = perf_counter() + for _ in range(t): + _ = metric(**input_args) + end = perf_counter() + res[i, j, r] = end - start + metric.reset() + + mean = torch.mean(res, -1) + std = torch.std(res, -1) + + for t in range(len(num_update_to_compare)): + print(f"Full state for {num_update_to_compare[t]} steps took: {mean[0, t]}+-{std[0, t]:0.3f}") + print(f"Partial state for {num_update_to_compare[t]} steps took: {mean[1, t]:0.3f}+-{std[1, t]:0.3f}") + + faster = (mean[1, -1] < mean[0, -1]).item() # if faster on average, we recommend upgrading + print(f"Recommended setting `full_state_update={not faster}`") + return + + +def is_overridden(method_name: str, instance: object, parent: object) -> bool: + """Check if a method has been overridden by an instance compared to its parent class.""" + instance_attr = getattr(instance, method_name, None) + if instance_attr is None: + return False + # `functools.wraps()` support + if hasattr(instance_attr, "__wrapped__"): + instance_attr = instance_attr.__wrapped__ + # `Mock(wraps=...)` support + if isinstance(instance_attr, Mock): + # access the wrapped function + instance_attr = instance_attr._mock_wraps + # `partial` support + elif isinstance(instance_attr, partial): + instance_attr = instance_attr.func + if instance_attr is None: + return False + + parent_attr = getattr(parent, method_name, None) + if parent_attr is None: + raise ValueError("The parent should define the method") + + return instance_attr.__code__ != parent_attr.__code__ + + +def _try_proceed_with_timeout(fn: Callable, timeout: int = _DOCTEST_DOWNLOAD_TIMEOUT) -> bool: + """Check if a certain function is taking too long to execute. + + Function will only be executed if running inside a doctest context. Currently, does not support Windows. + + Args: + fn: function to check + timeout: timeout for function + + Returns: + Bool indicating if the function finished within the specified timeout + + """ + # source: https://stackoverflow.com/a/14924210/4521646 + if multiprocessing.current_process().daemon: + # Skip timeout check in daemon processes as they cannot spawn child processes. + return True + + proc = multiprocessing.Process(target=fn) + + print(f"Trying to run `{fn.__name__}` for {timeout}s...", file=sys.stderr) + proc.start() + # Wait for N seconds or until process finishes + proc.join(timeout) + # If thread is still active + if not proc.is_alive(): + return True + + print(f"`{fn.__name__}` did not complete with {timeout}, killing process and returning False", file=sys.stderr) + # Terminate - may not work if process is stuck for good + # proc.terminate() + # proc.join() + # OR Kill - will work for sure, no chance for process to finish nicely however + proc.kill() + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/compute.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/compute.py new file mode 100644 index 0000000000000000000000000000000000000000..fe053fccf65639eb12c3e4f6580aff7f04bf62e0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/compute.py @@ -0,0 +1,243 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional, Union + +import torch +from torch import Tensor +from typing_extensions import Literal + +from torchmetrics.utilities import rank_zero_warn + + +def _safe_matmul(x: Tensor, y: Tensor) -> Tensor: + """Safe calculation of matrix multiplication. + + If input is float16, will cast to float32 for computation and back again. + + """ + if x.dtype == torch.float16 or y.dtype == torch.float16: + return (x.float() @ y.T.float()).half() + return x @ y.T + + +def _safe_xlogy(x: Tensor, y: Tensor) -> Tensor: + """Compute x * log(y). Returns 0 if x=0. + + Example: + >>> import torch + >>> x = torch.zeros(1) + >>> _safe_xlogy(x, 1/x) + tensor([0.]) + + """ + res = x * torch.log(y) + res[x == 0] = 0.0 + return res + + +def _safe_divide( + num: Tensor, + denom: Tensor, + zero_division: Union[float, Literal["warn", "nan"]] = 0.0, +) -> Tensor: + """Safe division, by preventing division by zero. + + Function will cast to float if input is not already to secure backwards compatibility. + + Args: + num: numerator tensor + denom: denominator tensor, which may contain zeros + zero_division: value to replace elements divided by zero + + Example: + >>> import torch + >>> num = torch.tensor([1.0, 2.0, 3.0]) + >>> denom = torch.tensor([0.0, 1.0, 2.0]) + >>> _safe_divide(num, denom) + tensor([0.0000, 2.0000, 1.5000]) + + """ + num = num if num.is_floating_point() else num.float() + denom = denom if denom.is_floating_point() else denom.float() + if isinstance(zero_division, (float, int)) or zero_division == "warn": + if zero_division == "warn" and torch.any(denom == 0): + rank_zero_warn("Detected zero division in _safe_divide. Setting 0/0 to 0.0") + zero_division = 0.0 if zero_division == "warn" else zero_division + zero_division_tensor = torch.full((), zero_division, dtype=num.dtype, device=num.device) + return torch.where(denom != 0, num / denom, zero_division_tensor) + return torch.true_divide(num, denom) + + +def _adjust_weights_safe_divide( + score: Tensor, average: Optional[str], multilabel: bool, tp: Tensor, fp: Tensor, fn: Tensor, top_k: int = 1 +) -> Tensor: + if average is None or average == "none": + return score + if average == "weighted": + weights = tp + fn + else: + weights = torch.ones_like(score) + if not multilabel: + weights[tp + fp + fn == 0 if top_k == 1 else tp + fn == 0] = 0.0 + return _safe_divide(weights * score, weights.sum(-1, keepdim=True)).sum(-1) + + +def _auc_format_inputs(x: Tensor, y: Tensor) -> tuple[Tensor, Tensor]: + """Check that auc input is correct.""" + x = x.squeeze() if x.ndim > 1 else x + y = y.squeeze() if y.ndim > 1 else y + + if x.ndim > 1 or y.ndim > 1: + raise ValueError( + f"Expected both `x` and `y` tensor to be 1d, but got tensors with dimension {x.ndim} and {y.ndim}" + ) + if x.numel() != y.numel(): + raise ValueError( + f"Expected the same number of elements in `x` and `y` tensor but received {x.numel()} and {y.numel()}" + ) + return x, y + + +def _auc_compute_without_check(x: Tensor, y: Tensor, direction: float, axis: int = -1) -> Tensor: + """Compute area under the curve using the trapezoidal rule. + + Assumes increasing or decreasing order of `x`. + + """ + with torch.no_grad(): + auc_score: Tensor = torch.trapz(y, x, dim=axis) * direction + return auc_score + + +def _auc_compute(x: Tensor, y: Tensor, reorder: bool = False) -> Tensor: + """Compute area under the curve using the trapezoidal rule. + + Example: + >>> import torch + >>> x = torch.tensor([1, 2, 3, 4]) + >>> y = torch.tensor([1, 2, 3, 4]) + >>> _auc_compute(x, y) + tensor(7.5000) + + """ + with torch.no_grad(): + if reorder: + x, x_idx = torch.sort(x, stable=True) + y = y[x_idx] + + dx = x[1:] - x[:-1] + if (dx < 0).any(): + if (dx <= 0).all(): + direction = -1.0 + else: + raise ValueError( + "The `x` tensor is neither increasing or decreasing. Try setting the reorder argument to `True`." + ) + else: + direction = 1.0 + return _auc_compute_without_check(x, y, direction) + + +def auc(x: Tensor, y: Tensor, reorder: bool = False) -> Tensor: + """Compute Area Under the Curve (AUC) using the trapezoidal rule. + + Args: + x: x-coordinates, must be either increasing or decreasing + y: y-coordinates + reorder: if True, will reorder the arrays to make it either increasing or decreasing + + Return: + Tensor containing AUC score + + """ + x, y = _auc_format_inputs(x, y) + return _auc_compute(x, y, reorder=reorder) + + +def interp(x: Tensor, xp: Tensor, fp: Tensor) -> Tensor: + """One-dimensional linear interpolation for monotonically increasing sample points. + + Returns the one-dimensional piecewise linear interpolation to a function with + given discrete data points :math:`(xp, fp)`, evaluated at :math:`x`. + + Adjusted version of this https://github.com/pytorch/pytorch/issues/50334#issuecomment-1000917964 + + Args: + x: the :math:`x`-coordinates at which to evaluate the interpolated values. + xp: the :math:`x`-coordinates of the data points, must be increasing. + fp: the :math:`y`-coordinates of the data points, same length as `xp`. + + Returns: + the interpolated values, same size as `x`. + + Example: + >>> x = torch.tensor([0.5, 1.5, 2.5]) + >>> xp = torch.tensor([1, 2, 3]) + >>> fp = torch.tensor([1, 2, 3]) + >>> interp(x, xp, fp) + tensor([0.5000, 1.5000, 2.5000]) + + """ + m = _safe_divide(fp[1:] - fp[:-1], xp[1:] - xp[:-1]) + b = fp[:-1] - (m * xp[:-1]) + + indices = torch.sum(torch.ge(x[:, None], xp[None, :]), 1) - 1 + indices = torch.clamp(indices, 0, len(m) - 1) + + return m[indices] * x + b[indices] + + +def normalize_logits_if_needed(tensor: Tensor, normalization: Optional[Literal["sigmoid", "softmax"]]) -> Tensor: + """Normalize logits if needed. + + If input tensor is outside the [0,1] we assume that logits are provided and apply the normalization. + Use torch.where to prevent device-host sync. + + Args: + tensor: input tensor that may be logits or probabilities + normalization: normalization method, either 'sigmoid' or 'softmax' + + Returns: + normalized tensor if needed + + Example: + >>> import torch + >>> tensor = torch.tensor([-1.0, 0.0, 1.0]) + >>> normalize_logits_if_needed(tensor, normalization="sigmoid") + tensor([0.2689, 0.5000, 0.7311]) + >>> tensor = torch.tensor([[-1.0, 0.0, 1.0], [1.0, 0.0, -1.0]]) + >>> normalize_logits_if_needed(tensor, normalization="softmax") + tensor([[0.0900, 0.2447, 0.6652], + [0.6652, 0.2447, 0.0900]]) + >>> tensor = torch.tensor([0.0, 0.5, 1.0]) + >>> normalize_logits_if_needed(tensor, normalization="sigmoid") + tensor([0.0000, 0.5000, 1.0000]) + + """ + # if not specified, do nothing. + if not normalization: + return tensor + # decrease sigmoid on cpu . + if tensor.device == torch.device("cpu"): + if not torch.all((tensor >= 0) * (tensor <= 1)): + tensor = tensor.sigmoid() if normalization == "sigmoid" else torch.softmax(tensor, dim=1) + return tensor + + # decrease device-host sync on device . + condition = ((tensor < 0) | (tensor > 1)).any() + return torch.where( + condition, + torch.sigmoid(tensor) if normalization == "sigmoid" else torch.softmax(tensor, dim=1), + tensor, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/data.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/data.py new file mode 100644 index 0000000000000000000000000000000000000000..f6cab1878525106c3f8b56ef65cf3851e327c45d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/data.py @@ -0,0 +1,266 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import sys +from collections.abc import Sequence +from typing import Any, List, Optional, Union + +import torch +from lightning_utilities import apply_to_collection +from torch import Tensor + +from torchmetrics.utilities.exceptions import TorchMetricsUserWarning +from torchmetrics.utilities.imports import _TORCH_LESS_THAN_2_6, _XLA_AVAILABLE +from torchmetrics.utilities.prints import rank_zero_warn + +METRIC_EPS = 1e-6 + + +def dim_zero_cat(x: Union[Tensor, List[Tensor]]) -> Tensor: + """Concatenation along the zero dimension.""" + if isinstance(x, torch.Tensor): + return x + x = [y.unsqueeze(0) if y.numel() == 1 and y.ndim == 0 else y for y in x] + if not x: # empty list + raise ValueError("No samples to concatenate") + return torch.cat(x, dim=0) + + +def dim_zero_sum(x: Tensor) -> Tensor: + """Summation along the zero dimension.""" + return torch.sum(x, dim=0) + + +def dim_zero_mean(x: Tensor) -> Tensor: + """Average along the zero dimension.""" + return torch.mean(x, dim=0) + + +def dim_zero_max(x: Tensor) -> Tensor: + """Max along the zero dimension.""" + return torch.max(x, dim=0).values + + +def dim_zero_min(x: Tensor) -> Tensor: + """Min along the zero dimension.""" + return torch.min(x, dim=0).values + + +def _flatten(x: Sequence) -> list: + """Flatten list of list into single list.""" + return [item for sublist in x for item in sublist] + + +def _flatten_dict(x: dict) -> tuple[dict, bool]: + """Flatten dict of dicts into single dict and checking for duplicates in keys along the way.""" + new_dict = {} + duplicates = False + for key, value in x.items(): + if isinstance(value, dict): + for k, v in value.items(): + if k in new_dict: + duplicates = True + new_dict[k] = v + else: + if key in new_dict: + duplicates = True + new_dict[key] = value + return new_dict, duplicates + + +def to_onehot( + label_tensor: Tensor, + num_classes: Optional[int] = None, +) -> Tensor: + """Convert a dense label tensor to one-hot format. + + Args: + label_tensor: dense label tensor, with shape [N, d1, d2, ...] + num_classes: number of classes C + + Returns: + A sparse label tensor with shape [N, C, d1, d2, ...] + + Example: + >>> x = torch.tensor([1, 2, 3]) + >>> to_onehot(x) + tensor([[0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1]]) + + """ + if num_classes is None: + num_classes = int(label_tensor.max().detach().item() + 1) + + tensor_onehot = torch.zeros( + label_tensor.shape[0], + num_classes, + *label_tensor.shape[1:], + dtype=label_tensor.dtype, + device=label_tensor.device, + ) + index = label_tensor.long().unsqueeze(1).expand_as(tensor_onehot) + return tensor_onehot.scatter_(1, index, 1.0) + + +def _top_k_with_half_precision_support(x: Tensor, k: int = 1, dim: int = 1) -> Tensor: + """torch.top_k does not support half precision on CPU.""" + if x.dtype == torch.half and not x.is_cuda: + idx = torch.argsort(x, dim=dim, stable=True).flip(dim) + return idx.narrow(dim, 0, k) + return x.topk(k=k, dim=dim).indices + + +def select_topk(prob_tensor: Tensor, topk: int = 1, dim: int = 1) -> Tensor: + """Convert a probability tensor to binary by selecting top-k the highest entries. + + Args: + prob_tensor: dense tensor of shape ``[..., C, ...]``, where ``C`` is in the + position defined by the ``dim`` argument + topk: number of the highest entries to turn into 1s + dim: dimension on which to compare entries + + Returns: + A binary tensor of the same shape as the input tensor of type ``torch.int32`` + + Example: + >>> x = torch.tensor([[1.1, 2.0, 3.0], [2.0, 1.0, 0.5]]) + >>> select_topk(x, topk=2) + tensor([[0, 1, 1], + [1, 1, 0]], dtype=torch.int32) + + """ + topk_tensor = torch.zeros_like(prob_tensor, dtype=torch.int) + if topk == 1: # argmax has better performance than topk + topk_tensor.scatter_(dim, prob_tensor.argmax(dim=dim, keepdim=True), 1.0) + else: + topk_tensor.scatter_(dim, _top_k_with_half_precision_support(prob_tensor, k=topk, dim=dim), 1.0) + return topk_tensor.int() + + +def to_categorical(x: Tensor, argmax_dim: int = 1) -> Tensor: + """Convert a tensor of probabilities to a dense label tensor. + + Args: + x: probabilities to get the categorical label [N, d1, d2, ...] + argmax_dim: dimension to apply + + Return: + A tensor with categorical labels [N, d2, ...] + + Example: + >>> x = torch.tensor([[0.2, 0.5], [0.9, 0.1]]) + >>> to_categorical(x) + tensor([1, 0]) + + """ + return torch.argmax(x, dim=argmax_dim) + + +def _squeeze_scalar_element_tensor(x: Tensor) -> Tensor: + return x.squeeze() if x.numel() == 1 else x + + +def _squeeze_if_scalar(data: Any) -> Any: + return apply_to_collection(data, Tensor, _squeeze_scalar_element_tensor) + + +def _bincount(x: Tensor, minlength: Optional[int] = None) -> Tensor: + """Implement custom bincount. + + PyTorch currently does not support ``torch.bincount`` when running in deterministic mode on GPU or when running + MPS devices or when running on XLA device. This implementation therefore falls back to using a combination of + `torch.arange` and `torch.eq` in these scenarios. A small performance hit can expected and higher memory consumption + as `[batch_size, mincount]` tensor needs to be initialized compared to native ``torch.bincount``. + + Args: + x: tensor to count + minlength: minimum length to count + + Returns: + Number of occurrences for each unique element in x + + Example: + >>> x = torch.tensor([0,0,0,1,1,2,2,2,2]) + >>> _bincount(x, minlength=3) + tensor([3, 2, 4]) + + """ + if minlength is None: + minlength = len(torch.unique(x)) + + if torch.are_deterministic_algorithms_enabled() or _XLA_AVAILABLE or x.is_mps: + mesh = torch.arange(minlength, device=x.device).repeat(len(x), 1) + return torch.eq(x.reshape(-1, 1), mesh).sum(dim=0) + + return torch.bincount(x, minlength=minlength) + + +def _cumsum(x: Tensor, dim: Optional[int] = 0, dtype: Optional[torch.dtype] = None) -> Tensor: + """Implement custom cumulative summation for Torch versions which does not support it natively.""" + is_cuda_fp_deterministic = torch.are_deterministic_algorithms_enabled() and x.is_cuda and x.is_floating_point() + if _TORCH_LESS_THAN_2_6 and is_cuda_fp_deterministic and sys.platform != "win32": + rank_zero_warn( + "You are trying to use a metric in deterministic mode on GPU that uses `torch.cumsum`, which is currently" + " not supported. The tensor will be copied to the CPU memory to compute it and then copied back to GPU." + " Expect some slowdowns.", + TorchMetricsUserWarning, + ) + return x.cpu().cumsum(dim=dim, dtype=dtype).to(x.device) + return torch.cumsum(x, dim=dim, dtype=dtype) + + +def _flexible_bincount(x: Tensor) -> Tensor: + """Similar to `_bincount`, but works also with tensor that do not contain continuous values. + + Args: + x: tensor to count + + Returns: + Number of occurrences for each unique element in x + + """ + unique_x, inverse_indices = torch.unique(x, return_inverse=True) + return _bincount(inverse_indices, minlength=len(unique_x)) + + +def allclose(tensor1: Tensor, tensor2: Tensor) -> bool: + """Wrap torch.allclose to be robust towards dtype difference.""" + if tensor1.dtype != tensor2.dtype: + tensor2 = tensor2.to(dtype=tensor1.dtype) + return torch.allclose(tensor1, tensor2) + + +def interp(x: Tensor, xp: Tensor, fp: Tensor) -> Tensor: + """Interpolation function comparable to numpy.interp. + + Args: + x: x-coordinates where to evaluate the interpolated values + xp: x-coordinates of the data points + fp: y-coordinates of the data points + + """ + # Sort xp and fp based on xp for compatibility with np.interp + sorted_indices = torch.argsort(xp) + xp = xp[sorted_indices] + fp = fp[sorted_indices] + + # Calculate slopes for each interval + slopes = (fp[1:] - fp[:-1]) / (xp[1:] - xp[:-1]) + + # Identify where x falls relative to xp + indices = torch.searchsorted(xp, x) - 1 + indices = torch.clamp(indices, 0, len(slopes) - 1) + + # Compute interpolated values + return fp[indices] + slopes[indices] * (x - xp[indices]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/distributed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ae2a04f70764302c4c46a4aa23f8ff6ccf6927 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/distributed.py @@ -0,0 +1,153 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, List, Optional + +import torch +from torch import Tensor +from torch.nn import functional as F # noqa: N812 +from typing_extensions import Literal + + +def reduce(x: Tensor, reduction: Optional[Literal["elementwise_mean", "sum", "none"]]) -> Tensor: + """Reduces a given tensor by a given reduction method. + + Args: + x: the tensor, which shall be reduced + reduction: a string specifying the reduction method ('elementwise_mean', 'none', 'sum') + + Return: + reduced Tensor + + Raise: + ValueError if an invalid reduction parameter was given + + """ + if reduction == "elementwise_mean": + return torch.mean(x) + if reduction == "none" or reduction is None: + return x + if reduction == "sum": + return torch.sum(x) + raise ValueError("Reduction parameter unknown.") + + +def class_reduce( + num: Tensor, + denom: Tensor, + weights: Tensor, + class_reduction: Optional[Literal["micro", "macro", "weighted", "none"]] = "none", +) -> Tensor: + """Reduce classification metrics of the form ``num / denom * weights``. + + For example for calculating standard accuracy the num would be number of true positives per class, denom would be + the support per class, and weights would be a tensor of 1s. + + Args: + num: numerator tensor + denom: denominator tensor + weights: weights for each class + class_reduction: reduction method for multiclass problems: + + - ``'micro'``: calculate metrics globally (default) + - ``'macro'``: calculate metrics for each label, and find their unweighted mean. + - ``'weighted'``: calculate metrics for each label, and find their weighted mean. + - ``'none'`` or ``None``: returns calculated metric per class + + Raises: + ValueError: + If ``class_reduction`` is none of ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"`` or ``None``. + + """ + valid_reduction = ("micro", "macro", "weighted", "none", None) + fraction = torch.sum(num) / torch.sum(denom) if class_reduction == "micro" else num / denom + + # We need to take care of instances where the denom can be 0 + # for some (or all) classes which will produce nans + fraction[fraction != fraction] = 0 + + if class_reduction == "micro": + return fraction + if class_reduction == "macro": + return torch.mean(fraction) + if class_reduction == "weighted": + return torch.sum(fraction * (weights.float() / torch.sum(weights))) + if class_reduction == "none" or class_reduction is None: + return fraction + + raise ValueError(f"Reduction parameter {class_reduction} unknown. Choose between one of these: {valid_reduction}") + + +def _simple_gather_all_tensors(result: Tensor, group: Any, world_size: int) -> List[Tensor]: + with torch.no_grad(): + gathered_result = [torch.zeros_like(result) for _ in range(world_size)] + torch.distributed.all_gather(gathered_result, result, group) + # to propagate autograd graph from local rank + gathered_result[torch.distributed.get_rank(group)] = result + return gathered_result + + +def gather_all_tensors(result: Tensor, group: Optional[Any] = None) -> List[Tensor]: + """Gather all tensors from several ddp processes onto a list that is broadcast to all processes. + + Works on tensors that have the same number of dimensions, but where each dimension may differ. In this case + tensors are padded, gathered and then trimmed to secure equal workload for all processes. + + Args: + result: the value to sync + group: the process group to gather results from. Defaults to all processes (world) + + Return: + list with size equal to the process group where element i corresponds to result tensor from process i + + """ + if group is None: + group = torch.distributed.group.WORLD + + # convert tensors to contiguous format + result = result.contiguous() + + world_size = torch.distributed.get_world_size(group) + torch.distributed.barrier(group=group) + + # if the tensor is scalar, things are easy + if result.ndim == 0: + return _simple_gather_all_tensors(result, group, world_size) + + # 1. Gather sizes of all tensors + local_size = torch.tensor(result.shape, device=result.device) + local_sizes = [torch.zeros_like(local_size) for _ in range(world_size)] + torch.distributed.all_gather(local_sizes, local_size, group=group) + max_size = torch.stack(local_sizes).max(dim=0).values + all_sizes_equal = all(all(ls == max_size) for ls in local_sizes) + + # 2. If shapes are all the same, then do a simple gather: + if all_sizes_equal: + return _simple_gather_all_tensors(result, group, world_size) + + # 3. If not, we need to pad each local tensor to maximum size, gather and then truncate + with torch.no_grad(): + pad_dims = [] + pad_by = (max_size - local_size).detach().cpu() + for val in reversed(pad_by): + pad_dims.append(0) + pad_dims.append(val.item()) + result_padded = F.pad(result, pad_dims) + gathered_result = [torch.zeros_like(result_padded) for _ in range(world_size)] + torch.distributed.all_gather(gathered_result, result_padded, group) + for idx, item_size in enumerate(local_sizes): + slice_param = [slice(dim_size) for dim_size in item_size] + gathered_result[idx] = gathered_result[idx][tuple(slice_param)] + # to propagate autograd graph from local rank + gathered_result[torch.distributed.get_rank(group)] = result + return gathered_result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/enums.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..155f1bb8f608480d4e4403a624b89a8d52d0372f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/enums.py @@ -0,0 +1,153 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from lightning_utilities.core.enums import StrEnum +from typing_extensions import Literal + + +class EnumStr(StrEnum): + """Base Enum.""" + + @staticmethod + def _name() -> str: + return "Task" + + @classmethod + def from_str(cls: type["EnumStr"], value: str, source: Literal["key", "value", "any"] = "key") -> "EnumStr": + """Load from string. + + Raises: + ValueError: + If required value is not among the supported options. + + >>> class MyEnum(EnumStr): + ... a = "aaa" + ... b = "bbb" + >>> MyEnum.from_str("a") + + >>> MyEnum.from_str("c") + Traceback (most recent call last): + ... + ValueError: Invalid Task: expected one of ['a', 'b'], but got c. + + """ + try: + me = super().from_str(value.replace("-", "_"), source=source) + except ValueError as err: + _allowed_im = [m.lower() for m in cls._member_names_] + raise ValueError( + f"Invalid {cls._name()}: expected one of {cls._allowed_matches(source)}, but got {value}." + ) from err + return cls(me) + + +class DataType(EnumStr): + """Enum to represent data type. + + >>> "Binary" in list(DataType) + True + + """ + + @staticmethod + def _name() -> str: + return "Data type" + + BINARY = "binary" + MULTILABEL = "multi-label" + MULTICLASS = "multi-class" + MULTIDIM_MULTICLASS = "multi-dim multi-class" + + +class AverageMethod(EnumStr): + """Enum to represent average method. + + >>> None in list(AverageMethod) + True + >>> AverageMethod.NONE == None + True + >>> AverageMethod.NONE == 'none' + True + + """ + + @staticmethod + def _name() -> str: + return "Average method" + + MICRO = "micro" + MACRO = "macro" + WEIGHTED = "weighted" + NONE = None + SAMPLES = "samples" + + +class MDMCAverageMethod(EnumStr): + """Enum to represent multi-dim multi-class average method.""" + + @staticmethod + def _name() -> str: + return "MDMC Average method" + + GLOBAL = "global" + SAMPLEWISE = "samplewise" + + +class ClassificationTask(EnumStr): + """Enum to represent the different tasks in classification metrics. + + >>> "binary" in list(ClassificationTask) + True + + """ + + @staticmethod + def _name() -> str: + return "Classification" + + BINARY = "binary" + MULTICLASS = "multiclass" + MULTILABEL = "multilabel" + + +class ClassificationTaskNoBinary(EnumStr): + """Enum to represent the different tasks in classification metrics. + + >>> "binary" in list(ClassificationTaskNoBinary) + False + + """ + + @staticmethod + def _name() -> str: + return "Classification" + + MULTILABEL = "multilabel" + MULTICLASS = "multiclass" + + +class ClassificationTaskNoMultilabel(EnumStr): + """Enum to represent the different tasks in classification metrics. + + >>> "multilabel" in list(ClassificationTaskNoMultilabel) + False + + """ + + @staticmethod + def _name() -> str: + return "Classification" + + BINARY = "binary" + MULTICLASS = "multiclass" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/exceptions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..38d48fc81f49e722595dac08942b164cbb324930 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/exceptions.py @@ -0,0 +1,21 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +class TorchMetricsUserError(Exception): + """Error used to inform users of a wrong combination of Metric API calls.""" + + +class TorchMetricsUserWarning(Warning): + """Error used to inform users of specific warnings due to the torchmetrics API.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/imports.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..88da9076269900eb4be469043770a413efef85c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/imports.py @@ -0,0 +1,69 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Import utilities.""" + +import shutil +import sys + +from lightning_utilities.core.imports import RequirementCache + +_PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" +_TORCH_GREATER_EQUAL_2_1 = RequirementCache("torch>=2.1.0") +_TORCH_GREATER_EQUAL_2_2 = RequirementCache("torch>=2.2.0") +_TORCH_GREATER_EQUAL_2_3 = RequirementCache("torch>=2.3.0") +_TORCH_GREATER_EQUAL_2_5 = RequirementCache("torch>=2.5.0") +_TORCH_LESS_THAN_2_6 = RequirementCache("torch<2.6.0") +_TORCHMETRICS_GREATER_EQUAL_1_6 = RequirementCache("torchmetrics>=1.7.0") + +_NLTK_AVAILABLE = RequirementCache("nltk") +_ROUGE_SCORE_AVAILABLE = RequirementCache("rouge_score") +_BERTSCORE_AVAILABLE = RequirementCache("bert_score") +_SCIPY_AVAILABLE = RequirementCache("scipy") +_SCIPY_GREATER_EQUAL_1_8 = RequirementCache("scipy>=1.8.0") +_TORCH_FIDELITY_AVAILABLE = RequirementCache("torch_fidelity") +_LPIPS_AVAILABLE = RequirementCache("lpips") +_PYCOCOTOOLS_AVAILABLE = RequirementCache("pycocotools") +_PYCOCOTOOLS_GREATER_EQUAL_2_0_9 = RequirementCache("pycocotools>=2.0.9") +_TORCHVISION_AVAILABLE = RequirementCache("torchvision") +_TQDM_AVAILABLE = RequirementCache("tqdm") +_TRANSFORMERS_AVAILABLE = RequirementCache("transformers") +_TRANSFORMERS_GREATER_EQUAL_4_4 = RequirementCache("transformers>=4.4.0") +_TRANSFORMERS_GREATER_EQUAL_4_10 = RequirementCache("transformers>=4.10.0") +_PESQ_AVAILABLE = RequirementCache("pesq") +_GAMMATONE_AVAILABLE = RequirementCache("gammatone") +_TORCHAUDIO_AVAILABLE = RequirementCache("torchaudio") +_REGEX_AVAILABLE = RequirementCache("regex") +_PYSTOI_AVAILABLE = RequirementCache("pystoi") +_REQUESTS_AVAILABLE = RequirementCache("requests") +_LIBROSA_AVAILABLE = RequirementCache("librosa") +_ONNXRUNTIME_AVAILABLE = RequirementCache("onnxruntime") +_FAST_BSS_EVAL_AVAILABLE = RequirementCache("fast_bss_eval") +_MATPLOTLIB_AVAILABLE = RequirementCache("matplotlib") +_SCIENCEPLOT_AVAILABLE = RequirementCache("scienceplots") +_MULTIPROCESSING_AVAILABLE = RequirementCache("multiprocessing") +_XLA_AVAILABLE = RequirementCache("torch_xla") +_PIQ_GREATER_EQUAL_0_8 = RequirementCache("piq>=0.8.0") +_FASTER_COCO_EVAL_AVAILABLE = RequirementCache("faster_coco_eval") +_MECAB_AVAILABLE = RequirementCache("MeCab") +_MECAB_KO_AVAILABLE = RequirementCache("mecab_ko") +_MECAB_KO_DIC_AVAILABLE = RequirementCache("mecab_ko_dic") +_IPADIC_AVAILABLE = RequirementCache("ipadic") +_SENTENCEPIECE_AVAILABLE = RequirementCache("sentencepiece") +_SCIPI_AVAILABLE = RequirementCache("scipy") +_TORCH_LINEAR_ASSIGNMENT_AVAILABLE = RequirementCache("torch_linear_assignment") +_AEON_AVAILABLE = RequirementCache("aeon") +_PYTDC_AVAILABLE = RequirementCache("pyTDC") +_TORCH_VMAF_AVAILABLE = RequirementCache("vmaf_torch") +_EINOPS_AVAILABLE = RequirementCache("einops") +_LATEX_AVAILABLE: bool = shutil.which("latex") is not None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/plot.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/plot.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f8f373c7b9a818c403dd7f51862a90c07cb661 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/plot.py @@ -0,0 +1,366 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Generator, Sequence +from itertools import product +from math import ceil, floor, sqrt +from typing import Any, List, Optional, Union, no_type_check + +import numpy as np +import torch +from torch import Tensor + +from torchmetrics.utilities.imports import _LATEX_AVAILABLE, _MATPLOTLIB_AVAILABLE, _SCIENCEPLOT_AVAILABLE + +if _MATPLOTLIB_AVAILABLE: + import matplotlib + import matplotlib.axes + import matplotlib.pyplot as plt + + _PLOT_OUT_TYPE = tuple[plt.Figure, Union[matplotlib.axes.Axes, np.ndarray]] + _AX_TYPE = matplotlib.axes.Axes + _CMAP_TYPE = Union[matplotlib.colors.Colormap, str] + + style_change = plt.style.context +else: + _PLOT_OUT_TYPE = tuple[object, object] # type: ignore[misc] + _AX_TYPE = object + _CMAP_TYPE = object # type: ignore[misc] + + from contextlib import contextmanager + + @contextmanager + def style_change(*args: Any, **kwargs: Any) -> Generator: + """No-ops decorator if matplotlib is not installed.""" + yield + + +if _SCIENCEPLOT_AVAILABLE: + import scienceplots # noqa: F401 + + _style = ["science", "no-latex"] + +_style = ["science"] if _SCIENCEPLOT_AVAILABLE and _LATEX_AVAILABLE else ["default"] + + +def _error_on_missing_matplotlib() -> None: + """Raise error if matplotlib is not installed.""" + if not _MATPLOTLIB_AVAILABLE: + raise ModuleNotFoundError( + "Plot function expects `matplotlib` to be installed. Please install with `pip install matplotlib`" + ) + + +@style_change(_style) +def plot_single_or_multi_val( + val: Union[Tensor, Sequence[Tensor], dict[str, Tensor], Sequence[dict[str, Tensor]]], + ax: Optional[_AX_TYPE] = None, # type: ignore[valid-type] + higher_is_better: Optional[bool] = None, + lower_bound: Optional[float] = None, + upper_bound: Optional[float] = None, + legend_name: Optional[str] = None, + name: Optional[str] = None, +) -> _PLOT_OUT_TYPE: + """Plot a single metric value or multiple, including bounds of value if existing. + + Args: + val: A single tensor with one or multiple values (multiclass/label/output format) or a list of such tensors. + If a list is provided the values are interpreted as a time series of evolving values. + ax: Axis from a figure. + higher_is_better: Indicates if a label indicating where the optimal value it should be added to the figure + lower_bound: lower value that the metric can take + upper_bound: upper value that the metric can take + legend_name: for class based metrics specify the legend prefix e.g. Class or Label to use when multiple values + are provided + name: Name of the metric to use for the y-axis label + + Returns: + A tuple consisting of the figure and respective ax objects of the generated figure + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + """ + _error_on_missing_matplotlib() + fig, ax = plt.subplots() if ax is None else (None, ax) + ax.get_xaxis().set_visible(False) + + if isinstance(val, Tensor): + if val.numel() == 1: + ax.plot([val.detach().cpu()], marker="o", markersize=10) + else: + for i, v in enumerate(val): + label = f"{legend_name} {i}" if legend_name else f"{i}" + ax.plot(i, v.detach().cpu(), marker="o", markersize=10, linestyle="None", label=label) + elif isinstance(val, dict): + for i, (k, v) in enumerate(val.items()): + if v.numel() != 1: + ax.plot(v.detach().cpu(), marker="o", markersize=10, linestyle="-", label=k) + ax.get_xaxis().set_visible(True) + ax.set_xlabel("Step") + ax.set_xticks(torch.arange(len(v))) + else: + ax.plot(i, v.detach().cpu(), marker="o", markersize=10, label=k) + elif isinstance(val, Sequence): + n_steps = len(val) + if isinstance(val[0], dict): + val = {k: torch.stack([val[i][k] for i in range(n_steps)]) for k in val[0]} # type: ignore + for k, v in val.items(): + ax.plot(v.detach().cpu(), marker="o", markersize=10, linestyle="-", label=k) + else: + val = torch.stack(val, 0) # type: ignore + multi_series = val.ndim != 1 + val = val.T if multi_series else val.unsqueeze(0) + for i, v in enumerate(val): + label = (f"{legend_name} {i}" if legend_name else f"{i}") if multi_series else "" + ax.plot(v.detach().cpu(), marker="o", markersize=10, linestyle="-", label=label) + ax.get_xaxis().set_visible(True) + ax.set_xlabel("Step") + ax.set_xticks(torch.arange(n_steps)) + else: + raise ValueError("Got unknown format for argument `val`.") + + handles, labels = ax.get_legend_handles_labels() + if handles and labels: + ax.legend(handles, labels, loc="upper center", bbox_to_anchor=(0.5, 1.15), ncol=3, fancybox=True, shadow=True) + + ylim = ax.get_ylim() + if lower_bound is not None and upper_bound is not None: + factor = 0.1 * (upper_bound - lower_bound) + else: + factor = 0.1 * (ylim[1] - ylim[0]) + + ax.set_ylim( + bottom=lower_bound - factor if lower_bound is not None else ylim[0] - factor, + top=upper_bound + factor if upper_bound is not None else ylim[1] + factor, + ) + + ax.grid(True) + ax.set_ylabel(name if name is not None else None) + + xlim = ax.get_xlim() + factor = 0.1 * (xlim[1] - xlim[0]) + + y_lines = [] + if lower_bound is not None: + y_lines.append(lower_bound) + if upper_bound is not None: + y_lines.append(upper_bound) + ax.hlines(y_lines, xlim[0], xlim[1], linestyles="dashed", colors="k") + if higher_is_better is not None: + if lower_bound is not None and not higher_is_better: + ax.set_xlim(xlim[0] - factor, xlim[1]) + ax.text( + xlim[0], lower_bound, s="Optimal \n value", horizontalalignment="center", verticalalignment="center" + ) + if upper_bound is not None and higher_is_better: + ax.set_xlim(xlim[0] - factor, xlim[1]) + ax.text( + xlim[0], upper_bound, s="Optimal \n value", horizontalalignment="center", verticalalignment="center" + ) + return fig, ax + + +def _get_col_row_split(n: int) -> tuple[int, int]: + """Split `n` figures into `rows` x `cols` figures.""" + nsq = sqrt(n) + if int(nsq) == nsq: # square number + return int(nsq), int(nsq) + if floor(nsq) * ceil(nsq) >= n: + return floor(nsq), ceil(nsq) + return ceil(nsq), ceil(nsq) + + +def _get_text_color(patch_color: tuple[float, float, float, float]) -> str: + """Get the text color for a given value and colormap. + + Following Wikipedia's recommendations: https://en.wikipedia.org/wiki/Relative_luminance. + + Args: + patch_color: RGBA color tuple + + """ + # Convert to linear color space + r, g, b, a = patch_color + r, g, b = (c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in (r, g, b)) + + # Get the relative luminance + y = 0.2126 * r + 0.7152 * g + 0.0722 * b + + return ".1" if y > 0.4 else "white" + + +def trim_axs(axs: Union[_AX_TYPE, np.ndarray], nb: int) -> Union[np.ndarray, _AX_TYPE]: # type: ignore[valid-type] + """Reduce `axs` to `nb` Axes. + + All further Axes are removed from the figure. + + """ + if isinstance(axs, _AX_TYPE): + return axs + + axs = axs.flat # type: ignore[union-attr] + for ax in axs[nb:]: + ax.remove() + return axs[:nb] + + +@style_change(_style) +@no_type_check +def plot_confusion_matrix( + confmat: Tensor, + ax: Optional[_AX_TYPE] = None, + add_text: bool = True, + labels: Optional[list[Union[int, str]]] = None, + cmap: Optional[_CMAP_TYPE] = None, +) -> _PLOT_OUT_TYPE: + """Plot an confusion matrix. + + Inspired by: https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/metrics/_plot/confusion_matrix.py. + Works for both binary, multiclass and multilabel confusion matrices. + + Args: + confmat: the confusion matrix. Either should be an [N,N] matrix in the binary and multiclass cases or an + [N, 2, 2] matrix for multilabel classification + ax: Axis from a figure. If not provided, a new figure and axis will be created + add_text: if text should be added to each cell with the given value + labels: labels to add the x- and y-axis + cmap: matplotlib colormap to use for the confusion matrix + https://matplotlib.org/stable/users/explain/colors/colormaps.html + + Returns: + A tuple consisting of the figure and respective ax objects (or array of ax objects) of the generated figure + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + """ + _error_on_missing_matplotlib() + + if confmat.ndim == 3: # multilabel + nb, n_classes = confmat.shape[0], 2 + rows, cols = _get_col_row_split(nb) + else: + nb, n_classes, rows, cols = 1, confmat.shape[0], 1, 1 + + if labels is not None and confmat.ndim != 3 and len(labels) != n_classes: + raise ValueError( + "Expected number of elements in arg `labels` to match number of labels in confmat but " + f"got {len(labels)} and {n_classes}" + ) + if confmat.ndim == 3: + fig_label = labels or np.arange(nb) + labels = list(map(str, range(n_classes))) + else: + fig_label = None + labels = labels or np.arange(n_classes).tolist() + + fig, axs = plt.subplots(nrows=rows, ncols=cols, constrained_layout=True) if ax is None else (ax.get_figure(), ax) + axs = trim_axs(axs, nb) + for i in range(nb): + ax = axs[i] if (rows != 1 or cols != 1) else axs + if fig_label is not None: + ax.set_title(f"Label {fig_label[i]}", fontsize=15) + im = ax.imshow(confmat[i].cpu().detach() if confmat.ndim == 3 else confmat.cpu().detach(), cmap=cmap) + if i // cols == rows - 1: # bottom row only + ax.set_xlabel("Predicted class", fontsize=15) + if i % cols == 0: # leftmost column only + ax.set_ylabel("True class", fontsize=15) + ax.set_xticks(list(range(n_classes))) + ax.set_yticks(list(range(n_classes))) + ax.set_xticklabels(labels, rotation=45, fontsize=10) + ax.set_yticklabels(labels, rotation=25, fontsize=10) + + if add_text: + for ii, jj in product(range(n_classes), range(n_classes)): + val = confmat[i, ii, jj] if confmat.ndim == 3 else confmat[ii, jj] + patch_color = im.cmap(im.norm(val.item())) + c = _get_text_color(patch_color) + ax.text(jj, ii, str(round(val.item(), 2)), ha="center", va="center", fontsize=15, color=c) + + return fig, axs + + +@style_change(_style) +def plot_curve( + curve: Union[tuple[Tensor, Tensor, Tensor], tuple[List[Tensor], List[Tensor], List[Tensor]]], + score: Optional[Tensor] = None, + ax: Optional[_AX_TYPE] = None, # type: ignore[valid-type] + label_names: Optional[tuple[str, str]] = None, + legend_name: Optional[str] = None, + name: Optional[str] = None, + labels: Optional[list[Union[int, str]]] = None, +) -> _PLOT_OUT_TYPE: + """Inspired by: https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/metrics/_plot/roc_curve.py. + + Plots a curve object + + Args: + curve: a tuple of (x, y, t) where x and y are the coordinates of the curve and t are the thresholds used + to compute the curve + score: optional area under the curve added as label to the plot + ax: Axis from a figure + label_names: Tuple containing the names of the x and y axis + legend_name: Name of the curve to be used in the legend + name: Custom name to describe the metric + labels: Optional labels for the different curves that will be added to the plot + + Returns: + A tuple consisting of the figure and respective ax objects (or array of ax objects) of the generated figure + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + ValueError: + If `curve` does not have 3 elements, being in the wrong format + """ + if len(curve) < 2: + raise ValueError(f"Expected 2 or 3 elements in curve but got {len(curve)}") + x, y = curve[:2] + + _error_on_missing_matplotlib() + fig, ax = plt.subplots() if ax is None else (None, ax) + + if isinstance(x, Tensor) and isinstance(y, Tensor) and x.ndim == 1 and y.ndim == 1: + label = f"AUC={score.item():0.3f}" if score is not None else None + ax.plot(x.detach().cpu(), y.detach().cpu(), linestyle="-", linewidth=2, label=label) + if label is not None: + ax.legend() + elif (isinstance(x, list) and isinstance(y, list)) or ( + isinstance(x, Tensor) and isinstance(y, Tensor) and x.ndim == 2 and y.ndim == 2 + ): + n_classes = len(x) + if labels is not None and len(labels) != n_classes: + raise ValueError( + "Expected number of elements in arg `labels` to match number of labels in roc curves but " + f"got {len(labels)} and {n_classes}" + ) + + for i, (x_, y_) in enumerate(zip(x, y)): + label = f"{legend_name}_{i}" if legend_name is not None else str(i) if labels is None else str(labels[i]) + label += f" AUC={score[i].item():0.3f}" if score is not None else "" + ax.plot(x_.detach().cpu(), y_.detach().cpu(), linestyle="-", linewidth=2, label=label) + ax.legend() + else: + raise ValueError( + f"Unknown format for argument `x` and `y`. Expected either list or tensors but got {type(x)} and {type(y)}." + ) + if label_names is not None: + ax.set_xlabel(label_names[0]) + ax.set_ylabel(label_names[1]) + ax.grid(True) + ax.set_title(name) + + return fig, ax diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/prints.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/prints.py new file mode 100644 index 0000000000000000000000000000000000000000..0824d06bea3be5dac4567a65ab47435e68e798eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/utilities/prints.py @@ -0,0 +1,73 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import warnings +from functools import partial, wraps +from typing import Any, Callable + +from torchmetrics import _logger as log + + +def rank_zero_only(fn: Callable) -> Callable: + """Call a function only on rank 0 in distributed settings. + + Meant to be used as an decorator. + + """ + + @wraps(fn) + def wrapped_fn(*args: Any, **kwargs: Any) -> Any: + if rank_zero_only.rank == 0: + return fn(*args, **kwargs) + return None + + return wrapped_fn + + +# add the attribute to the function but don't overwrite in case Trainer has already set it +rank_zero_only.rank = getattr(rank_zero_only, "rank", int(os.environ.get("LOCAL_RANK", 0))) + + +def _warn(*args: Any, **kwargs: Any) -> None: + warnings.warn(*args, **kwargs) + + +def _info(*args: Any, **kwargs: Any) -> None: + log.info(*args, **kwargs) + + +def _debug(*args: Any, **kwargs: Any) -> None: + log.debug(*args, **kwargs) + + +rank_zero_debug = rank_zero_only(_debug) +rank_zero_info = rank_zero_only(_info) +rank_zero_warn = rank_zero_only(_warn) +_future_warning = partial(warnings.warn, category=FutureWarning) + + +def _deprecated_root_import_class(name: str, domain: str) -> None: + """Warn user that he is importing class from location it has been deprecated.""" + _future_warning( + f"Importing `{name}` from `torchmetrics` was deprecated and will be removed in 2.0." + f" Import `{name}` from `torchmetrics.{domain}` instead." + ) + + +def _deprecated_root_import_func(name: str, domain: str) -> None: + """Warn user that he is importing function from location it has been deprecated.""" + _future_warning( + f"Importing `{name}` from `torchmetrics.functional` was deprecated and will be removed in 2.0." + f" Import `{name}` from `torchmetrics.{domain}` instead." + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/video/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5903f59052e1e354c103034944947f4cab2bc7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/video/__init__.py @@ -0,0 +1,21 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.utilities.imports import _TORCH_VMAF_AVAILABLE + +__all__ = [] + +if _TORCH_VMAF_AVAILABLE: + from torchmetrics.video.vmaf import VideoMultiMethodAssessmentFusion + + __all__ += ["VideoMultiMethodAssessmentFusion"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/video/vmaf.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/video/vmaf.py new file mode 100644 index 0000000000000000000000000000000000000000..1199c9619f1b0857486a6d4c9bb19ad68e44c80b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/video/vmaf.py @@ -0,0 +1,187 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Dict, List, Union + +from torch import Tensor + +from torchmetrics.functional.video.vmaf import video_multi_method_assessment_fusion +from torchmetrics.metric import Metric +from torchmetrics.utilities.data import dim_zero_cat +from torchmetrics.utilities.imports import _TORCH_VMAF_AVAILABLE + +if not _TORCH_VMAF_AVAILABLE: + __doctest_skip__ = ["VideoMultiMethodAssessmentFusion"] + + +class VideoMultiMethodAssessmentFusion(Metric): + """Calculates Video Multi-Method Assessment Fusion (VMAF) metric. + + VMAF is a full-reference video quality assessment algorithm that combines multiple quality assessment features + such as detail loss, motion, and contrast using a machine learning model to predict human perception of video + quality more accurately than traditional metrics like PSNR or SSIM. + + The metric works by: + + 1. Converting input videos to luma component (grayscale) + 2. Computing multiple elementary features: + - Additive Detail Measure (ADM): Evaluates detail preservation at different scales + - Visual Information Fidelity (VIF): Measures preservation of visual information across frequency bands + - Motion: Quantifies the amount of motion in the video + 3. Combining these features using a trained SVM model to predict quality + + .. note:: + This implementation requires you to have vmaf-torch installed: https://github.com/alvitrioliks/VMAF-torch. + Install either by cloning the repository and running ``pip install .`` + or with ``pip install torchmetrics[video]``. + + As input to ``forward`` and ``update`` the metric accepts the following input: + + - ``preds`` (:class:`~torch.Tensor`): Video tensor of shape ``(batch, channels, frames, height, width)``. + Expected to be in RGB format with values in range [0, 1]. + - ``target`` (:class:`~torch.Tensor`): Video tensor of shape ``(batch, channels, frames, height, width)``. + Expected to be in RGB format with values in range [0, 1]. + + As output of ``forward`` and ``compute`` the metric returns the following output ``vmaf`` (:class:`~torch.Tensor`): + + - If ``features`` is False, returns a tensor with shape (batch, frame) + of VMAF score for each frame in each video. Higher scores indicate better quality, with typical values + ranging from 0 to 100. + - If ``features`` is True, returns a dictionary where each value is a (batch, frame) tensor of the + corresponding feature. The keys are: + + - 'integer_motion2': Integer motion feature + - 'integer_motion': Integer motion feature + - 'integer_adm2': Integer ADM feature + - 'integer_adm_scale0': Integer ADM feature at scale 0 + - 'integer_adm_scale1': Integer ADM feature at scale 1 + - 'integer_adm_scale2': Integer ADM feature at scale 2 + - 'integer_adm_scale3': Integer ADM feature at scale 3 + - 'integer_vif_scale0': Integer VIF feature at scale 0 + - 'integer_vif_scale1': Integer VIF feature at scale 1 + - 'integer_vif_scale2': Integer VIF feature at scale 2 + - 'integer_vif_scale3': Integer VIF feature at scale 3 + - 'vmaf': VMAF score for each frame in each video + + Args: + features: If True, all the elementary features (ADM, VIF, motion) are returned along with the VMAF score in + a dictionary. This corresponds to the output you would get from the VMAF command line tool with + the ``--csv`` option enabled. If False, only the VMAF score is returned as a tensor. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + RuntimeError: + If vmaf-torch is not installed. + ValueError: + If ``features`` is not a boolean. + + Example: + >>> import torch + >>> from torchmetrics.video import VideoMultiMethodAssessmentFusion + >>> # 2 videos, 3 channels, 10 frames, 32x32 resolution + >>> preds = torch.rand(2, 3, 10, 32, 32, generator=torch.manual_seed(42)) + >>> target = torch.rand(2, 3, 10, 32, 32, generator=torch.manual_seed(43)) + >>> vmaf = VideoMultiMethodAssessmentFusion() + >>> torch.round(vmaf(preds, target), decimals=2) + tensor([[ 9.9900, 15.9000, 14.2600, 16.6100, 15.9100, 14.3000, 13.5800, 13.4900, 15.4700, 20.2800], + [ 6.2500, 11.3000, 17.3000, 11.4600, 19.0600, 14.9300, 14.0500, 14.4100, 12.4700, 14.8200]]) + >>> vmaf = VideoMultiMethodAssessmentFusion(features=True) + >>> vmaf_dict = vmaf(preds, target) + >>> vmaf_dict['vmaf'].round(decimals=2) + tensor([[ 9.9900, 15.9000, 14.2600, 16.6100, 15.9100, 14.3000, 13.5800, 13.4900, 15.4700, 20.2800], + [ 6.2500, 11.3000, 17.3000, 11.4600, 19.0600, 14.9300, 14.0500, 14.4100, 12.4700, 14.8200]]) + >>> vmaf_dict['integer_adm2'].round(decimals=2) + tensor([[0.4500, 0.4500, 0.3600, 0.4700, 0.4300, 0.3600, 0.3900, 0.4100, 0.3700, 0.4700], + [0.4200, 0.3900, 0.4400, 0.3700, 0.4500, 0.3900, 0.3800, 0.4800, 0.3900, 0.3900]]) + + """ + + is_differentiable: bool = False + higher_is_better: bool = True + full_state_update: bool = False + plot_lower_bound: float = 0.0 + plot_upper_bound: float = 100.0 + + vmaf_score: List[Tensor] + integer_motion2: List[Tensor] + integer_motion: List[Tensor] + integer_adm2: List[Tensor] + integer_adm_scale0: List[Tensor] + integer_adm_scale1: List[Tensor] + integer_adm_scale2: List[Tensor] + integer_adm_scale3: List[Tensor] + integer_vif_scale0: List[Tensor] + integer_vif_scale1: List[Tensor] + integer_vif_scale2: List[Tensor] + integer_vif_scale3: List[Tensor] + + def __init__(self, features: bool = False, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not _TORCH_VMAF_AVAILABLE: + raise RuntimeError("vmaf-torch is not installed. Please install with `pip install torchmetrics[video]`.") + + if not isinstance(features, bool): + raise ValueError("Argument `elementary_features` should be a boolean, but got {features}.") + self.features = features + + self.add_state("vmaf_score", default=[], dist_reduce_fx="cat") + if self.features: + self.add_state("integer_motion2", default=[], dist_reduce_fx="cat") + self.add_state("integer_motion", default=[], dist_reduce_fx="cat") + self.add_state("integer_adm2", default=[], dist_reduce_fx="cat") + self.add_state("integer_adm_scale0", default=[], dist_reduce_fx="cat") + self.add_state("integer_adm_scale1", default=[], dist_reduce_fx="cat") + self.add_state("integer_adm_scale2", default=[], dist_reduce_fx="cat") + self.add_state("integer_adm_scale3", default=[], dist_reduce_fx="cat") + self.add_state("integer_vif_scale0", default=[], dist_reduce_fx="cat") + self.add_state("integer_vif_scale1", default=[], dist_reduce_fx="cat") + self.add_state("integer_vif_scale2", default=[], dist_reduce_fx="cat") + self.add_state("integer_vif_scale3", default=[], dist_reduce_fx="cat") + + def update(self, preds: Tensor, target: Tensor) -> None: + """Update state with predictions and targets.""" + score = video_multi_method_assessment_fusion(preds, target, self.features) + if self.features and isinstance(score, dict): + self.vmaf_score.append(score["vmaf"]) + self.integer_motion2.append(score["integer_motion2"]) + self.integer_motion.append(score["integer_motion"]) + self.integer_adm2.append(score["integer_adm2"]) + self.integer_adm_scale0.append(score["integer_adm_scale0"]) + self.integer_adm_scale1.append(score["integer_adm_scale1"]) + self.integer_adm_scale2.append(score["integer_adm_scale2"]) + self.integer_adm_scale3.append(score["integer_adm_scale3"]) + self.integer_vif_scale0.append(score["integer_vif_scale0"]) + self.integer_vif_scale1.append(score["integer_vif_scale1"]) + self.integer_vif_scale2.append(score["integer_vif_scale2"]) + self.integer_vif_scale3.append(score["integer_vif_scale3"]) + elif isinstance(score, Tensor): + self.vmaf_score.append(score) + + def compute(self) -> Union[Tensor, Dict[str, Tensor]]: + """Compute final VMAF score.""" + if self.features: + return { + "vmaf": dim_zero_cat(self.vmaf_score), + "integer_motion2": dim_zero_cat(self.integer_motion2), + "integer_motion": dim_zero_cat(self.integer_motion), + "integer_adm2": dim_zero_cat(self.integer_adm2), + "integer_adm_scale0": dim_zero_cat(self.integer_adm_scale0), + "integer_adm_scale1": dim_zero_cat(self.integer_adm_scale1), + "integer_adm_scale2": dim_zero_cat(self.integer_adm_scale2), + "integer_adm_scale3": dim_zero_cat(self.integer_adm_scale3), + "integer_vif_scale0": dim_zero_cat(self.integer_vif_scale0), + "integer_vif_scale1": dim_zero_cat(self.integer_vif_scale1), + "integer_vif_scale2": dim_zero_cat(self.integer_vif_scale2), + "integer_vif_scale3": dim_zero_cat(self.integer_vif_scale3), + } + return dim_zero_cat(self.vmaf_score) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a41f990a218b60bd4b33b26a2cd5d1198dff0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/__init__.py @@ -0,0 +1,40 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from torchmetrics.wrappers.bootstrapping import BootStrapper +from torchmetrics.wrappers.classwise import ClasswiseWrapper +from torchmetrics.wrappers.feature_share import FeatureShare +from torchmetrics.wrappers.minmax import MinMaxMetric +from torchmetrics.wrappers.multioutput import MultioutputWrapper +from torchmetrics.wrappers.multitask import MultitaskWrapper +from torchmetrics.wrappers.running import Running +from torchmetrics.wrappers.tracker import MetricTracker +from torchmetrics.wrappers.transformations import ( + BinaryTargetTransformer, + LambdaInputTransformer, + MetricInputTransformer, +) + +__all__ = [ + "BinaryTargetTransformer", + "BootStrapper", + "ClasswiseWrapper", + "FeatureShare", + "LambdaInputTransformer", + "MetricInputTransformer", + "MetricTracker", + "MinMaxMetric", + "MultioutputWrapper", + "MultitaskWrapper", + "Running", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/abstract.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/abstract.py new file mode 100644 index 0000000000000000000000000000000000000000..27bdfc0a9f3b9966c632dfc4564b9277b7ab3bd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/abstract.py @@ -0,0 +1,42 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Callable + +from torchmetrics.metric import Metric + + +class WrapperMetric(Metric): + """Abstract base class for wrapper metrics. + + Wrapper metrics are characterized by them wrapping another metric, and forwarding all calls to the wrapped metric. + This means that all logic regarding synchronization etc. is handled by the wrapped metric, and the wrapper metric + should not do anything in this regard. + + This class therefore overwrites all methods that are related to synchronization, and does nothing in them. + + Additionally, the forward method is not implemented by default as custom logic is required for each wrapper metric. + + """ + + def _wrap_update(self, update: Callable) -> Callable: + """Overwrite to do nothing, because the default wrapped functionality is handled by the wrapped metric.""" + return update + + def _wrap_compute(self, compute: Callable) -> Callable: + """Overwrite to do nothing, because the default wrapped functionality is handled by the wrapped metric.""" + return compute + + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Overwrite to do nothing, because the default wrapped functionality is handled by the wrapped metric.""" + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/bootstrapping.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/bootstrapping.py new file mode 100644 index 0000000000000000000000000000000000000000..b4283022e3f403e992a051ed94912ec3663c0dda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/bootstrapping.py @@ -0,0 +1,221 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from copy import deepcopy +from typing import Any, Optional, Union, cast + +import torch +from lightning_utilities import apply_to_collection +from torch import Tensor +from torch.nn import ModuleList + +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE +from torchmetrics.wrappers.abstract import WrapperMetric + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["BootStrapper.plot"] + + +def _bootstrap_sampler( + size: int, + sampling_strategy: str = "poisson", +) -> torch.Tensor: + """Resample a tensor along its first dimension with replacement. + + Args: + size: number of samples + sampling_strategy: the strategy to use for sampling, either ``'poisson'`` or ``'multinomial'`` + + Returns: + resampled tensor + + """ + if sampling_strategy == "poisson": + p = torch.distributions.Poisson(1) + n = p.sample((size,)) + return torch.arange(size).repeat_interleave(n.long(), dim=0) + if sampling_strategy == "multinomial": + return torch.multinomial(torch.ones(size), num_samples=size, replacement=True) + raise ValueError("Unknown sampling strategy") + + +class BootStrapper(WrapperMetric): + r"""Using `Turn a Metric into a Bootstrapped`_. + + That can automate the process of getting confidence intervals for metric values. This wrapper + class basically keeps multiple copies of the same base metric in memory and whenever ``update`` or + ``forward`` is called, all input tensors are resampled (with replacement) along the first dimension. + + Args: + base_metric: base metric class to wrap + num_bootstraps: number of copies to make of the base metric for bootstrapping + mean: if ``True`` return the mean of the bootstraps + std: if ``True`` return the standard deviation of the bootstraps + quantile: if given, returns the quantile of the bootstraps. Can only be used with pytorch version 1.6 or higher + raw: if ``True``, return all bootstrapped values + sampling_strategy: + Determines how to produce bootstrapped samplings. Either ``'poisson'`` or ``multinomial``. + If ``'possion'`` is chosen, the number of times each sample will be included in the bootstrap + will be given by :math:`n\sim Poisson(\lambda=1)`, which approximates the true bootstrap distribution + when the number of samples is large. If ``'multinomial'`` is chosen, we will apply true bootstrapping + at the batch level to approximate bootstrapping over the hole dataset. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Example:: + >>> from pprint import pprint + >>> from torch import randint + >>> from torchmetrics.wrappers import BootStrapper + >>> from torchmetrics.classification import MulticlassAccuracy + >>> base_metric = MulticlassAccuracy(num_classes=5, average='micro') + >>> bootstrap = BootStrapper(base_metric, num_bootstraps=20) + >>> bootstrap.update(randint(5, (20,)), randint(5, (20,))) + >>> output = bootstrap.compute() + >>> pprint(output) + {'mean': tensor(0.2089), 'std': tensor(0.0772)} + + """ + + full_state_update: Optional[bool] = True + + def __init__( + self, + base_metric: Metric, + num_bootstraps: int = 10, + mean: bool = True, + std: bool = True, + quantile: Optional[Union[float, Tensor]] = None, + raw: bool = False, + sampling_strategy: str = "poisson", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(base_metric, Metric): + raise ValueError( + f"Expected base metric to be an instance of torchmetrics.Metric but received {base_metric}" + ) + + self.metrics = ModuleList([deepcopy(base_metric) for _ in range(num_bootstraps)]) + self.num_bootstraps = num_bootstraps + + self.mean = mean + self.std = std + self.quantile = quantile + self.raw = raw + + allowed_sampling = ("poisson", "multinomial") + if sampling_strategy not in allowed_sampling: + raise ValueError( + f"Expected argument ``sampling_strategy`` to be one of {allowed_sampling}" + f" but received {sampling_strategy}" + ) + self.sampling_strategy = sampling_strategy + + def update(self, *args: Any, **kwargs: Any) -> None: + """Update the state of the base metric. + + Any tensor passed in will be bootstrapped along dimension 0. + + """ + args_sizes = apply_to_collection(args, torch.Tensor, len) + kwargs_sizes = apply_to_collection(kwargs, torch.Tensor, len) + if len(args_sizes) > 0: + size = args_sizes[0] + elif len(kwargs_sizes) > 0: + size = next(iter(kwargs_sizes.values())) + else: + raise ValueError("None of the input contained tensors, so could not determine the sampling size") + + for idx in range(self.num_bootstraps): + sample_idx = _bootstrap_sampler(size, sampling_strategy=self.sampling_strategy).to(self.device) + if sample_idx.numel() == 0: + continue + new_args = apply_to_collection(args, torch.Tensor, torch.index_select, dim=0, index=sample_idx) + new_kwargs = apply_to_collection(kwargs, torch.Tensor, torch.index_select, dim=0, index=sample_idx) + self.metrics[idx].update(*new_args, **new_kwargs) # type: ignore[operator] # needed for mypy + + def compute(self) -> dict[str, Tensor]: + """Compute the bootstrapped metric values. + + Always returns a dict of tensors, which can contain the following keys: ``mean``, ``std``, ``quantile`` and + ``raw`` depending on how the class was initialized. + + """ + computed_vals = torch.stack([cast(Metric, m).compute() for m in self.metrics], dim=0) + output_dict = {} + if self.mean: + output_dict["mean"] = computed_vals.mean(dim=0) + if self.std: + output_dict["std"] = computed_vals.std(dim=0) + if self.quantile is not None: + output_dict["quantile"] = torch.quantile(computed_vals, self.quantile) + if self.raw: + output_dict["raw"] = computed_vals + return output_dict + + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Use the original forward method of the base metric class.""" + return super(WrapperMetric, self).forward(*args, **kwargs) + + def reset(self) -> None: + """Reset the state of the base metric.""" + for m in self.metrics: + m = cast(Metric, m) + m.reset() + super().reset() + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.wrappers import BootStrapper + >>> from torchmetrics.regression import MeanSquaredError + >>> metric = BootStrapper(MeanSquaredError(), num_bootstraps=20) + >>> metric.update(torch.randn(100,), torch.randn(100,)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.wrappers import BootStrapper + >>> from torchmetrics.regression import MeanSquaredError + >>> metric = BootStrapper(MeanSquaredError(), num_bootstraps=20) + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.randn(100,), torch.randn(100,))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/classwise.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/classwise.py new file mode 100644 index 0000000000000000000000000000000000000000..59a6bd223acc931b51315e0d04b4f06173c91e7c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/classwise.py @@ -0,0 +1,244 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import typing +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor + +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE +from torchmetrics.wrappers.abstract import WrapperMetric + +if typing.TYPE_CHECKING: + from torch.nn import Module + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["ClasswiseWrapper.plot"] + + +class ClasswiseWrapper(WrapperMetric): + """Wrapper metric for altering the output of classification metrics. + + This metric works together with classification metrics that returns multiple values (one value per class) such that + label information can be automatically included in the output. + + Args: + metric: base metric that should be wrapped. It is assumed that the metric outputs a single + tensor that is split along the first dimension. + labels: list of strings indicating the different classes. + prefix: string that is prepended to the metric names. + postfix: string that is appended to the metric names. + + Example:: + Basic example where the output of a metric is unwrapped into a dictionary with the class index as keys: + + >>> from torch import randint, randn + >>> from torchmetrics.wrappers import ClasswiseWrapper + >>> from torchmetrics.classification import MulticlassAccuracy + >>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None)) + >>> preds = randn(10, 3).softmax(dim=-1) + >>> target = randint(3, (10,)) + >>> metric(preds, target) # doctest: +NORMALIZE_WHITESPACE + {'multiclassaccuracy_0': tensor(0.5000), + 'multiclassaccuracy_1': tensor(0.7500), + 'multiclassaccuracy_2': tensor(0.)} + + Example:: + Using custom name via prefix and postfix: + + >>> from torch import randint, randn + >>> from torchmetrics.wrappers import ClasswiseWrapper + >>> from torchmetrics.classification import MulticlassAccuracy + >>> metric_pre = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), prefix="acc-") + >>> metric_post = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), postfix="-acc") + >>> preds = randn(10, 3).softmax(dim=-1) + >>> target = randint(3, (10,)) + >>> metric_pre(preds, target) # doctest: +NORMALIZE_WHITESPACE + {'acc-0': tensor(0.3333), 'acc-1': tensor(0.6667), 'acc-2': tensor(0.)} + >>> metric_post(preds, target) # doctest: +NORMALIZE_WHITESPACE + {'0-acc': tensor(0.3333), '1-acc': tensor(0.6667), '2-acc': tensor(0.)} + + Example:: + Providing labels as a list of strings: + + >>> from torch import randint, randn + >>> from torchmetrics.wrappers import ClasswiseWrapper + >>> from torchmetrics.classification import MulticlassAccuracy + >>> metric = ClasswiseWrapper( + ... MulticlassAccuracy(num_classes=3, average=None), + ... labels=["horse", "fish", "dog"] + ... ) + >>> preds = randn(10, 3).softmax(dim=-1) + >>> target = randint(3, (10,)) + >>> metric(preds, target) # doctest: +NORMALIZE_WHITESPACE + {'multiclassaccuracy_horse': tensor(0.), + 'multiclassaccuracy_fish': tensor(0.3333), + 'multiclassaccuracy_dog': tensor(0.4000)} + + Example:: + Classwise can also be used in combination with :class:`~torchmetrics.MetricCollection`. In this case, everything + will be flattened into a single dictionary: + + >>> from torch import randint, randn + >>> from torchmetrics import MetricCollection + >>> from torchmetrics.wrappers import ClasswiseWrapper + >>> from torchmetrics.classification import MulticlassAccuracy, MulticlassRecall + >>> labels = ["horse", "fish", "dog"] + >>> metric = MetricCollection( + ... {'multiclassaccuracy': ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), labels), + ... 'multiclassrecall': ClasswiseWrapper(MulticlassRecall(num_classes=3, average=None), labels)} + ... ) + >>> preds = randn(10, 3).softmax(dim=-1) + >>> target = randint(3, (10,)) + >>> metric(preds, target) # doctest: +NORMALIZE_WHITESPACE + {'multiclassaccuracy_horse': tensor(0.6667), + 'multiclassaccuracy_fish': tensor(0.3333), + 'multiclassaccuracy_dog': tensor(0.5000), + 'multiclassrecall_horse': tensor(0.6667), + 'multiclassrecall_fish': tensor(0.3333), + 'multiclassrecall_dog': tensor(0.5000)} + + """ + + metric: Metric + labels: Optional[list[str]] + + def __init__( + self, + metric: Metric, + labels: Optional[list[str]] = None, + prefix: Optional[str] = None, + postfix: Optional[str] = None, + ) -> None: + super().__init__() + if not isinstance(metric, Metric): + raise ValueError(f"Expected argument `metric` to be an instance of `torchmetrics.Metric` but got {metric}") + self.metric = metric + + if labels is not None and not (isinstance(labels, list) and all(isinstance(lab, str) for lab in labels)): + raise ValueError(f"Expected argument `labels` to either be `None` or a list of strings but got {labels}") + self.labels = labels + + if prefix is not None and not isinstance(prefix, str): + raise ValueError(f"Expected argument `prefix` to either be `None` or a string but got {prefix}") + self._prefix = prefix + + if postfix is not None and not isinstance(postfix, str): + raise ValueError(f"Expected argument `postfix` to either be `None` or a string but got {postfix}") + self._postfix = postfix + + self._update_count = 1 + + @property + def higher_is_better(self) -> Optional[bool]: # type: ignore + """Return if the metric is higher the better.""" + return self.metric.higher_is_better + + def _filter_kwargs(self, **kwargs: Any) -> dict[str, Any]: + """Filter kwargs for the metric.""" + return self.metric._filter_kwargs(**kwargs) + + def _convert_output(self, x: Tensor) -> dict[str, Any]: + """Convert output to dictionary with labels as keys.""" + # Will set the class name as prefix if neither prefix nor postfix is given + if not self._prefix and not self._postfix: + prefix = f"{self.metric.__class__.__name__.lower()}_" + postfix = "" + else: + prefix = self._prefix or "" + postfix = self._postfix or "" + if self.labels is None: + return {f"{prefix}{i}{postfix}": val for i, val in enumerate(x)} + return {f"{prefix}{lab}{postfix}": val for lab, val in zip(self.labels, x)} + + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Calculate on batch and accumulate to global state.""" + return self._convert_output(self.metric(*args, **kwargs)) + + def update(self, *args: Any, **kwargs: Any) -> None: + """Update state.""" + self.metric.update(*args, **kwargs) + + def compute(self) -> dict[str, Tensor]: + """Compute metric.""" + return self._convert_output(self.metric.compute()) + + def reset(self) -> None: + """Reset metric.""" + self.metric.reset() + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.wrappers import ClasswiseWrapper + >>> from torchmetrics.classification import MulticlassAccuracy + >>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None)) + >>> metric.update(torch.randint(3, (20,)), torch.randint(3, (20,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.wrappers import ClasswiseWrapper + >>> from torchmetrics.classification import MulticlassAccuracy + >>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None)) + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.randint(3, (20,)), torch.randint(3, (20,)))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) + + def __getattr__(self, name: str) -> Union[Tensor, "Module"]: + """Get attribute from classwise wrapper.""" + if name == "metric" or (name in self.__dict__ and name not in self.metric.__dict__): + # we need this to prevent from infinite getattribute loop. + return super().__getattr__(name) + + return getattr(self.metric, name) + + def __setattr__(self, name: str, value: Any) -> None: + """Set attribute to classwise wrapper.""" + if hasattr(self, "metric") and name in self.metric._defaults: + setattr(self.metric, name, value) + else: + super().__setattr__(name, value) + if name == "metric": + self._defaults = self.metric._defaults + self._persistent = self.metric._persistent + self._reductions = self.metric._reductions diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/feature_share.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/feature_share.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa8f2264980119625465067c9c2beffba9d05c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/feature_share.py @@ -0,0 +1,135 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from functools import lru_cache +from typing import Any, Optional, Union + +from torch.nn import Module + +from torchmetrics.collections import MetricCollection +from torchmetrics.metric import Metric +from torchmetrics.utilities import rank_zero_warn + +__doctest_requires__ = {("FeatureShare",): ["torch_fidelity"]} + + +class NetworkCache(Module): + """Create a cached version of a network to be shared between metrics. + + Because the different metrics may invoke the same network multiple times, we can save time by caching the input- + output pairs of the network. + + """ + + def __init__(self, network: Module, max_size: int = 100) -> None: + super().__init__() + self.max_size = max_size + self.network = network + self.network.forward = lru_cache(maxsize=self.max_size)(network.forward) + + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Call the network with the given arguments.""" + return self.network(*args, **kwargs) + + +class FeatureShare(MetricCollection): + """Specialized metric collection that facilitates sharing features between metrics. + + Certain metrics rely on an underlying expensive neural network for feature extraction when computing the metric. + This wrapper allows to share the feature extraction between multiple metrics, which can save a lot of time and + memory. This is achieved by making a shared instance of the network between the metrics and secondly by caching + the input-output pairs of the network, such the subsequent calls to the network with the same input will be much + faster. + + Args: + metrics: One of the following: + + * list or tuple (sequence): if metrics are passed in as a list or tuple, will use the metrics class name + as key for output dict. Therefore, two metrics of the same class cannot be chained this way. + + + * dict: if metrics are passed in as a dict, will use each key in the dict as key for output dict. + Use this format if you want to chain together multiple of the same metric with different parameters. + Note that the keys in the output dict will be sorted alphabetically. + + max_cache_size: maximum number of input-output pairs to cache per metric. By default, this is none which means + that the cache will be set to the number of metrics in the collection meaning that all features will be + cached and shared across all metrics per batch. + + Example:: + >>> import torch + >>> from torchmetrics.wrappers import FeatureShare + >>> from torchmetrics.image import FrechetInceptionDistance, KernelInceptionDistance + >>> # initialize the metrics + >>> fs = FeatureShare([FrechetInceptionDistance(), KernelInceptionDistance(subset_size=10, subsets=2)]) + >>> # update metric + >>> input_tensor = torch.randint(255, (50, 3, 64, 64), dtype=torch.uint8, generator=torch.manual_seed(42)) + >>> fs.update(input_tensor, real=True) + >>> input_tensor = torch.randint(255, (50, 3, 64, 64), dtype=torch.uint8, generator=torch.manual_seed(43)) + >>> fs.update(input_tensor, real=False) + >>> # compute metric + >>> fs.compute() + {'FrechetInceptionDistance': tensor(13.5367), 'KernelInceptionDistance': (tensor(0.0003), tensor(0.0003))} + + """ + + def __init__( + self, + metrics: Union[Metric, Sequence[Metric], dict[str, Metric]], + max_cache_size: Optional[int] = None, + ) -> None: + # disable compute groups because the feature sharing is more custom + super().__init__(metrics=metrics, compute_groups=False) # type: ignore + + if max_cache_size is None: + max_cache_size = len(self) + if not isinstance(max_cache_size, int): + raise TypeError(f"max_cache_size should be an integer, but got {max_cache_size}") + + try: + first_net = next(iter(self.values())) + if not isinstance(first_net.feature_network, str): + raise TypeError("The `feature_network` attribute must be a string.") + network_to_share = getattr(first_net, first_net.feature_network) + except AttributeError as err: + raise AttributeError( + "Tried to extract the network to share from the first metric, but it did not have a `feature_network`" + " attribute. Please make sure that the metric has an attribute with that name," + " else it cannot be shared." + ) from err + except TypeError as err: + raise TypeError("The `feature_network` attribute must be a string representing the network name.") from err + cached_net = NetworkCache(network_to_share, max_size=max_cache_size) + + # set the cached network to all metrics + for metric_name, metric in self.items(): + if not hasattr(metric, "feature_network"): + raise AttributeError( + "Tried to set the cached network to all metrics, but one of the metrics did not have a" + " `feature_network` attribute. Please make sure that all metrics have a attribute with that name," + f" else it cannot be shared. Failed on metric {metric_name}." + ) + if not isinstance(metric.feature_network, str): + raise TypeError(f"Metric {metric_name}'s `feature_network` attribute must be a string.") + + # check if its the same network as the first metric + if str(getattr(metric, metric.feature_network)) != str(network_to_share): + rank_zero_warn( + f"The network to share between the metrics is not the same for all metrics." + f" Metric {metric_name} has a different network than the first metric." + " This may lead to unexpected behavior.", + UserWarning, + ) + + setattr(metric, metric.feature_network, cached_net) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/minmax.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/minmax.py new file mode 100644 index 0000000000000000000000000000000000000000..25300e8fbe0818ece1ae7d26d31ae7bb741bb677 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/minmax.py @@ -0,0 +1,160 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torch import Tensor + +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE +from torchmetrics.wrappers.abstract import WrapperMetric + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MinMaxMetric.plot"] + + +class MinMaxMetric(WrapperMetric): + """Wrapper metric that tracks both the minimum and maximum of a scalar/tensor across an experiment. + + The min/max value will be updated each time ``.compute`` is called. + + Args: + base_metric: + The metric of which you want to keep track of its maximum and minimum values. + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. + + Raises: + ValueError + If ``base_metric` argument is not a subclasses instance of ``torchmetrics.Metric`` + + Example:: + >>> import torch + >>> from torchmetrics.wrappers import MinMaxMetric + >>> from torchmetrics.classification import BinaryAccuracy + >>> from pprint import pprint + >>> base_metric = BinaryAccuracy() + >>> minmax_metric = MinMaxMetric(base_metric) + >>> preds_1 = torch.Tensor([[0.1, 0.9], [0.2, 0.8]]) + >>> preds_2 = torch.Tensor([[0.9, 0.1], [0.2, 0.8]]) + >>> labels = torch.Tensor([[0, 1], [0, 1]]).long() + >>> pprint(minmax_metric(preds_1, labels)) + {'max': tensor(1.), 'min': tensor(1.), 'raw': tensor(1.)} + >>> pprint(minmax_metric.compute()) + {'max': tensor(1.), 'min': tensor(1.), 'raw': tensor(1.)} + >>> minmax_metric.update(preds_2, labels) + >>> pprint(minmax_metric.compute()) + {'max': tensor(1.), 'min': tensor(0.7500), 'raw': tensor(0.7500)} + + """ + + full_state_update: Optional[bool] = True + min_val: Tensor + max_val: Tensor + + def __init__( + self, + base_metric: Metric, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(base_metric, Metric): + raise ValueError( + f"Expected base metric to be an instance of `torchmetrics.Metric` but received {base_metric}" + ) + self._base_metric = base_metric + self.min_val = torch.tensor(float("inf")) + self.max_val = torch.tensor(float("-inf")) + + def update(self, *args: Any, **kwargs: Any) -> None: + """Update the underlying metric.""" + self._base_metric.update(*args, **kwargs) + + def compute(self) -> dict[str, Tensor]: + """Compute the underlying metric as well as max and min values for this metric. + + Returns a dictionary that consists of the computed value (``raw``), as well as the minimum (``min``) and maximum + (``max``) values. + + """ + val = self._base_metric.compute() + if not self._is_suitable_val(val): + raise RuntimeError(f"Returned value from base metric should be a float or scalar tensor, but got {val}.") + self.max_val = val if self.max_val.to(val.device) < val else self.max_val.to(val.device) + self.min_val = val if self.min_val.to(val.device) > val else self.min_val.to(val.device) + return {"raw": val, "max": self.max_val, "min": self.min_val} + + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Use the original forward method of the base metric class.""" + return super(WrapperMetric, self).forward(*args, **kwargs) + + def reset(self) -> None: + """Set ``max_val`` and ``min_val`` to the initialization bounds and resets the base metric.""" + super().reset() + self._base_metric.reset() + + @staticmethod + def _is_suitable_val(val: Union[float, Tensor]) -> bool: + """Check whether min/max is a scalar value.""" + if isinstance(val, (int, float)): + return True + if isinstance(val, Tensor): + return val.numel() == 1 + return False + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.wrappers import MinMaxMetric + >>> from torchmetrics.classification import BinaryAccuracy + >>> metric = MinMaxMetric(BinaryAccuracy()) + >>> metric.update(torch.randint(2, (20,)), torch.randint(2, (20,))) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.wrappers import MinMaxMetric + >>> from torchmetrics.classification import BinaryAccuracy + >>> metric = MinMaxMetric(BinaryAccuracy()) + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.randint(2, (20,)), torch.randint(2, (20,)))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/multioutput.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/multioutput.py new file mode 100644 index 0000000000000000000000000000000000000000..aec593f9f1decc10a66d75c1473d0d6441af5b91 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/multioutput.py @@ -0,0 +1,203 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Mapping, Sequence +from copy import deepcopy +from typing import Any, Optional, Union, cast + +import torch +from lightning_utilities import apply_to_collection +from torch import Tensor +from torch.nn import ModuleList + +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE +from torchmetrics.wrappers.abstract import WrapperMetric + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MultioutputWrapper.plot"] + + +def _get_nan_indices(*tensors: Tensor) -> Tensor: + """Get indices of rows along dim 0 which have NaN values.""" + if len(tensors) == 0: + raise ValueError("Must pass at least one tensor as argument") + sentinel = tensors[0] + nan_idxs = torch.zeros(len(sentinel), dtype=torch.bool, device=sentinel.device) + for tensor in tensors: + permuted_tensor = tensor.flatten(start_dim=1) + nan_idxs |= torch.any(torch.isnan(permuted_tensor), dim=1) + return nan_idxs + + +class MultioutputWrapper(WrapperMetric): + """Wrap a base metric to enable it to support multiple outputs. + + Several torchmetrics metrics, such as :class:`~torchmetrics.regression.spearman.SpearmanCorrCoef` lack support for + multioutput mode. This class wraps such metrics to support computing one metric per output. + Unlike specific torchmetric metrics, it doesn't support any aggregation across outputs. + This means if you set ``num_outputs`` to 2, ``.compute()`` will return a Tensor of dimension + ``(2, ...)`` where ``...`` represents the dimensions the metric returns when not wrapped. + + In addition to enabling multioutput support for metrics that lack it, this class also supports, albeit in a crude + fashion, dealing with missing labels (or other data). When ``remove_nans`` is passed, the class will remove the + intersection of NaN containing "rows" upon each update for each output. For example, suppose a user uses + `MultioutputWrapper` to wrap :class:`torchmetrics.regression.r2.R2Score` with 2 outputs, one of which occasionally + has missing labels for classes like ``R2Score`` is that this class supports removing ``NaN`` values + (parameter ``remove_nans``) on a per-output basis. When ``remove_nans`` is passed the wrapper will remove all rows + + Args: + base_metric: Metric being wrapped. + num_outputs: Expected dimensionality of the output dimension. + This parameter is used to determine the number of distinct metrics we need to track. + output_dim: + Dimension on which output is expected. Note that while this provides some flexibility, the output dimension + must be the same for all inputs to update. This applies even for metrics such as `Accuracy` where the labels + can have a different number of dimensions than the predictions. This can be worked around if the output + dimension can be set to -1 for both, even if -1 corresponds to different dimensions in different inputs. + remove_nans: + Whether to remove the intersection of rows containing NaNs from the values passed through to each underlying + metric. Proper operation requires all tensors passed to update to have dimension ``(N, ...)`` where N + represents the length of the batch or dataset being passed in. + squeeze_outputs: + If ``True``, will squeeze the 1-item dimensions left after ``index_select`` is applied. + This is sometimes unnecessary but harmless for metrics such as `R2Score` but useful + for certain classification metrics that can't handle additional 1-item dimensions. + + Example: + >>> # Mimic R2Score in `multioutput`, `raw_values` mode: + >>> import torch + >>> from torchmetrics.wrappers import MultioutputWrapper + >>> from torchmetrics.regression import R2Score + >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) + >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) + >>> r2score = MultioutputWrapper(R2Score(), 2) + >>> r2score(preds, target) + tensor([0.9654, 0.9082]) + + """ + + is_differentiable = False + + def __init__( + self, + base_metric: Metric, + num_outputs: int, + output_dim: int = -1, + remove_nans: bool = True, + squeeze_outputs: bool = True, + ) -> None: + super().__init__() + self.metrics = ModuleList([deepcopy(base_metric) for _ in range(num_outputs)]) + self.output_dim = output_dim + self.remove_nans = remove_nans + self.squeeze_outputs = squeeze_outputs + + def _get_args_kwargs_by_output(self, *args: Tensor, **kwargs: Tensor) -> list[tuple[Tensor, Tensor]]: + """Get args and kwargs reshaped to be output-specific and (maybe) having NaNs stripped out.""" + args_kwargs_by_output = [] + for i in range(len(self.metrics)): + selected_args = apply_to_collection( + args, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device) + ) + selected_kwargs = apply_to_collection( + kwargs, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device) + ) + if self.remove_nans: + args_kwargs = selected_args + tuple(selected_kwargs.values()) + nan_idxs = _get_nan_indices(*args_kwargs) + selected_args = [arg[~nan_idxs] for arg in selected_args] + selected_kwargs = {k: v[~nan_idxs] for k, v in selected_kwargs.items()} + + if self.squeeze_outputs: + selected_args = [arg.squeeze(self.output_dim) for arg in selected_args] + selected_kwargs = {k: v.squeeze(self.output_dim) for k, v in selected_kwargs.items()} + args_kwargs_by_output.append((selected_args, selected_kwargs)) + return args_kwargs_by_output + + def update(self, *args: Any, **kwargs: Any) -> None: + """Update each underlying metric with the corresponding output.""" + reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs) + for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs): + cast(Metric, metric).update(*selected_args, **cast(Mapping, selected_kwargs)) + + def compute(self) -> Tensor: + """Compute metrics.""" + return torch.stack([cast(Metric, m).compute() for m in self.metrics], 0) + + @torch.jit.unused + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Call underlying forward methods and aggregate the results if they're non-null. + + We override this method to ensure that state variables get copied over on the underlying metrics. + + """ + reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs) + results = [ + metric(*selected_args, **cast(Mapping, selected_kwargs)) + for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs) + ] + if results[0] is None: + return None + return torch.stack(results, 0) + + def reset(self) -> None: + """Reset all underlying metrics.""" + for metric in self.metrics: + cast(Metric, metric).reset() + super().reset() + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.wrappers import MultioutputWrapper + >>> from torchmetrics.regression import R2Score + >>> metric = MultioutputWrapper(R2Score(), 2) + >>> metric.update(torch.randn(20, 2), torch.randn(20, 2)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.wrappers import MultioutputWrapper + >>> from torchmetrics.regression import R2Score + >>> metric = MultioutputWrapper(R2Score(), 2) + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.randn(20, 2), torch.randn(20, 2))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/multitask.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/multitask.py new file mode 100644 index 0000000000000000000000000000000000000000..98918e248af7fd68a2799f52306f5a3e3e66e636 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/multitask.py @@ -0,0 +1,389 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# this is just a bypass for this module name collision with built-in one +from collections.abc import Iterable, Sequence +from copy import deepcopy +from typing import Any, Optional, Union + +from torch import Tensor, nn + +from torchmetrics.collections import MetricCollection +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE +from torchmetrics.wrappers.abstract import WrapperMetric + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MultitaskWrapper.plot"] + + +class MultitaskWrapper(WrapperMetric): + """Wrapper class for computing different metrics on different tasks in the context of multitask learning. + + In multitask learning the different tasks requires different metrics to be evaluated. This wrapper allows + for easy evaluation in such cases by supporting multiple predictions and targets through a dictionary. + Note that only metrics where the signature of `update` follows the standard `preds, target` is supported. + + Args: + task_metrics: + Dictionary associating each task to a Metric or a MetricCollection. The keys of the dictionary represent the + names of the tasks, and the values represent the metrics to use for each task. + prefix: + A string to append in front of the metric keys. If not provided, will default to an empty string. + postfix: + A string to append after the keys of the output dict. If not provided, will default to an empty string. + + .. tip:: + The use prefix and postfix allows for easily creating task wrappers for training, validation and test. + The arguments are only changing the output keys of the computed metrics and not the input keys. This means + that a ``MultitaskWrapper`` initialized as ``MultitaskWrapper({"task": Metric()}, prefix="train_")`` will + still expect the input to be a dictionary with the key "task", but the output will be a dictionary with the key + "train_task". + + Raises: + TypeError: + If argument `task_metrics` is not an dictionary + TypeError: + If not all values in the `task_metrics` dictionary is instances of `Metric` or `MetricCollection` + ValueError: + If `prefix` is not a string + ValueError: + If `postfix` is not a string + + Example (with a single metric per class): + >>> import torch + >>> from torchmetrics.wrappers import MultitaskWrapper + >>> from torchmetrics.regression import MeanSquaredError + >>> from torchmetrics.classification import BinaryAccuracy + >>> + >>> classification_target = torch.tensor([0, 1, 0]) + >>> regression_target = torch.tensor([2.5, 5.0, 4.0]) + >>> targets = {"Classification": classification_target, "Regression": regression_target} + >>> + >>> classification_preds = torch.tensor([0, 0, 1]) + >>> regression_preds = torch.tensor([3.0, 5.0, 2.5]) + >>> preds = {"Classification": classification_preds, "Regression": regression_preds} + >>> + >>> metrics = MultitaskWrapper({ + ... "Classification": BinaryAccuracy(), + ... "Regression": MeanSquaredError() + ... }) + >>> metrics.update(preds, targets) + >>> metrics.compute() + {'Classification': tensor(0.3333), 'Regression': tensor(0.8333)} + + Example (with several metrics per task): + >>> import torch + >>> from torchmetrics import MetricCollection + >>> from torchmetrics.wrappers import MultitaskWrapper + >>> from torchmetrics.regression import MeanSquaredError, MeanAbsoluteError + >>> from torchmetrics.classification import BinaryAccuracy, BinaryF1Score + >>> + >>> classification_target = torch.tensor([0, 1, 0]) + >>> regression_target = torch.tensor([2.5, 5.0, 4.0]) + >>> targets = {"Classification": classification_target, "Regression": regression_target} + >>> + >>> classification_preds = torch.tensor([0, 0, 1]) + >>> regression_preds = torch.tensor([3.0, 5.0, 2.5]) + >>> preds = {"Classification": classification_preds, "Regression": regression_preds} + >>> + >>> metrics = MultitaskWrapper({ + ... "Classification": MetricCollection(BinaryAccuracy(), BinaryF1Score()), + ... "Regression": MetricCollection(MeanSquaredError(), MeanAbsoluteError()) + ... }) + >>> metrics.update(preds, targets) + >>> metrics.compute() + {'Classification': {'BinaryAccuracy': tensor(0.3333), 'BinaryF1Score': tensor(0.)}, + 'Regression': {'MeanSquaredError': tensor(0.8333), 'MeanAbsoluteError': tensor(0.6667)}} + + Example (with a prefix and postfix): + >>> import torch + >>> from torchmetrics.wrappers import MultitaskWrapper + >>> from torchmetrics.regression import MeanSquaredError + >>> from torchmetrics.classification import BinaryAccuracy + >>> + >>> classification_target = torch.tensor([0, 1, 0]) + >>> regression_target = torch.tensor([2.5, 5.0, 4.0]) + >>> targets = {"Classification": classification_target, "Regression": regression_target} + >>> classification_preds = torch.tensor([0, 0, 1]) + >>> regression_preds = torch.tensor([3.0, 5.0, 2.5]) + >>> preds = {"Classification": classification_preds, "Regression": regression_preds} + >>> + >>> metrics = MultitaskWrapper({ + ... "Classification": BinaryAccuracy(), + ... "Regression": MeanSquaredError() + ... }, prefix="train_") + >>> metrics.update(preds, targets) + >>> metrics.compute() + {'train_Classification': tensor(0.3333), 'train_Regression': tensor(0.8333)} + + """ + + is_differentiable: bool = False + + def __init__( + self, + task_metrics: dict[str, Union[Metric, MetricCollection]], + prefix: Optional[str] = None, + postfix: Optional[str] = None, + ) -> None: + super().__init__() + + if not isinstance(task_metrics, dict): + raise TypeError(f"Expected argument `task_metrics` to be a dict. Found task_metrics = {task_metrics}") + + for metric in task_metrics.values(): + if not (isinstance(metric, (Metric, MetricCollection))): + raise TypeError( + "Expected each task's metric to be a Metric or a MetricCollection. " + f"Found a metric of type {type(metric)}" + ) + + self.task_metrics = nn.ModuleDict(task_metrics) + + if prefix is not None and not isinstance(prefix, str): + raise ValueError(f"Expected argument `prefix` to either be `None` or a string but got {prefix}") + self._prefix = prefix or "" + + if postfix is not None and not isinstance(postfix, str): + raise ValueError(f"Expected argument `postfix` to either be `None` or a string but got {postfix}") + self._postfix = postfix or "" + + def items(self, flatten: bool = True) -> Iterable[tuple[str, nn.Module]]: + """Iterate over task and task metrics. + + Args: + flatten: If True, will iterate over all sub-metrics in the case of a MetricCollection. + If False, will iterate over the task names and the corresponding metrics. + + """ + for task_name, metric in self.task_metrics.items(): + if flatten and isinstance(metric, MetricCollection): + for sub_metric_name, sub_metric in metric.items(): + yield f"{self._prefix}{task_name}_{sub_metric_name}{self._postfix}", sub_metric + else: + yield f"{self._prefix}{task_name}{self._postfix}", metric + + def keys(self, flatten: bool = True) -> Iterable[str]: + """Iterate over task names. + + Args: + flatten: If True, will iterate over all sub-metrics in the case of a MetricCollection. + If False, will iterate over the task names and the corresponding metrics. + + """ + for task_name, metric in self.task_metrics.items(): + if flatten and isinstance(metric, MetricCollection): + for sub_metric_name in metric: + yield f"{self._prefix}{task_name}_{sub_metric_name}{self._postfix}" + else: + yield f"{self._prefix}{task_name}{self._postfix}" + + def values(self, flatten: bool = True) -> Iterable[nn.Module]: + """Iterate over task metrics. + + Args: + flatten: If True, will iterate over all sub-metrics in the case of a MetricCollection. + If False, will iterate over the task names and the corresponding metrics. + + """ + for metric in self.task_metrics.values(): + if flatten and isinstance(metric, MetricCollection): + yield from metric.values() + else: + yield metric + + def update(self, task_preds: dict[str, Any], task_targets: dict[str, Any]) -> None: + """Update each task's metric with its corresponding pred and target. + + Args: + task_preds: Dictionary associating each task to a Tensor of pred. + task_targets: Dictionary associating each task to a Tensor of target. + + """ + if not self.task_metrics.keys() == task_preds.keys() == task_targets.keys(): + raise ValueError( + "Expected arguments `task_preds` and `task_targets` to have the same keys as the wrapped `task_metrics`" + f". Found task_preds.keys() = {task_preds.keys()}, task_targets.keys() = {task_targets.keys()} " + f"and self.task_metrics.keys() = {self.task_metrics.keys()}" + ) + + for task_name, metric in self.task_metrics.items(): + pred = task_preds[task_name] + target = task_targets[task_name] + if not (isinstance(metric, (Metric, MetricCollection))): + raise TypeError( + "Expected each task's metric to be a Metric or a MetricCollection. " + f"Found a metric of type {type(metric)}" + ) + metric.update(pred, target) + + def _convert_output(self, output: dict[str, Any]) -> dict[str, Any]: + """Convert the output of the underlying metrics to a dictionary with the task names as keys.""" + return {f"{self._prefix}{task_name}{self._postfix}": task_output for task_name, task_output in output.items()} + + def compute(self) -> dict[str, Any]: + """Compute metrics for all tasks.""" + output: dict[str, Any] = {} + for task_name, metric in self.task_metrics.items(): + if not isinstance(metric, (Metric, MetricCollection)): + raise TypeError( + "Expected each task's metric to be a Metric or a MetricCollection. " + f"Found a metric of type {type(metric)}" + ) + output[task_name] = metric.compute() + return self._convert_output(output) + + def forward(self, task_preds: dict[str, Tensor], task_targets: dict[str, Tensor]) -> dict[str, Any]: + """Call underlying forward methods for all tasks and return the result as a dictionary.""" + # This method is overridden because we do not need the complex version defined in Metric, that relies on the + # value of full_state_update, and that also accumulates the results. Here, all computations are handled by the + # underlying metrics, which all have their own value of full_state_update, and which all accumulate the results + # by themselves. + return self._convert_output({ + task_name: metric(task_preds[task_name], task_targets[task_name]) + for task_name, metric in self.task_metrics.items() + }) + + def reset(self) -> None: + """Reset all underlying metrics.""" + for metric in self.task_metrics.values(): + if not isinstance(metric, (Metric, MetricCollection)): + raise TypeError( + "Expected each task's metric to be a Metric or a MetricCollection. " + f"Found a metric of type {type(metric)}" + ) + metric.reset() + super().reset() + + @staticmethod + def _check_arg(arg: Optional[str], name: str) -> Optional[str]: + if arg is None or isinstance(arg, str): + return arg + raise ValueError(f"Expected input `{name}` to be a string, but got {type(arg)}") + + def clone(self, prefix: Optional[str] = None, postfix: Optional[str] = None) -> "MultitaskWrapper": + """Make a copy of the metric. + + Args: + prefix: a string to append in front of the metric keys + postfix: a string to append after the keys of the output dict. + + """ + multitask_copy = deepcopy(self) + multitask_copy._prefix = self._check_arg(prefix, "prefix") or "" + multitask_copy._postfix = self._check_arg(postfix, "prefix") or "" + return multitask_copy + + def plot( + self, val: Optional[Union[dict, Sequence[dict]]] = None, axes: Optional[Sequence[_AX_TYPE]] = None + ) -> Sequence[_PLOT_OUT_TYPE]: + """Plot a single or multiple values from the metric. + + All tasks' results are plotted on individual axes. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + axes: Sequence of matplotlib axis objects. If provided, will add the plots to the provided axis objects. + If not provided, will create them. + + Returns: + Sequence of tuples with Figure and Axes object for each task. + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.wrappers import MultitaskWrapper + >>> from torchmetrics.regression import MeanSquaredError + >>> from torchmetrics.classification import BinaryAccuracy + >>> + >>> classification_target = torch.tensor([0, 1, 0]) + >>> regression_target = torch.tensor([2.5, 5.0, 4.0]) + >>> targets = {"Classification": classification_target, "Regression": regression_target} + >>> + >>> classification_preds = torch.tensor([0, 0, 1]) + >>> regression_preds = torch.tensor([3.0, 5.0, 2.5]) + >>> preds = {"Classification": classification_preds, "Regression": regression_preds} + >>> + >>> metrics = MultitaskWrapper({ + ... "Classification": BinaryAccuracy(), + ... "Regression": MeanSquaredError() + ... }) + >>> metrics.update(preds, targets) + >>> value = metrics.compute() + >>> fig_, ax_ = metrics.plot(value) + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.wrappers import MultitaskWrapper + >>> from torchmetrics.regression import MeanSquaredError + >>> from torchmetrics.classification import BinaryAccuracy + >>> + >>> classification_target = torch.tensor([0, 1, 0]) + >>> regression_target = torch.tensor([2.5, 5.0, 4.0]) + >>> targets = {"Classification": classification_target, "Regression": regression_target} + >>> + >>> classification_preds = torch.tensor([0, 0, 1]) + >>> regression_preds = torch.tensor([3.0, 5.0, 2.5]) + >>> preds = {"Classification": classification_preds, "Regression": regression_preds} + >>> + >>> metrics = MultitaskWrapper({ + ... "Classification": BinaryAccuracy(), + ... "Regression": MeanSquaredError() + ... }) + >>> values = [] + >>> for _ in range(10): + ... values.append(metrics(preds, targets)) + >>> fig_, ax_ = metrics.plot(values) + + """ + if axes is not None: + if not isinstance(axes, Sequence): + raise TypeError(f"Expected argument `axes` to be a Sequence. Found type(axes) = {type(axes)}") + + if not all(isinstance(ax, _AX_TYPE) for ax in axes): + raise TypeError("Expected each ax in argument `axes` to be a matplotlib axis object") + + if len(axes) != len(self.task_metrics): + raise ValueError( + "Expected argument `axes` to be a Sequence of the same length as the number of tasks." + f"Found len(axes) = {len(axes)} and {len(self.task_metrics)} tasks" + ) + + val = val if val is not None else self.compute() + fig_axs = [] + for i, (task_name, task_metric) in enumerate(self.task_metrics.items()): + ax = axes[i] if axes is not None else None + if not isinstance(task_metric, (Metric, MetricCollection)): + raise TypeError( + "Expected each task's metric to be a Metric or a MetricCollection. " + f"Found a metric of type {type(task_metric)}" + ) + if isinstance(val, dict): + f, a = task_metric.plot(val[task_name], ax=ax) + elif isinstance(val, Sequence): + f, a = task_metric.plot([v[task_name] for v in val], ax=ax) + else: + raise TypeError( + "Expected argument `val` to be None or of type Dict or Sequence[Dict]. " + f"Found type(val)= {type(val)}" + ) + fig_axs.append((f, a)) + return fig_axs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/running.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/running.py new file mode 100644 index 0000000000000000000000000000000000000000..a57cb8333f0c906f6814c5407ce3970a17df0c8e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/running.py @@ -0,0 +1,183 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from typing import Any, Optional, Union + +from torch import Tensor + +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE +from torchmetrics.wrappers.abstract import WrapperMetric + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["Running.plot"] + + +class Running(WrapperMetric): + """Running wrapper for metrics. + + Using this wrapper allows for calculating metrics over a running window of values, instead of the whole history of + values. This is beneficial when you want to get a better estimate of the metric during training and don't want to + wait for the whole training to finish to get epoch level estimates. + + The running window is defined by the `window` argument. The window is a fixed size and this wrapper will store a + duplicate of the underlying metric state for each value in the window. Thus memory usage will increase linearly + with window size. Use accordingly. Also note that the running only works with metrics that have the + `full_state_update` set to `False`. + + Importantly, the wrapper does not alter the value of the `forward` method of the underlying metric. Thus, forward + will still return the value on the current batch. To get the running value call `compute` instead. + + Args: + base_metric: The metric to wrap. + window: The size of the running window. + + Example (single metric): + >>> from torch import tensor + >>> from torchmetrics.wrappers import Running + >>> from torchmetrics.aggregation import SumMetric + >>> metric = Running(SumMetric(), window=3) + >>> for i in range(6): + ... current_val = metric(tensor([i])) + ... running_val = metric.compute() + ... total_val = tensor(sum(list(range(i+1)))) # value we would get from `compute` without running + ... print(f"{current_val=}, {running_val=}, {total_val=}") + current_val=tensor(0.), running_val=tensor(0.), total_val=tensor(0) + current_val=tensor(1.), running_val=tensor(1.), total_val=tensor(1) + current_val=tensor(2.), running_val=tensor(3.), total_val=tensor(3) + current_val=tensor(3.), running_val=tensor(6.), total_val=tensor(6) + current_val=tensor(4.), running_val=tensor(9.), total_val=tensor(10) + current_val=tensor(5.), running_val=tensor(12.), total_val=tensor(15) + + Example (metric collection): + >>> from torch import tensor + >>> from torchmetrics.wrappers import Running + >>> from torchmetrics import MetricCollection + >>> from torchmetrics.aggregation import SumMetric, MeanMetric + >>> # note that running is input to collection, not the other way + >>> metric = MetricCollection({"sum": Running(SumMetric(), 3), "mean": Running(MeanMetric(), 3)}) + >>> for i in range(6): + ... current_val = metric(tensor([i])) + ... running_val = metric.compute() + ... print(f"{current_val=}, {running_val=}") + current_val={'mean': tensor(0.), 'sum': tensor(0.)}, running_val={'mean': tensor(0.), 'sum': tensor(0.)} + current_val={'mean': tensor(1.), 'sum': tensor(1.)}, running_val={'mean': tensor(0.5000), 'sum': tensor(1.)} + current_val={'mean': tensor(2.), 'sum': tensor(2.)}, running_val={'mean': tensor(1.), 'sum': tensor(3.)} + current_val={'mean': tensor(3.), 'sum': tensor(3.)}, running_val={'mean': tensor(2.), 'sum': tensor(6.)} + current_val={'mean': tensor(4.), 'sum': tensor(4.)}, running_val={'mean': tensor(3.), 'sum': tensor(9.)} + current_val={'mean': tensor(5.), 'sum': tensor(5.)}, running_val={'mean': tensor(4.), 'sum': tensor(12.)} + + """ + + def __init__(self, base_metric: Metric, window: int = 5) -> None: + super().__init__() + if not isinstance(base_metric, Metric): + raise ValueError( + f"Expected argument `metric` to be an instance of `torchmetrics.Metric` but got {base_metric}" + ) + if not (isinstance(window, int) and window > 0): + raise ValueError(f"Expected argument `window` to be a positive integer but got {window}") + self.base_metric = base_metric + self.window = window + + if base_metric.full_state_update is not False: + raise ValueError( + f"Expected attribute `full_state_update` set to `False` but got {base_metric.full_state_update}" + ) + self._num_vals_seen = 0 + + for key in base_metric._defaults: + for i in range(window): + self.add_state( + name=key + f"_{i}", default=base_metric._defaults[key], dist_reduce_fx=base_metric._reductions[key] + ) + + def update(self, *args: Any, **kwargs: Any) -> None: + """Update the underlying metric and save state afterwards.""" + val = self._num_vals_seen % self.window + self.base_metric.update(*args, **kwargs) + for key in self.base_metric._defaults: + setattr(self, key + f"_{val}", getattr(self.base_metric, key)) + self.base_metric.reset() + self._num_vals_seen += 1 + + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Forward input to the underlying metric and save state afterwards.""" + val = self._num_vals_seen % self.window + res = self.base_metric.forward(*args, **kwargs) + for key in self.base_metric._defaults: + setattr(self, key + f"_{val}", getattr(self.base_metric, key)) + self.base_metric.reset() + self._num_vals_seen += 1 + self._computed = None + return res + + def compute(self) -> Any: + """Compute the metric over the running window.""" + for i in range(self.window): + self.base_metric._reduce_states({key: getattr(self, key + f"_{i}") for key in self.base_metric._defaults}) + self.base_metric._update_count = self._num_vals_seen + val = self.base_metric.compute() + self.base_metric.reset() + return val + + def reset(self) -> None: + """Reset metric.""" + super().reset() + self._num_vals_seen = 0 + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.wrappers import Running + >>> from torchmetrics.aggregation import SumMetric + >>> metric = Running(SumMetric(), 2) + >>> metric.update(torch.randn(20, 2)) + >>> fig_, ax_ = metric.plot() + + .. plot:: + :scale: 75 + + >>> # Example plotting multiple values + >>> import torch + >>> from torchmetrics.wrappers import Running + >>> from torchmetrics.aggregation import SumMetric + >>> metric = Running(SumMetric(), 2) + >>> values = [ ] + >>> for _ in range(3): + ... values.append(metric(torch.randn(20, 2))) + >>> fig_, ax_ = metric.plot(values) + + """ + return self._plot(val, ax) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/tracker.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..f3db3c051765566fdf8b0e2237fbc3985f8e6ac3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/tracker.py @@ -0,0 +1,364 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Sequence +from copy import deepcopy +from typing import Any, Optional, Union, cast + +import torch +from torch import Tensor +from torch.nn import ModuleList + +from torchmetrics.collections import MetricCollection +from torchmetrics.metric import Metric +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE, plot_single_or_multi_val +from torchmetrics.utilities.prints import rank_zero_warn +from torchmetrics.wrappers import ClasswiseWrapper + +if not _MATPLOTLIB_AVAILABLE: + __doctest_skip__ = ["MetricTracker.plot"] + + +class MetricTracker(ModuleList): + """A wrapper class that can help keeping track of a metric or metric collection over time. + + The wrapper implements the standard ``.update()``, ``.compute()``, ``.reset()`` methods that just + calls corresponding method of the currently tracked metric. However, the following additional methods are + provided: + + -``MetricTracker.n_steps``: number of metrics being tracked + -``MetricTracker.increment()``: initialize a new metric for being tracked + -``MetricTracker.compute_all()``: get the metric value for all steps + -``MetricTracker.best_metric()``: returns the best value + + Out of the box, this wrapper class fully supports that the base metric being tracked is a single `Metric`, a + `MetricCollection` or another `MetricWrapper` wrapped around a metric. However, multiple layers of nesting, such + as using a `Metric` inside a `MetricWrapper` inside a `MetricCollection` is not fully supported, especially the + `.best_metric` method that cannot auto compute the best metric and index for such nested structures. + + Args: + metric: instance of a ``torchmetrics.Metric`` or ``torchmetrics.MetricCollection`` + to keep track of at each timestep. + maximize: either single bool or list of bool indicating if higher metric values are + better (``True``) or lower is better (``False``). + + Example (single metric): + >>> from torch import randint + >>> from torchmetrics.wrappers import MetricTracker + >>> from torchmetrics.classification import MulticlassAccuracy + >>> tracker = MetricTracker(MulticlassAccuracy(num_classes=10, average='micro')) + >>> for epoch in range(5): + ... tracker.increment() + ... for batch_idx in range(5): + ... tracker.update(randint(10, (100,)), randint(10, (100,))) + ... print(f"current acc={tracker.compute()}") + current acc=0.1120000034570694 + current acc=0.08799999952316284 + current acc=0.12600000202655792 + current acc=0.07999999821186066 + current acc=0.10199999809265137 + >>> best_acc, which_epoch = tracker.best_metric(return_step=True) + >>> best_acc # doctest: +ELLIPSIS + 0.1260... + >>> which_epoch + 2 + >>> tracker.compute_all() + tensor([0.1120, 0.0880, 0.1260, 0.0800, 0.1020]) + + Example (multiple metrics using MetricCollection): + >>> from torch import randn + >>> from torchmetrics.wrappers import MetricTracker + >>> from torchmetrics import MetricCollection + >>> from torchmetrics.regression import MeanSquaredError, ExplainedVariance + >>> tracker = MetricTracker(MetricCollection([MeanSquaredError(), ExplainedVariance()]), maximize=[False, True]) + >>> for epoch in range(5): + ... tracker.increment() + ... for batch_idx in range(5): + ... tracker.update(randn(100), randn(100)) + ... print(f"current stats={tracker.compute()}") # doctest: +NORMALIZE_WHITESPACE + current stats={'MeanSquaredError': tensor(2.3292), 'ExplainedVariance': tensor(-0.9516)} + current stats={'MeanSquaredError': tensor(2.1370), 'ExplainedVariance': tensor(-1.0775)} + current stats={'MeanSquaredError': tensor(2.1695), 'ExplainedVariance': tensor(-0.9945)} + current stats={'MeanSquaredError': tensor(2.1072), 'ExplainedVariance': tensor(-1.1878)} + current stats={'MeanSquaredError': tensor(2.0562), 'ExplainedVariance': tensor(-1.0754)} + >>> from pprint import pprint + >>> best_res, which_epoch = tracker.best_metric(return_step=True) + >>> pprint(best_res) # doctest: +ELLIPSIS + {'ExplainedVariance': -0.951..., + 'MeanSquaredError': 2.056...} + >>> which_epoch + {'MeanSquaredError': 4, 'ExplainedVariance': 0} + >>> pprint(tracker.compute_all()) + {'ExplainedVariance': tensor([-0.9516, -1.0775, -0.9945, -1.1878, -1.0754]), + 'MeanSquaredError': tensor([2.3292, 2.1370, 2.1695, 2.1072, 2.0562])} + + """ + + maximize: Union[bool, list[bool]] + _base_metric: Union[Metric, MetricCollection] + + def __init__(self, metric: Union[Metric, MetricCollection], maximize: Union[bool, list[bool], None] = None) -> None: + super().__init__() + if not isinstance(metric, (Metric, MetricCollection)): + raise TypeError( + f"Metric arg need to be an instance of a torchmetrics `Metric` or `MetricCollection` but got {metric}" + ) + self._base_metric = metric + + if maximize is None: + if isinstance(metric, Metric): + if getattr(metric, "higher_is_better", None) is None: + raise AttributeError( + f"The metric '{metric.__class__.__name__}' does not have a 'higher_is_better' attribute." + " Please provide the `maximize` argument explicitly." + ) + self.maximize = metric.higher_is_better # type: ignore[assignment] # this is false alarm + elif isinstance(metric, MetricCollection): + self.maximize = [] + for name, m in metric.items(): + if getattr(m, "higher_is_better", None) is None: + raise AttributeError( + f"The metric '{name}' in the MetricCollection does not have a 'higher_is_better' attribute." + " Please provide the `maximize` argument explicitly." + ) + if isinstance(m, ClasswiseWrapper) and isinstance(m.metric.num_classes, int): + m_higher_is_better = [m.higher_is_better for _ in range(int(m.metric.num_classes))] + else: + m_higher_is_better = [m.higher_is_better] + self.maximize.extend(m_higher_is_better) # type: ignore[arg-type] # this is false alarm + else: + # The default value for `maximize` has be changed from `True` to `None` in v1.7.0 of TorchMetrics, + # will automatically infer the value based on the `higher_is_better` attribute of the metric + # (if such attribute exists) or raise an error if it does not. If you are explicitly setting the + # `maximize` argument to either `True` or `False` already, you can ignore this warning. + if not isinstance(maximize, (bool, list)): + raise ValueError("Argument `maximize` should either be a single bool or list of bool") + if isinstance(maximize, list) and not all(isinstance(m, bool) for m in maximize): + raise ValueError("Argument `maximize` is list but not type of bool.") + if isinstance(maximize, list) and isinstance(metric, MetricCollection) and len(maximize) != len(metric): + raise ValueError("The len of argument `maximize` should match the length of the metric collection") + if isinstance(metric, Metric) and not isinstance(maximize, bool): + raise ValueError("Argument `maximize` should be a single bool when `metric` is a single Metric") + self.maximize = maximize + + self._increment_called = False + + @property + def n_steps(self) -> int: + """Returns the number of times the tracker has been incremented.""" + return len(self) - 1 # subtract the base metric + + def increment(self) -> None: + """Create a new instance of the input metric that will be updated next.""" + self._increment_called = True + self.append(deepcopy(self._base_metric)) + + def forward(self, *args: Any, **kwargs: Any) -> None: + """Call forward of the current metric being tracked.""" + self._check_for_increment("forward") + if not isinstance(self[-1], (Metric, MetricCollection)): + raise TypeError(f"Expected the last item to be a Metric or MetricCollection, but got {type(self[-1])}.") + return self[-1](*args, **kwargs) + + def update(self, *args: Any, **kwargs: Any) -> None: + """Update the current metric being tracked.""" + self._check_for_increment("update") + if not isinstance(self[-1], (Metric, MetricCollection)): + raise TypeError(f"Expected the last item to be a Metric or MetricCollection, but got {type(self[-1])}.") + self[-1].update(*args, **kwargs) + + def compute(self) -> Any: + """Call compute of the current metric being tracked.""" + self._check_for_increment("compute") + if not isinstance(self[-1], (Metric, MetricCollection)): + raise TypeError(f"Expected the last item to be a Metric or MetricCollection, but got {type(self[-1])}.") + return self[-1].compute() + + def compute_all(self) -> Any: + """Compute the metric value for all tracked metrics. + + Return: + By default will try stacking the results from all increments into a single tensor if the tracked base + object is a single metric. If a metric collection is provided a dict of stacked tensors will be returned. + If the stacking process fails a list of the computed results will be returned. + + Raises: + ValueError: + If `self.increment` have not been called before this method is called. + + """ + self._check_for_increment("compute_all") + # The i!=0 accounts for the self._base_metric should be ignored + res: list[Any] = [] + for i, metric in enumerate(self): + if i == 0: + continue + if not isinstance(metric, (Metric, MetricCollection)): + raise TypeError(f"Expected the item to be a Metric or MetricCollection, but got {type(metric)}.") + res.append(metric.compute()) + + try: + if isinstance(res[0], dict): + keys = res[0].keys() + return {k: torch.stack([cast(Tensor, r[k]) for r in res], dim=0) for k in keys} + + if isinstance(res[0], list): + return torch.stack([torch.stack(cast(list[Tensor], r), dim=0) for r in res], dim=0) + + return torch.stack(cast(list[Tensor], res), dim=0) + + except TypeError: # fallback solution to just return as it is if we cannot successfully stack + return res + return res + + def reset(self) -> None: + """Reset the current metric being tracked.""" + if not isinstance(self[-1], (Metric, MetricCollection)): + raise TypeError(f"Expected the last item to be a Metric or MetricCollection, but got {type(self[-1])}.") + self[-1].reset() + + def reset_all(self) -> None: + """Reset all metrics being tracked.""" + for metric in self: + if not isinstance(metric, (Metric, MetricCollection)): + raise TypeError(f"Expected all metrics to be Metric or MetricCollection, but got {type(metric)}.") + metric.reset() + + def best_metric( + self, return_step: bool = False + ) -> Union[ + None, + float, + Tensor, + tuple[Union[int, float, Tensor], Union[int, float, Tensor]], + tuple[None, None], + dict[str, Union[float, None]], + tuple[dict[str, Union[float, None]], dict[str, Union[int, None]]], + ]: + """Return the highest metric out of all tracked. + + Args: + return_step: If ``True`` will also return the step with the highest metric value. + + Returns: + Either a single value or a tuple, depends on the value of ``return_step`` and the object being tracked. + + - If a single metric is being tracked and ``return_step=False`` then a single tensor will be returned + - If a single metric is being tracked and ``return_step=True`` then a 2-element tuple will be returned, + where the first value is optimal value and second value is the corresponding optimal step + - If a metric collection is being tracked and ``return_step=False`` then a single dict will be returned, + where keys correspond to the different values of the collection and the values are the optimal metric + value + - If a metric collection is being bracked and ``return_step=True`` then a 2-element tuple will be returned + where each is a dict, with keys corresponding to the different values of th collection and the values + of the first dict being the optimal values and the values of the second dict being the optimal step + + In addition the value in all cases may be ``None`` if the underlying metric does have a proper defined way + of being optimal or in the case where a nested structure of metrics are being tracked. + + """ + res = self.compute_all() + if isinstance(res, list): + rank_zero_warn( + "Encountered nested structure. You are probably using a metric collection inside a metric collection," + " or a metric wrapper inside a metric collection, which is not supported by `.best_metric()` method." + " Returning `None` instead." + ) + if return_step: + return None, None + return None + + if isinstance(self._base_metric, Metric) and not isinstance(self._base_metric, ClasswiseWrapper): + fn = torch.max if self.maximize else torch.min + try: + value, idx = fn(res, 0) + if return_step: + return value.item(), idx.item() + return value.item() + except (ValueError, RuntimeError) as error: + rank_zero_warn( + f"Encountered the following error when trying to get the best metric: {error}" + "this is probably due to the 'best' not being defined for this metric." + "Returning `None` instead.", + UserWarning, + ) + if return_step: + return None, None + return None + + else: # this is a metric collection + maximize = self.maximize if isinstance(self.maximize, list) else len(res) * [self.maximize] + value, idx = {}, {} # type: ignore[assignment] + for i, (k, v) in enumerate(res.items()): + try: + fn = torch.max if maximize[i] else torch.min + out = fn(v, 0) + value[k], idx[k] = out[0].item(), out[1].item() + except (ValueError, RuntimeError) as error: # noqa: PERF203 # todo + rank_zero_warn( + f"Encountered the following error when trying to get the best metric for metric {k}:" + f"{error} this is probably due to the 'best' not being defined for this metric." + "Returning `None` instead.", + UserWarning, + ) + value[k], idx[k] = None, None # type: ignore[assignment] + + if return_step: + return value, idx + return value + + def _check_for_increment(self, method: str) -> None: + """Check that a metric that can be updated/used for computations has been initialized.""" + if not self._increment_called: + raise ValueError(f"`{method}` cannot be called before `.increment()` has been called.") + + def plot( + self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None + ) -> _PLOT_OUT_TYPE: + """Plot a single or multiple values from the metric. + + Args: + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. + If no value is provided, will automatically call `metric.compute` and plot that result. + ax: An matplotlib axis object. If provided will add plot to that axis + + Returns: + Figure and Axes object + + Raises: + ModuleNotFoundError: + If `matplotlib` is not installed + + .. plot:: + :scale: 75 + + >>> # Example plotting a single value + >>> import torch + >>> from torchmetrics.wrappers import MetricTracker + >>> from torchmetrics.classification import BinaryAccuracy + >>> tracker = MetricTracker(BinaryAccuracy(), maximize=True) + >>> for epoch in range(5): + ... tracker.increment() + ... for batch_idx in range(5): + ... tracker.update(torch.randint(2, (10,)), torch.randint(2, (10,))) + >>> fig_, ax_ = tracker.plot() # plot all epochs + + """ + val = val if val is not None else self.compute_all() + fig, ax = plot_single_or_multi_val( + val, + ax=ax, + name=self.__class__.__name__, + ) + return fig, ax diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/transformations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/transformations.py new file mode 100644 index 0000000000000000000000000000000000000000..835769c1884d10da0e574cb7eed25a874e90816a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/wrappers/transformations.py @@ -0,0 +1,180 @@ +# Copyright The Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Callable, Optional, Union + +import torch + +from torchmetrics.collections import MetricCollection +from torchmetrics.metric import Metric +from torchmetrics.wrappers.abstract import WrapperMetric + + +class MetricInputTransformer(WrapperMetric): + """Abstract base class for metric input transformations. + + Input transformations are characterized by them applying a transformation to the input data of a metric, and then + forwarding all calls to the wrapped metric with modifications applied. + + """ + + def __init__(self, wrapped_metric: Union[Metric, MetricCollection], **kwargs: dict[str, Any]) -> None: + super().__init__(**kwargs) + if not isinstance(wrapped_metric, (Metric, MetricCollection)): + raise TypeError( + f"Expected wrapped metric to be an instance of `torchmetrics.Metric` or " + f"`torchmetrics.MetricsCollection`but received {wrapped_metric}" + ) + self.wrapped_metric = wrapped_metric + + def transform_pred(self, pred: torch.Tensor) -> torch.Tensor: + """Define transform operations on the prediction data. + + Overridden by subclasses. Identity by default. + + """ + return pred + + def transform_target(self, target: torch.Tensor) -> torch.Tensor: + """Define transform operations on the target data. + + Overridden by subclasses. Identity by default. + + """ + return target + + def _wrap_transform(self, *args: torch.Tensor) -> tuple[torch.Tensor, ...]: + """Wrap transformation functions to dispatch args to their individual transform functions.""" + if len(args) == 1: + return (self.transform_pred(args[0]),) + if len(args) == 2: + return self.transform_pred(args[0]), self.transform_target(args[1]) + return self.transform_pred(args[0]), self.transform_target(args[1]), *args[2:] + + def update(self, *args: torch.Tensor, **kwargs: dict[str, Any]) -> None: + """Wrap the update call of the underlying metric.""" + args = self._wrap_transform(*args) + self.wrapped_metric.update(*args, **kwargs) + + def compute(self) -> Any: + """Wrap the compute call of the underlying metric.""" + return self.wrapped_metric.compute() + + def forward(self, *args: torch.Tensor, **kwargs: dict[str, Any]) -> Any: + """Wrap the forward call of the underlying metric.""" + args = self._wrap_transform(*args) + return self.wrapped_metric.forward(*args, **kwargs) + + def reset(self) -> None: + """Wrap the reset call of the underlying metric.""" + self.wrapped_metric.reset() + super().reset() + + +class LambdaInputTransformer(MetricInputTransformer): + """Wrapper class for transforming a metrics' inputs given a user-defined lambda function. + + Args: + wrapped_metric: + The underlying `Metric` or `MetricCollection`. + transform_pred: + The function to apply to the predictions before computing the metric. + transform_target: + The function to apply to the target before computing the metric. + + Raises: + TypeError: + If `transform_pred` is not a Callable. + TypeError: + If `transform_target` is not a Callable. + + Example: + >>> import torch + >>> from torchmetrics.classification import BinaryAccuracy + >>> from torchmetrics.wrappers import LambdaInputTransformer + >>> + >>> preds = torch.tensor([0.9, 0.8, 0.7, 0.6, 0.5, 0.6, 0.7, 0.8, 0.5, 0.4]) + >>> targets = torch.tensor([1,0,0,0,0,1,1,0,0,0]) + >>> + >>> metric = LambdaInputTransformer(BinaryAccuracy(), lambda preds: 1 - preds) + >>> metric.update(preds, targets) + >>> metric.compute() + tensor(0.6000) + + """ + + def __init__( + self, + wrapped_metric: Metric, + transform_pred: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, + transform_target: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, + **kwargs: Any, + ) -> None: + super().__init__(wrapped_metric, **kwargs) + if transform_pred is not None: + if not callable(transform_pred): + raise TypeError(f"Expected `transform_pred` to be of type `Callable` but received `{transform_pred}`") + self.transform_pred = transform_pred # type: ignore[assignment,method-assign] + + if transform_target is not None: + if not callable(transform_target): + raise TypeError( + f"Expected `transform_target` to be of type `Callable` but received `{transform_target}`" + ) + self.transform_target = transform_target # type: ignore[assignment,method-assign] + + +class BinaryTargetTransformer(MetricInputTransformer): + """Wrapper class for computing a metric on binarized targets. + + Useful when the given ground-truth targets are continuous, but the metric requires binary targets. + + Args: + wrapped_metric: + The underlying `Metric` or `MetricCollection`. + threshold: + The binarization threshold for the targets. Targets values `t` are cast to binary with `t > threshold`. + + Raises: + TypeError: + If `threshold` is not an `int` or `float`. + + Example: + >>> import torch + >>> from torchmetrics.retrieval import RetrievalMRR + >>> from torchmetrics.wrappers import BinaryTargetTransformer + >>> + >>> preds = torch.tensor([0.9, 0.8, 0.7, 0.6, 0.5, 0.6, 0.7, 0.8, 0.5, 0.4]) + >>> targets = torch.tensor([1,0,0,0,0,2,1,0,0,0]) + >>> topics = torch.tensor([0,0,0,0,0,1,1,1,1,1]) + >>> + >>> metric = BinaryTargetTransformer(RetrievalMRR()) + >>> metric.update(preds, targets, indexes=topics) + >>> metric.compute() + tensor(0.7500) + + """ + + def __init__(self, wrapped_metric: Union[Metric, MetricCollection], threshold: float = 0, **kwargs: Any) -> None: + super().__init__(wrapped_metric, **kwargs) + if not isinstance(threshold, (int, float)): + raise TypeError(f"Expected `threshold` to be of type `int` or `float` but received `{threshold}`") + self.threshold = threshold + + def transform_target(self, target: torch.Tensor) -> torch.Tensor: + """Cast the target tensor to binary values according to the threshold. + + Output assumes same type as input. + + """ + return target.gt(self.threshold).to(target.dtype) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d06156c25f1dfd34e9f01529e5a6b4bbeda7b42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/__init__.py @@ -0,0 +1,105 @@ +import os +import warnings +from modulefinder import Module + +import torch + +# Don't re-order these, we need to load the _C extension (done when importing +# .extensions) before entering _meta_registrations. +from .extension import _HAS_OPS # usort:skip +from torchvision import _meta_registrations, datasets, io, models, ops, transforms, utils # usort:skip + +try: + from .version import __version__ # noqa: F401 +except ImportError: + pass + + +# Check if torchvision is being imported within the root folder +if not _HAS_OPS and os.path.dirname(os.path.realpath(__file__)) == os.path.join( + os.path.realpath(os.getcwd()), "torchvision" +): + message = ( + "You are importing torchvision within its own root folder ({}). " + "This is not expected to work and may give errors. Please exit the " + "torchvision project source and relaunch your python interpreter." + ) + warnings.warn(message.format(os.getcwd())) + +_image_backend = "PIL" + +_video_backend = "pyav" + + +def set_image_backend(backend): + """ + Specifies the package used to load images. + + Args: + backend (string): Name of the image backend. one of {'PIL', 'accimage'}. + The :mod:`accimage` package uses the Intel IPP library. It is + generally faster than PIL, but does not support as many operations. + """ + global _image_backend + if backend not in ["PIL", "accimage"]: + raise ValueError(f"Invalid backend '{backend}'. Options are 'PIL' and 'accimage'") + _image_backend = backend + + +def get_image_backend(): + """ + Gets the name of the package used to load images + """ + return _image_backend + + +def set_video_backend(backend): + """ + Specifies the package used to decode videos. + + Args: + backend (string): Name of the video backend. one of {'pyav', 'video_reader'}. + The :mod:`pyav` package uses the 3rd party PyAv library. It is a Pythonic + binding for the FFmpeg libraries. + The :mod:`video_reader` package includes a native C++ implementation on + top of FFMPEG libraries, and a python API of TorchScript custom operator. + It generally decodes faster than :mod:`pyav`, but is perhaps less robust. + + .. note:: + Building with FFMPEG is disabled by default in the latest `main`. If you want to use the 'video_reader' + backend, please compile torchvision from source. + """ + global _video_backend + if backend not in ["pyav", "video_reader", "cuda"]: + raise ValueError("Invalid video backend '%s'. Options are 'pyav', 'video_reader' and 'cuda'" % backend) + if backend == "video_reader" and not io._HAS_CPU_VIDEO_DECODER: + # TODO: better messages + message = "video_reader video backend is not available. Please compile torchvision from source and try again" + raise RuntimeError(message) + elif backend == "cuda" and not io._HAS_GPU_VIDEO_DECODER: + # TODO: better messages + message = "cuda video backend is not available." + raise RuntimeError(message) + else: + _video_backend = backend + + +def get_video_backend(): + """ + Returns the currently active video backend used to decode videos. + + Returns: + str: Name of the video backend. one of {'pyav', 'video_reader'}. + """ + + return _video_backend + + +def _is_tracing(): + return torch._C._get_tracing_state() + + +def disable_beta_transforms_warning(): + # Noop, only exists to avoid breaking existing code. + # See https://github.com/pytorch/vision/issues/7896 + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_internally_replaced_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_internally_replaced_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e0fa72489f1ac8fba771fc7bc20fc80424a71d85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_internally_replaced_utils.py @@ -0,0 +1,51 @@ +import importlib.machinery +import os + +from torch.hub import _get_torch_home + + +_HOME = os.path.join(_get_torch_home(), "datasets", "vision") +_USE_SHARDED_DATASETS = False +IN_FBCODE = False + + +def _download_file_from_remote_location(fpath: str, url: str) -> None: + pass + + +def _is_remote_location_available() -> bool: + return False + + +try: + from torch.hub import load_state_dict_from_url # noqa: 401 +except ImportError: + from torch.utils.model_zoo import load_url as load_state_dict_from_url # noqa: 401 + + +def _get_extension_path(lib_name): + + lib_dir = os.path.dirname(__file__) + if os.name == "nt": + # Register the main torchvision library location on the default DLL path + import ctypes + + kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True) + with_load_library_flags = hasattr(kernel32, "AddDllDirectory") + prev_error_mode = kernel32.SetErrorMode(0x0001) + + if with_load_library_flags: + kernel32.AddDllDirectory.restype = ctypes.c_void_p + + os.add_dll_directory(lib_dir) + + kernel32.SetErrorMode(prev_error_mode) + + loader_details = (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES) + + extfinder = importlib.machinery.FileFinder(lib_dir, loader_details) + ext_specs = extfinder.find_spec(lib_name) + if ext_specs is None: + raise ImportError + + return ext_specs.origin diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_meta_registrations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_meta_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..f75bfb77a7f25a1842509de595f109f232994574 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_meta_registrations.py @@ -0,0 +1,225 @@ +import functools + +import torch +import torch._custom_ops +import torch.library + +# Ensure that torch.ops.torchvision is visible +import torchvision.extension # noqa: F401 + + +@functools.lru_cache(None) +def get_meta_lib(): + return torch.library.Library("torchvision", "IMPL", "Meta") + + +def register_meta(op_name, overload_name="default"): + def wrapper(fn): + if torchvision.extension._has_ops(): + get_meta_lib().impl(getattr(getattr(torch.ops.torchvision, op_name), overload_name), fn) + return fn + + return wrapper + + +@register_meta("roi_align") +def meta_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + num_rois = rois.size(0) + channels = input.size(1) + return input.new_empty((num_rois, channels, pooled_height, pooled_width)) + + +@register_meta("_roi_align_backward") +def meta_roi_align_backward( + grad, rois, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width, sampling_ratio, aligned +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@register_meta("ps_roi_align") +def meta_ps_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + channels = input.size(1) + torch._check( + channels % (pooled_height * pooled_width) == 0, + "input channels must be a multiple of pooling height * pooling width", + ) + + num_rois = rois.size(0) + out_size = (num_rois, channels // (pooled_height * pooled_width), pooled_height, pooled_width) + return input.new_empty(out_size), torch.empty(out_size, dtype=torch.int32, device="meta") + + +@register_meta("_ps_roi_align_backward") +def meta_ps_roi_align_backward( + grad, + rois, + channel_mapping, + spatial_scale, + pooled_height, + pooled_width, + sampling_ratio, + batch_size, + channels, + height, + width, +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@register_meta("roi_pool") +def meta_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + num_rois = rois.size(0) + channels = input.size(1) + out_size = (num_rois, channels, pooled_height, pooled_width) + return input.new_empty(out_size), torch.empty(out_size, device="meta", dtype=torch.int32) + + +@register_meta("_roi_pool_backward") +def meta_roi_pool_backward( + grad, rois, argmax, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@register_meta("ps_roi_pool") +def meta_ps_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + channels = input.size(1) + torch._check( + channels % (pooled_height * pooled_width) == 0, + "input channels must be a multiple of pooling height * pooling width", + ) + num_rois = rois.size(0) + out_size = (num_rois, channels // (pooled_height * pooled_width), pooled_height, pooled_width) + return input.new_empty(out_size), torch.empty(out_size, device="meta", dtype=torch.int32) + + +@register_meta("_ps_roi_pool_backward") +def meta_ps_roi_pool_backward( + grad, rois, channel_mapping, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@torch.library.register_fake("torchvision::nms") +def meta_nms(dets, scores, iou_threshold): + torch._check(dets.dim() == 2, lambda: f"boxes should be a 2d tensor, got {dets.dim()}D") + torch._check(dets.size(1) == 4, lambda: f"boxes should have 4 elements in dimension 1, got {dets.size(1)}") + torch._check(scores.dim() == 1, lambda: f"scores should be a 1d tensor, got {scores.dim()}") + torch._check( + dets.size(0) == scores.size(0), + lambda: f"boxes and scores should have same number of elements in dimension 0, got {dets.size(0)} and {scores.size(0)}", + ) + ctx = torch._custom_ops.get_ctx() + num_to_keep = ctx.create_unbacked_symint() + return dets.new_empty(num_to_keep, dtype=torch.long) + + +@register_meta("deform_conv2d") +def meta_deform_conv2d( + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dil_h, + dil_w, + n_weight_grps, + n_offset_grps, + use_mask, +): + + out_height, out_width = offset.shape[-2:] + out_channels = weight.shape[0] + batch_size = input.shape[0] + return input.new_empty((batch_size, out_channels, out_height, out_width)) + + +@register_meta("_deform_conv2d_backward") +def meta_deform_conv2d_backward( + grad, + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dilation_h, + dilation_w, + groups, + offset_groups, + use_mask, +): + + grad_input = input.new_empty(input.shape) + grad_weight = weight.new_empty(weight.shape) + grad_offset = offset.new_empty(offset.shape) + grad_mask = mask.new_empty(mask.shape) + grad_bias = bias.new_empty(bias.shape) + return grad_input, grad_weight, grad_offset, grad_mask, grad_bias diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aee2676df45d1fa3ade4fc31e3890c9d36600fc7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/_utils.py @@ -0,0 +1,33 @@ +import enum +from collections.abc import Sequence +from typing import TypeVar + +T = TypeVar("T", bound=enum.Enum) + + +class StrEnumMeta(enum.EnumMeta): + auto = enum.auto + + def from_str(self: type[T], member: str) -> T: # type: ignore[misc] + try: + return self[member] + except KeyError: + # TODO: use `add_suggestion` from torchvision.prototype.utils._internal to improve the error message as + # soon as it is migrated. + raise ValueError(f"Unknown value '{member}' for {self.__name__}.") from None + + +class StrEnum(enum.Enum, metaclass=StrEnumMeta): + pass + + +def sequence_to_str(seq: Sequence, separate_last: str = "") -> str: + if not seq: + return "" + if len(seq) == 1: + return f"'{seq[0]}'" + + head = "'" + "', '".join([str(item) for item in seq[:-1]]) + "'" + tail = f"{'' if separate_last and len(seq) == 2 else ','} {separate_last}'{seq[-1]}'" + + return head + tail diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4005b4a90729c9fe1b811f7388bd8453998d2322 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/__init__.py @@ -0,0 +1,147 @@ +from ._optical_flow import FlyingChairs, FlyingThings3D, HD1K, KittiFlow, Sintel +from ._stereo_matching import ( + CarlaStereo, + CREStereo, + ETH3DStereo, + FallingThingsStereo, + InStereo2k, + Kitti2012Stereo, + Kitti2015Stereo, + Middlebury2014Stereo, + SceneFlowStereo, + SintelStereo, +) +from .caltech import Caltech101, Caltech256 +from .celeba import CelebA +from .cifar import CIFAR10, CIFAR100 +from .cityscapes import Cityscapes +from .clevr import CLEVRClassification +from .coco import CocoCaptions, CocoDetection +from .country211 import Country211 +from .dtd import DTD +from .eurosat import EuroSAT +from .fakedata import FakeData +from .fer2013 import FER2013 +from .fgvc_aircraft import FGVCAircraft +from .flickr import Flickr30k, Flickr8k +from .flowers102 import Flowers102 +from .folder import DatasetFolder, ImageFolder +from .food101 import Food101 +from .gtsrb import GTSRB +from .hmdb51 import HMDB51 +from .imagenet import ImageNet +from .imagenette import Imagenette +from .inaturalist import INaturalist +from .kinetics import Kinetics +from .kitti import Kitti +from .lfw import LFWPairs, LFWPeople +from .lsun import LSUN, LSUNClass +from .mnist import EMNIST, FashionMNIST, KMNIST, MNIST, QMNIST +from .moving_mnist import MovingMNIST +from .omniglot import Omniglot +from .oxford_iiit_pet import OxfordIIITPet +from .pcam import PCAM +from .phototour import PhotoTour +from .places365 import Places365 +from .rendered_sst2 import RenderedSST2 +from .sbd import SBDataset +from .sbu import SBU +from .semeion import SEMEION +from .stanford_cars import StanfordCars +from .stl10 import STL10 +from .sun397 import SUN397 +from .svhn import SVHN +from .ucf101 import UCF101 +from .usps import USPS +from .vision import VisionDataset +from .voc import VOCDetection, VOCSegmentation +from .widerface import WIDERFace + +__all__ = ( + "LSUN", + "LSUNClass", + "ImageFolder", + "DatasetFolder", + "FakeData", + "CocoCaptions", + "CocoDetection", + "CIFAR10", + "CIFAR100", + "EMNIST", + "FashionMNIST", + "QMNIST", + "MNIST", + "KMNIST", + "MovingMNIST", + "StanfordCars", + "STL10", + "SUN397", + "SVHN", + "PhotoTour", + "SEMEION", + "Omniglot", + "SBU", + "Flickr8k", + "Flickr30k", + "Flowers102", + "VOCSegmentation", + "VOCDetection", + "Cityscapes", + "ImageNet", + "Caltech101", + "Caltech256", + "CelebA", + "WIDERFace", + "SBDataset", + "VisionDataset", + "USPS", + "Kinetics", + "HMDB51", + "UCF101", + "Places365", + "Kitti", + "INaturalist", + "LFWPeople", + "LFWPairs", + "KittiFlow", + "Sintel", + "FlyingChairs", + "FlyingThings3D", + "HD1K", + "Food101", + "DTD", + "FER2013", + "GTSRB", + "CLEVRClassification", + "OxfordIIITPet", + "PCAM", + "Country211", + "FGVCAircraft", + "EuroSAT", + "RenderedSST2", + "Kitti2012Stereo", + "Kitti2015Stereo", + "CarlaStereo", + "Middlebury2014Stereo", + "CREStereo", + "FallingThingsStereo", + "SceneFlowStereo", + "SintelStereo", + "InStereo2k", + "ETH3DStereo", + "wrap_dataset_for_transforms_v2", + "Imagenette", +) + + +# We override current module's attributes to handle the import: +# from torchvision.datasets import wrap_dataset_for_transforms_v2 +# without a cyclic error. +# Ref: https://peps.python.org/pep-0562/ +def __getattr__(name): + if name in ("wrap_dataset_for_transforms_v2",): + from torchvision.tv_tensors._dataset_wrapper import wrap_dataset_for_transforms_v2 + + return wrap_dataset_for_transforms_v2 + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/_optical_flow.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/_optical_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..af8e17ad95c937dd679cf5f5c14f5e277ab1b1ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/_optical_flow.py @@ -0,0 +1,520 @@ +import itertools +import os +from abc import ABC, abstractmethod +from glob import glob +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +import torch +from PIL import Image + +from ..io.image import decode_png, read_file +from .folder import default_loader +from .utils import _read_pfm, verify_str_arg +from .vision import VisionDataset + +T1 = tuple[Image.Image, Image.Image, Optional[np.ndarray], Optional[np.ndarray]] +T2 = tuple[Image.Image, Image.Image, Optional[np.ndarray]] + + +__all__ = ( + "KittiFlow", + "Sintel", + "FlyingThings3D", + "FlyingChairs", + "HD1K", +) + + +class FlowDataset(ABC, VisionDataset): + # Some datasets like Kitti have a built-in valid_flow_mask, indicating which flow values are valid + # For those we return (img1, img2, flow, valid_flow_mask), and for the rest we return (img1, img2, flow), + # and it's up to whatever consumes the dataset to decide what valid_flow_mask should be. + _has_builtin_flow_mask = False + + def __init__( + self, + root: Union[str, Path], + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + + super().__init__(root=root) + self.transforms = transforms + + self._flow_list: list[str] = [] + self._image_list: list[list[str]] = [] + self._loader = loader + + def _read_img(self, file_name: str) -> Union[Image.Image, torch.Tensor]: + return self._loader(file_name) + + @abstractmethod + def _read_flow(self, file_name: str): + # Return the flow or a tuple with the flow and the valid_flow_mask if _has_builtin_flow_mask is True + pass + + def __getitem__(self, index: int) -> Union[T1, T2]: + + img1 = self._read_img(self._image_list[index][0]) + img2 = self._read_img(self._image_list[index][1]) + + if self._flow_list: # it will be empty for some dataset when split="test" + flow = self._read_flow(self._flow_list[index]) + if self._has_builtin_flow_mask: + flow, valid_flow_mask = flow + else: + valid_flow_mask = None + else: + flow = valid_flow_mask = None + + if self.transforms is not None: + img1, img2, flow, valid_flow_mask = self.transforms(img1, img2, flow, valid_flow_mask) + + if self._has_builtin_flow_mask or valid_flow_mask is not None: + # The `or valid_flow_mask is not None` part is here because the mask can be generated within a transform + return img1, img2, flow, valid_flow_mask # type: ignore[return-value] + else: + return img1, img2, flow # type: ignore[return-value] + + def __len__(self) -> int: + return len(self._image_list) + + def __rmul__(self, v: int) -> torch.utils.data.ConcatDataset: + return torch.utils.data.ConcatDataset([self] * v) + + +class Sintel(FlowDataset): + """`Sintel `_ Dataset for optical flow. + + The dataset is expected to have the following structure: :: + + root + Sintel + testing + clean + scene_1 + scene_2 + ... + final + scene_1 + scene_2 + ... + training + clean + scene_1 + scene_2 + ... + final + scene_1 + scene_2 + ... + flow + scene_1 + scene_2 + ... + + Args: + root (str or ``pathlib.Path``): Root directory of the Sintel Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + pass_name (string, optional): The pass to use, either "clean" (default), "final", or "both". See link above for + details on the different passes. + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + ``valid_flow_mask`` is expected for consistency with other datasets which + return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + pass_name: str = "clean", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both")) + passes = ["clean", "final"] if pass_name == "both" else [pass_name] + + root = Path(root) / "Sintel" + flow_root = root / "training" / "flow" + + for pass_name in passes: + split_dir = "training" if split == "train" else split + image_root = root / split_dir / pass_name + for scene in os.listdir(image_root): + image_list = sorted(glob(str(image_root / scene / "*.png"))) + for i in range(len(image_list) - 1): + self._image_list += [[image_list[i], image_list[i + 1]]] + + if split == "train": + self._flow_list += sorted(glob(str(flow_root / scene / "*.flo"))) + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img1, img2, flow)``. + The flow is a numpy array of shape (2, H, W) and the images are PIL images. + ``flow`` is None if ``split="test"``. + If a valid flow mask is generated within the ``transforms`` parameter, + a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> np.ndarray: + return _read_flo(file_name) + + +class KittiFlow(FlowDataset): + """`KITTI `__ dataset for optical flow (2015). + + The dataset is expected to have the following structure: :: + + root + KittiFlow + testing + image_2 + training + image_2 + flow_occ + + Args: + root (str or ``pathlib.Path``): Root directory of the KittiFlow Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _has_builtin_flow_mask = True + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "KittiFlow" / (split + "ing") + images1 = sorted(glob(str(root / "image_2" / "*_10.png"))) + images2 = sorted(glob(str(root / "image_2" / "*_11.png"))) + + if not images1 or not images2: + raise FileNotFoundError( + "Could not find the Kitti flow images. Please make sure the directory structure is correct." + ) + + for img1, img2 in zip(images1, images2): + self._image_list += [[img1, img2]] + + if split == "train": + self._flow_list = sorted(glob(str(root / "flow_occ" / "*_10.png"))) + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` + where ``valid_flow_mask`` is a numpy boolean mask of shape (H, W) + indicating which flow values are valid. The flow is a numpy array of + shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if + ``split="test"``. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> tuple[np.ndarray, np.ndarray]: + return _read_16bits_png_with_flow_and_valid_mask(file_name) + + +class FlyingChairs(FlowDataset): + """`FlyingChairs `_ Dataset for optical flow. + + You will also need to download the FlyingChairs_train_val.txt file from the dataset page. + + The dataset is expected to have the following structure: :: + + root + FlyingChairs + data + 00001_flow.flo + 00001_img1.ppm + 00001_img2.ppm + ... + FlyingChairs_train_val.txt + + + Args: + root (str or ``pathlib.Path``): Root directory of the FlyingChairs Dataset. + split (string, optional): The dataset split, either "train" (default) or "val" + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + ``valid_flow_mask`` is expected for consistency with other datasets which + return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. + """ + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root=root, transforms=transforms) + + verify_str_arg(split, "split", valid_values=("train", "val")) + + root = Path(root) / "FlyingChairs" + images = sorted(glob(str(root / "data" / "*.ppm"))) + flows = sorted(glob(str(root / "data" / "*.flo"))) + + split_file_name = "FlyingChairs_train_val.txt" + + if not os.path.exists(root / split_file_name): + raise FileNotFoundError( + "The FlyingChairs_train_val.txt file was not found - please download it from the dataset page (see docstring)." + ) + + split_list = np.loadtxt(str(root / split_file_name), dtype=np.int32) + for i in range(len(flows)): + split_id = split_list[i] + if (split == "train" and split_id == 1) or (split == "val" and split_id == 2): + self._flow_list += [flows[i]] + self._image_list += [[images[2 * i], images[2 * i + 1]]] + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img1, img2, flow)``. + The flow is a numpy array of shape (2, H, W) and the images are PIL images. + ``flow`` is None if ``split="val"``. + If a valid flow mask is generated within the ``transforms`` parameter, + a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> np.ndarray: + return _read_flo(file_name) + + +class FlyingThings3D(FlowDataset): + """`FlyingThings3D `_ dataset for optical flow. + + The dataset is expected to have the following structure: :: + + root + FlyingThings3D + frames_cleanpass + TEST + TRAIN + frames_finalpass + TEST + TRAIN + optical_flow + TEST + TRAIN + + Args: + root (str or ``pathlib.Path``): Root directory of the intel FlyingThings3D Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + pass_name (string, optional): The pass to use, either "clean" (default) or "final" or "both". See link above for + details on the different passes. + camera (string, optional): Which camera to return images from. Can be either "left" (default) or "right" or "both". + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + ``valid_flow_mask`` is expected for consistency with other datasets which + return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + pass_name: str = "clean", + camera: str = "left", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + split = split.upper() + + verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both")) + passes = { + "clean": ["frames_cleanpass"], + "final": ["frames_finalpass"], + "both": ["frames_cleanpass", "frames_finalpass"], + }[pass_name] + + verify_str_arg(camera, "camera", valid_values=("left", "right", "both")) + cameras = ["left", "right"] if camera == "both" else [camera] + + root = Path(root) / "FlyingThings3D" + + directions = ("into_future", "into_past") + for pass_name, camera, direction in itertools.product(passes, cameras, directions): + image_dirs = sorted(glob(str(root / pass_name / split / "*/*"))) + image_dirs = sorted(Path(image_dir) / camera for image_dir in image_dirs) + + flow_dirs = sorted(glob(str(root / "optical_flow" / split / "*/*"))) + flow_dirs = sorted(Path(flow_dir) / direction / camera for flow_dir in flow_dirs) + + if not image_dirs or not flow_dirs: + raise FileNotFoundError( + "Could not find the FlyingThings3D flow images. " + "Please make sure the directory structure is correct." + ) + + for image_dir, flow_dir in zip(image_dirs, flow_dirs): + images = sorted(glob(str(image_dir / "*.png"))) + flows = sorted(glob(str(flow_dir / "*.pfm"))) + for i in range(len(flows) - 1): + if direction == "into_future": + self._image_list += [[images[i], images[i + 1]]] + self._flow_list += [flows[i]] + elif direction == "into_past": + self._image_list += [[images[i + 1], images[i]]] + self._flow_list += [flows[i + 1]] + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img1, img2, flow)``. + The flow is a numpy array of shape (2, H, W) and the images are PIL images. + ``flow`` is None if ``split="test"``. + If a valid flow mask is generated within the ``transforms`` parameter, + a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> np.ndarray: + return _read_pfm(file_name) + + +class HD1K(FlowDataset): + """`HD1K `__ dataset for optical flow. + + The dataset is expected to have the following structure: :: + + root + hd1k + hd1k_challenge + image_2 + hd1k_flow_gt + flow_occ + hd1k_input + image_2 + + Args: + root (str or ``pathlib.Path``): Root directory of the HD1K Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _has_builtin_flow_mask = True + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "hd1k" + if split == "train": + # There are 36 "sequences" and we don't want seq i to overlap with seq i + 1, so we need this for loop + for seq_idx in range(36): + flows = sorted(glob(str(root / "hd1k_flow_gt" / "flow_occ" / f"{seq_idx:06d}_*.png"))) + images = sorted(glob(str(root / "hd1k_input" / "image_2" / f"{seq_idx:06d}_*.png"))) + for i in range(len(flows) - 1): + self._flow_list += [flows[i]] + self._image_list += [[images[i], images[i + 1]]] + else: + images1 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*10.png"))) + images2 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*11.png"))) + for image1, image2 in zip(images1, images2): + self._image_list += [[image1, image2]] + + if not self._image_list: + raise FileNotFoundError( + "Could not find the HD1K images. Please make sure the directory structure is correct." + ) + + def _read_flow(self, file_name: str) -> tuple[np.ndarray, np.ndarray]: + return _read_16bits_png_with_flow_and_valid_mask(file_name) + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` where ``valid_flow_mask`` + is a numpy boolean mask of shape (H, W) + indicating which flow values are valid. The flow is a numpy array of + shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if + ``split="test"``. + """ + return super().__getitem__(index) + + +def _read_flo(file_name: str) -> np.ndarray: + """Read .flo file in Middlebury format""" + # Code adapted from: + # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy + # Everything needs to be in little Endian according to + # https://vision.middlebury.edu/flow/code/flow-code/README.txt + with open(file_name, "rb") as f: + magic = np.fromfile(f, "c", count=4).tobytes() + if magic != b"PIEH": + raise ValueError("Magic number incorrect. Invalid .flo file") + + w = np.fromfile(f, " tuple[np.ndarray, np.ndarray]: + + flow_and_valid = decode_png(read_file(file_name)).to(torch.float32) + flow, valid_flow_mask = flow_and_valid[:2, :, :], flow_and_valid[2, :, :] + flow = (flow - 2**15) / 64 # This conversion is explained somewhere on the kitti archive + valid_flow_mask = valid_flow_mask.bool() + + # For consistency with other datasets, we convert to numpy + return flow.numpy(), valid_flow_mask.numpy() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/_stereo_matching.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/_stereo_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2236e97b85c7647bf10b507ad83f0f34e83987 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/_stereo_matching.py @@ -0,0 +1,1223 @@ +import functools +import json +import os +import random +import shutil +from abc import ABC, abstractmethod +from glob import glob +from pathlib import Path +from typing import Callable, cast, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import _read_pfm, download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + +T1 = tuple[Image.Image, Image.Image, Optional[np.ndarray], np.ndarray] +T2 = tuple[Image.Image, Image.Image, Optional[np.ndarray]] + +__all__ = () + +_read_pfm_file = functools.partial(_read_pfm, slice_channels=1) + + +class StereoMatchingDataset(ABC, VisionDataset): + """Base interface for Stereo matching datasets""" + + _has_built_in_disparity_mask = False + + def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None: + """ + Args: + root(str): Root directory of the dataset. + transforms(callable, optional): A function/transform that takes in Tuples of + (images, disparities, valid_masks) and returns a transformed version of each of them. + images is a Tuple of (``PIL.Image``, ``PIL.Image``) + disparities is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (1, H, W) + valid_masks is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (H, W) + In some cases, when a dataset does not provide disparities, the ``disparities`` and + ``valid_masks`` can be Tuples containing None values. + For training splits generally the datasets provide a minimal guarantee of + images: (``PIL.Image``, ``PIL.Image``) + disparities: (``np.ndarray``, ``None``) with shape (1, H, W) + Optionally, based on the dataset, it can return a ``mask`` as well: + valid_masks: (``np.ndarray | None``, ``None``) with shape (H, W) + For some test splits, the datasets provides outputs that look like: + imgaes: (``PIL.Image``, ``PIL.Image``) + disparities: (``None``, ``None``) + Optionally, based on the dataset, it can return a ``mask`` as well: + valid_masks: (``None``, ``None``) + """ + super().__init__(root=root) + self.transforms = transforms + + self._images = [] # type: ignore + self._disparities = [] # type: ignore + + def _read_img(self, file_path: Union[str, Path]) -> Image.Image: + img = Image.open(file_path) + if img.mode != "RGB": + img = img.convert("RGB") # type: ignore [assignment] + return img + + def _scan_pairs( + self, + paths_left_pattern: str, + paths_right_pattern: Optional[str] = None, + ) -> list[tuple[str, Optional[str]]]: + + left_paths = list(sorted(glob(paths_left_pattern))) + + right_paths: list[Union[None, str]] + if paths_right_pattern: + right_paths = list(sorted(glob(paths_right_pattern))) + else: + right_paths = list(None for _ in left_paths) + + if not left_paths: + raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_left_pattern}") + + if not right_paths: + raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_right_pattern}") + + if len(left_paths) != len(right_paths): + raise ValueError( + f"Found {len(left_paths)} left files but {len(right_paths)} right files using:\n " + f"left pattern: {paths_left_pattern}\n" + f"right pattern: {paths_right_pattern}\n" + ) + + paths = list((left, right) for left, right in zip(left_paths, right_paths)) + return paths + + @abstractmethod + def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], Optional[np.ndarray]]: + # function that returns a disparity map and an occlusion map + pass + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3 or 4-tuple with ``(img_left, img_right, disparity, Optional[valid_mask])`` where ``valid_mask`` + can be a numpy boolean mask of shape (H, W) if the dataset provides a file + indicating which disparity pixels are valid. The disparity is a numpy array of + shape (1, H, W) and the images are PIL images. ``disparity`` is None for + datasets on which for ``split="test"`` the authors did not provide annotations. + """ + img_left = self._read_img(self._images[index][0]) + img_right = self._read_img(self._images[index][1]) + + dsp_map_left, valid_mask_left = self._read_disparity(self._disparities[index][0]) + dsp_map_right, valid_mask_right = self._read_disparity(self._disparities[index][1]) + + imgs = (img_left, img_right) + dsp_maps = (dsp_map_left, dsp_map_right) + valid_masks = (valid_mask_left, valid_mask_right) + + if self.transforms is not None: + ( + imgs, + dsp_maps, + valid_masks, + ) = self.transforms(imgs, dsp_maps, valid_masks) + + if self._has_built_in_disparity_mask or valid_masks[0] is not None: + return imgs[0], imgs[1], dsp_maps[0], cast(np.ndarray, valid_masks[0]) + else: + return imgs[0], imgs[1], dsp_maps[0] + + def __len__(self) -> int: + return len(self._images) + + +class CarlaStereo(StereoMatchingDataset): + """ + Carla simulator data linked in the `CREStereo github repo `_. + + The dataset is expected to have the following structure: :: + + root + carla-highres + trainingF + scene1 + img0.png + img1.png + disp0GT.pfm + disp1GT.pfm + calib.txt + scene2 + img0.png + img1.png + disp0GT.pfm + disp1GT.pfm + calib.txt + ... + + Args: + root (str or ``pathlib.Path``): Root directory where `carla-highres` is located. + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + root = Path(root) / "carla-highres" + + left_image_pattern = str(root / "trainingF" / "*" / "im0.png") + right_image_pattern = str(root / "trainingF" / "*" / "im1.png") + imgs = self._scan_pairs(left_image_pattern, right_image_pattern) + self._images = imgs + + left_disparity_pattern = str(root / "trainingF" / "*" / "disp0GT.pfm") + right_disparity_pattern = str(root / "trainingF" / "*" / "disp1GT.pfm") + disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + self._disparities = disparities + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class Kitti2012Stereo(StereoMatchingDataset): + """ + KITTI dataset from the `2012 stereo evaluation benchmark `_. + Uses the RGB images for consistency with KITTI 2015. + + The dataset is expected to have the following structure: :: + + root + Kitti2012 + testing + colored_0 + 1_10.png + 2_10.png + ... + colored_1 + 1_10.png + 2_10.png + ... + training + colored_0 + 1_10.png + 2_10.png + ... + colored_1 + 1_10.png + 2_10.png + ... + disp_noc + 1.png + 2.png + ... + calib + + Args: + root (str or ``pathlib.Path``): Root directory where `Kitti2012` is located. + split (string, optional): The dataset split of scenes, either "train" (default) or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "Kitti2012" / (split + "ing") + + left_img_pattern = str(root / "colored_0" / "*_10.png") + right_img_pattern = str(root / "colored_1" / "*_10.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "train": + disparity_pattern = str(root / "disp_noc" / "*.png") + self._disparities = self._scan_pairs(disparity_pattern, None) + else: + self._disparities = list((None, None) for _ in self._images) + + def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]: + # test split has no disparity maps + if file_path is None: + return None, None + + disparity_map = np.asarray(Image.open(file_path)) / 256.0 + # unsqueeze the disparity map into (C, H, W) format + disparity_map = disparity_map[None, :, :] + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test. + """ + return cast(T1, super().__getitem__(index)) + + +class Kitti2015Stereo(StereoMatchingDataset): + """ + KITTI dataset from the `2015 stereo evaluation benchmark `_. + + The dataset is expected to have the following structure: :: + + root + Kitti2015 + testing + image_2 + img1.png + img2.png + ... + image_3 + img1.png + img2.png + ... + training + image_2 + img1.png + img2.png + ... + image_3 + img1.png + img2.png + ... + disp_occ_0 + img1.png + img2.png + ... + disp_occ_1 + img1.png + img2.png + ... + calib + + Args: + root (str or ``pathlib.Path``): Root directory where `Kitti2015` is located. + split (string, optional): The dataset split of scenes, either "train" (default) or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "Kitti2015" / (split + "ing") + left_img_pattern = str(root / "image_2" / "*.png") + right_img_pattern = str(root / "image_3" / "*.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "train": + left_disparity_pattern = str(root / "disp_occ_0" / "*.png") + right_disparity_pattern = str(root / "disp_occ_1" / "*.png") + self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + else: + self._disparities = list((None, None) for _ in self._images) + + def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]: + # test split has no disparity maps + if file_path is None: + return None, None + + disparity_map = np.asarray(Image.open(file_path)) / 256.0 + # unsqueeze the disparity map into (C, H, W) format + disparity_map = disparity_map[None, :, :] + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test. + """ + return cast(T1, super().__getitem__(index)) + + +class Middlebury2014Stereo(StereoMatchingDataset): + """Publicly available scenes from the Middlebury dataset `2014 version `. + + The dataset mostly follows the original format, without containing the ambient subdirectories. : :: + + root + Middlebury2014 + train + scene1-{perfect,imperfect} + calib.txt + im{0,1}.png + im1E.png + im1L.png + disp{0,1}.pfm + disp{0,1}-n.png + disp{0,1}-sd.pfm + disp{0,1}y.pfm + scene2-{perfect,imperfect} + calib.txt + im{0,1}.png + im1E.png + im1L.png + disp{0,1}.pfm + disp{0,1}-n.png + disp{0,1}-sd.pfm + disp{0,1}y.pfm + ... + additional + scene1-{perfect,imperfect} + calib.txt + im{0,1}.png + im1E.png + im1L.png + disp{0,1}.pfm + disp{0,1}-n.png + disp{0,1}-sd.pfm + disp{0,1}y.pfm + ... + test + scene1 + calib.txt + im{0,1}.png + scene2 + calib.txt + im{0,1}.png + ... + + Args: + root (str or ``pathlib.Path``): Root directory of the Middleburry 2014 Dataset. + split (string, optional): The dataset split of scenes, either "train" (default), "test", or "additional" + use_ambient_views (boolean, optional): Whether to use different expose or lightning views when possible. + The dataset samples with equal probability between ``[im1.png, im1E.png, im1L.png]``. + calibration (string, optional): Whether or not to use the calibrated (default) or uncalibrated scenes. + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + download (boolean, optional): Whether or not to download the dataset in the ``root`` directory. + """ + + splits = { + "train": [ + "Adirondack", + "Jadeplant", + "Motorcycle", + "Piano", + "Pipes", + "Playroom", + "Playtable", + "Recycle", + "Shelves", + "Vintage", + ], + "additional": [ + "Backpack", + "Bicycle1", + "Cable", + "Classroom1", + "Couch", + "Flowers", + "Mask", + "Shopvac", + "Sticks", + "Storage", + "Sword1", + "Sword2", + "Umbrella", + ], + "test": [ + "Plants", + "Classroom2E", + "Classroom2", + "Australia", + "DjembeL", + "CrusadeP", + "Crusade", + "Hoops", + "Bicycle2", + "Staircase", + "Newkuba", + "AustraliaP", + "Djembe", + "Livingroom", + "Computer", + ], + } + + _has_built_in_disparity_mask = True + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + calibration: Optional[str] = "perfect", + use_ambient_views: bool = False, + transforms: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test", "additional")) + self.split = split + + if calibration: + verify_str_arg(calibration, "calibration", valid_values=("perfect", "imperfect", "both", None)) # type: ignore + if split == "test": + raise ValueError("Split 'test' has only no calibration settings, please set `calibration=None`.") + else: + if split != "test": + raise ValueError( + f"Split '{split}' has calibration settings, however None was provided as an argument." + f"\nSetting calibration to 'perfect' for split '{split}'. Available calibration settings are: 'perfect', 'imperfect', 'both'.", + ) + + if download: + self._download_dataset(root) + + root = Path(root) / "Middlebury2014" + + if not os.path.exists(root / split): + raise FileNotFoundError(f"The {split} directory was not found in the provided root directory") + + split_scenes = self.splits[split] + # check that the provided root folder contains the scene splits + if not any( + # using startswith to account for perfect / imperfect calibrartion + scene.startswith(s) + for scene in os.listdir(root / split) + for s in split_scenes + ): + raise FileNotFoundError(f"Provided root folder does not contain any scenes from the {split} split.") + + calibrartion_suffixes = { + None: [""], + "perfect": ["-perfect"], + "imperfect": ["-imperfect"], + "both": ["-perfect", "-imperfect"], + }[calibration] + + for calibration_suffix in calibrartion_suffixes: + scene_pattern = "*" + calibration_suffix + left_img_pattern = str(root / split / scene_pattern / "im0.png") + right_img_pattern = str(root / split / scene_pattern / "im1.png") + self._images += self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "test": + self._disparities = list((None, None) for _ in self._images) + else: + left_dispartity_pattern = str(root / split / scene_pattern / "disp0.pfm") + right_dispartity_pattern = str(root / split / scene_pattern / "disp1.pfm") + self._disparities += self._scan_pairs(left_dispartity_pattern, right_dispartity_pattern) + + self.use_ambient_views = use_ambient_views + + def _read_img(self, file_path: Union[str, Path]) -> Image.Image: + """ + Function that reads either the original right image or an augmented view when ``use_ambient_views`` is True. + When ``use_ambient_views`` is True, the dataset will return at random one of ``[im1.png, im1E.png, im1L.png]`` + as the right image. + """ + ambient_file_paths: list[Union[str, Path]] # make mypy happy + + if not isinstance(file_path, Path): + file_path = Path(file_path) + + if file_path.name == "im1.png" and self.use_ambient_views: + base_path = file_path.parent + # initialize sampleable container + ambient_file_paths = list(base_path / view_name for view_name in ["im1E.png", "im1L.png"]) + # double check that we're not going to try to read from an invalid file path + ambient_file_paths = list(filter(lambda p: os.path.exists(p), ambient_file_paths)) + # keep the original image as an option as well for uniform sampling between base views + ambient_file_paths.append(file_path) + file_path = random.choice(ambient_file_paths) # type: ignore + return super()._read_img(file_path) + + def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]: + # test split has not disparity maps + if file_path is None: + return None, None + + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + disparity_map[disparity_map == np.inf] = 0 # remove infinite disparities + valid_mask = (disparity_map > 0).squeeze(0) # mask out invalid disparities + return disparity_map, valid_mask + + def _download_dataset(self, root: Union[str, Path]) -> None: + base_url = "https://vision.middlebury.edu/stereo/data/scenes2014/zip" + # train and additional splits have 2 different calibration settings + root = Path(root) / "Middlebury2014" + split_name = self.split + + if split_name != "test": + for split_scene in self.splits[split_name]: + split_root = root / split_name + for calibration in ["perfect", "imperfect"]: + scene_name = f"{split_scene}-{calibration}" + scene_url = f"{base_url}/{scene_name}.zip" + # download the scene only if it doesn't exist + if not (split_root / scene_name).exists(): + download_and_extract_archive( + url=scene_url, + filename=f"{scene_name}.zip", + download_root=str(split_root), + remove_finished=True, + ) + else: + os.makedirs(root / "test") + if any(s not in os.listdir(root / "test") for s in self.splits["test"]): + # test split is downloaded from a different location + test_set_url = "https://vision.middlebury.edu/stereo/submit3/zip/MiddEval3-data-F.zip" + # the unzip is going to produce a directory MiddEval3 with two subdirectories trainingF and testF + # we want to move the contents from testF into the directory + download_and_extract_archive(url=test_set_url, download_root=str(root), remove_finished=True) + for scene_dir, scene_names, _ in os.walk(str(root / "MiddEval3/testF")): + for scene in scene_names: + scene_dst_dir = root / "test" + scene_src_dir = Path(scene_dir) / scene + os.makedirs(scene_dst_dir, exist_ok=True) + shutil.move(str(scene_src_dir), str(scene_dst_dir)) + + # cleanup MiddEval3 directory + shutil.rmtree(str(root / "MiddEval3")) + + def __getitem__(self, index: int) -> T2: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` for `split=test`. + """ + return cast(T2, super().__getitem__(index)) + + +class CREStereo(StereoMatchingDataset): + """Synthetic dataset used in training the `CREStereo `_ architecture. + Dataset details on the official paper `repo `_. + + The dataset is expected to have the following structure: :: + + root + CREStereo + tree + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + img2_left.jpg + img2_right.jpg + img2_left.disp.jpg + img2_right.disp.jpg + ... + shapenet + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + ... + reflective + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + ... + hole + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + ... + + Args: + root (str): Root directory of the dataset. + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__( + self, + root: Union[str, Path], + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms) + + root = Path(root) / "CREStereo" + + dirs = ["shapenet", "reflective", "tree", "hole"] + + for s in dirs: + left_image_pattern = str(root / s / "*_left.jpg") + right_image_pattern = str(root / s / "*_right.jpg") + imgs = self._scan_pairs(left_image_pattern, right_image_pattern) + self._images += imgs + + left_disparity_pattern = str(root / s / "*_left.disp.png") + right_disparity_pattern = str(root / s / "*_right.disp.png") + disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + self._disparities += disparities + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = np.asarray(Image.open(file_path), dtype=np.float32) + # unsqueeze the disparity map into (C, H, W) format + disparity_map = disparity_map[None, :, :] / 32.0 + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + """ + return cast(T1, super().__getitem__(index)) + + +class FallingThingsStereo(StereoMatchingDataset): + """`FallingThings `_ dataset. + + The dataset is expected to have the following structure: :: + + root + FallingThings + single + dir1 + scene1 + _object_settings.json + _camera_settings.json + image1.left.depth.png + image1.right.depth.png + image1.left.jpg + image1.right.jpg + image2.left.depth.png + image2.right.depth.png + image2.left.jpg + image2.right + ... + scene2 + ... + mixed + scene1 + _object_settings.json + _camera_settings.json + image1.left.depth.png + image1.right.depth.png + image1.left.jpg + image1.right.jpg + image2.left.depth.png + image2.right.depth.png + image2.left.jpg + image2.right + ... + scene2 + ... + + Args: + root (str or ``pathlib.Path``): Root directory where FallingThings is located. + variant (string): Which variant to use. Either "single", "mixed", or "both". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + def __init__(self, root: Union[str, Path], variant: str = "single", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + root = Path(root) / "FallingThings" + + verify_str_arg(variant, "variant", valid_values=("single", "mixed", "both")) + + variants = { + "single": ["single"], + "mixed": ["mixed"], + "both": ["single", "mixed"], + }[variant] + + split_prefix = { + "single": Path("*") / "*", + "mixed": Path("*"), + } + + for s in variants: + left_img_pattern = str(root / s / split_prefix[s] / "*.left.jpg") + right_img_pattern = str(root / s / split_prefix[s] / "*.right.jpg") + self._images += self._scan_pairs(left_img_pattern, right_img_pattern) + + left_disparity_pattern = str(root / s / split_prefix[s] / "*.left.depth.png") + right_disparity_pattern = str(root / s / split_prefix[s] / "*.right.depth.png") + self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + # (H, W) image + depth = np.asarray(Image.open(file_path)) + # as per https://research.nvidia.com/sites/default/files/pubs/2018-06_Falling-Things/readme_0.txt + # in order to extract disparity from depth maps + camera_settings_path = Path(file_path).parent / "_camera_settings.json" + with open(camera_settings_path) as f: + # inverse of depth-from-disparity equation: depth = (baseline * focal) / (disparity * pixel_constant) + intrinsics = json.load(f) + focal = intrinsics["camera_settings"][0]["intrinsic_settings"]["fx"] + baseline, pixel_constant = 6, 100 # pixel constant is inverted + disparity_map = (baseline * focal * pixel_constant) / depth.astype(np.float32) + # unsqueeze disparity to (C, H, W) + disparity_map = disparity_map[None, :, :] + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class SceneFlowStereo(StereoMatchingDataset): + """Dataset interface for `Scene Flow `_ datasets. + This interface provides access to the `FlyingThings3D, `Monkaa` and `Driving` datasets. + + The dataset is expected to have the following structure: :: + + root + SceneFlow + Monkaa + frames_cleanpass + scene1 + left + img1.png + img2.png + right + img1.png + img2.png + scene2 + left + img1.png + img2.png + right + img1.png + img2.png + frames_finalpass + scene1 + left + img1.png + img2.png + right + img1.png + img2.png + ... + ... + disparity + scene1 + left + img1.pfm + img2.pfm + right + img1.pfm + img2.pfm + FlyingThings3D + ... + ... + + Args: + root (str or ``pathlib.Path``): Root directory where SceneFlow is located. + variant (string): Which dataset variant to user, "FlyingThings3D" (default), "Monkaa" or "Driving". + pass_name (string): Which pass to use, "clean" (default), "final" or "both". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + + """ + + def __init__( + self, + root: Union[str, Path], + variant: str = "FlyingThings3D", + pass_name: str = "clean", + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms) + + root = Path(root) / "SceneFlow" + + verify_str_arg(variant, "variant", valid_values=("FlyingThings3D", "Driving", "Monkaa")) + verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both")) + + passes = { + "clean": ["frames_cleanpass"], + "final": ["frames_finalpass"], + "both": ["frames_cleanpass", "frames_finalpass"], + }[pass_name] + + root = root / variant + + prefix_directories = { + "Monkaa": Path("*"), + "FlyingThings3D": Path("*") / "*" / "*", + "Driving": Path("*") / "*" / "*", + } + + for p in passes: + left_image_pattern = str(root / p / prefix_directories[variant] / "left" / "*.png") + right_image_pattern = str(root / p / prefix_directories[variant] / "right" / "*.png") + self._images += self._scan_pairs(left_image_pattern, right_image_pattern) + + left_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "left" / "*.pfm") + right_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "right" / "*.pfm") + self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class SintelStereo(StereoMatchingDataset): + """Sintel `Stereo Dataset `_. + + The dataset is expected to have the following structure: :: + + root + Sintel + training + final_left + scene1 + img1.png + img2.png + ... + ... + final_right + scene2 + img1.png + img2.png + ... + ... + disparities + scene1 + img1.png + img2.png + ... + ... + occlusions + scene1 + img1.png + img2.png + ... + ... + outofframe + scene1 + img1.png + img2.png + ... + ... + + Args: + root (str or ``pathlib.Path``): Root directory where Sintel Stereo is located. + pass_name (string): The name of the pass to use, either "final", "clean" or "both". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], pass_name: str = "final", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(pass_name, "pass_name", valid_values=("final", "clean", "both")) + + root = Path(root) / "Sintel" + pass_names = { + "final": ["final"], + "clean": ["clean"], + "both": ["final", "clean"], + }[pass_name] + + for p in pass_names: + left_img_pattern = str(root / "training" / f"{p}_left" / "*" / "*.png") + right_img_pattern = str(root / "training" / f"{p}_right" / "*" / "*.png") + self._images += self._scan_pairs(left_img_pattern, right_img_pattern) + + disparity_pattern = str(root / "training" / "disparities" / "*" / "*.png") + self._disparities += self._scan_pairs(disparity_pattern, None) + + def _get_occlussion_mask_paths(self, file_path: str) -> tuple[str, str]: + # helper function to get the occlusion mask paths + # a path will look like .../.../.../training/disparities/scene1/img1.png + # we want to get something like .../.../.../training/occlusions/scene1/img1.png + fpath = Path(file_path) + basename = fpath.name + scenedir = fpath.parent + # the parent of the scenedir is actually the disparity dir + sampledir = scenedir.parent.parent + + occlusion_path = str(sampledir / "occlusions" / scenedir.name / basename) + outofframe_path = str(sampledir / "outofframe" / scenedir.name / basename) + + if not os.path.exists(occlusion_path): + raise FileNotFoundError(f"Occlusion mask {occlusion_path} does not exist") + + if not os.path.exists(outofframe_path): + raise FileNotFoundError(f"Out of frame mask {outofframe_path} does not exist") + + return occlusion_path, outofframe_path + + def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]: + if file_path is None: + return None, None + + # disparity decoding as per Sintel instructions in the README provided with the dataset + disparity_map = np.asarray(Image.open(file_path), dtype=np.float32) + r, g, b = np.split(disparity_map, 3, axis=-1) + disparity_map = r * 4 + g / (2**6) + b / (2**14) + # reshape into (C, H, W) format + disparity_map = np.transpose(disparity_map, (2, 0, 1)) + # find the appropriate file paths + occlued_mask_path, out_of_frame_mask_path = self._get_occlussion_mask_paths(file_path) + # occlusion masks + valid_mask = np.asarray(Image.open(occlued_mask_path)) == 0 + # out of frame masks + off_mask = np.asarray(Image.open(out_of_frame_mask_path)) == 0 + # combine the masks together + valid_mask = np.logical_and(off_mask, valid_mask) + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T2: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images whilst + the valid_mask is a numpy array of shape (H, W). + """ + return cast(T2, super().__getitem__(index)) + + +class InStereo2k(StereoMatchingDataset): + """`InStereo2k `_ dataset. + + The dataset is expected to have the following structure: :: + + root + InStereo2k + train + scene1 + left.png + right.png + left_disp.png + right_disp.png + ... + scene2 + ... + test + scene1 + left.png + right.png + left_disp.png + right_disp.png + ... + scene2 + ... + + Args: + root (str or ``pathlib.Path``): Root directory where InStereo2k is located. + split (string): Either "train" or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + root = Path(root) / "InStereo2k" / split + + verify_str_arg(split, "split", valid_values=("train", "test")) + + left_img_pattern = str(root / "*" / "left.png") + right_img_pattern = str(root / "*" / "right.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + left_disparity_pattern = str(root / "*" / "left_disp.png") + right_disparity_pattern = str(root / "*" / "right_disp.png") + self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = np.asarray(Image.open(file_path), dtype=np.float32) + # unsqueeze disparity to (C, H, W) + disparity_map = disparity_map[None, :, :] / 1024.0 + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class ETH3DStereo(StereoMatchingDataset): + """ETH3D `Low-Res Two-View `_ dataset. + + The dataset is expected to have the following structure: :: + + root + ETH3D + two_view_training + scene1 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + scene2 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + ... + two_view_training_gt + scene1 + disp0GT.pfm + mask0nocc.png + scene2 + disp0GT.pfm + mask0nocc.png + ... + two_view_testing + scene1 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + scene2 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + ... + + Args: + root (str or ``pathlib.Path``): Root directory of the ETH3D Dataset. + split (string, optional): The dataset split of scenes, either "train" (default) or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "ETH3D" + + img_dir = "two_view_training" if split == "train" else "two_view_test" + anot_dir = "two_view_training_gt" + + left_img_pattern = str(root / img_dir / "*" / "im0.png") + right_img_pattern = str(root / img_dir / "*" / "im1.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "test": + self._disparities = list((None, None) for _ in self._images) + else: + disparity_pattern = str(root / anot_dir / "*" / "disp0GT.pfm") + self._disparities = self._scan_pairs(disparity_pattern, None) + + def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]: + # test split has no disparity maps + if file_path is None: + return None, None + + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + mask_path = Path(file_path).parent / "mask0nocc.png" + valid_mask = Image.open(mask_path) + valid_mask = np.asarray(valid_mask).astype(bool) + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T2: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test. + """ + return cast(T2, super().__getitem__(index)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/caltech.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/caltech.py new file mode 100644 index 0000000000000000000000000000000000000000..7498f67400158f1c0da8a6bb66866153735120ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/caltech.py @@ -0,0 +1,241 @@ +import os +import os.path +import shutil +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive, extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Caltech101(VisionDataset): + """`Caltech 101 `_ Dataset. + + .. warning:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``caltech101`` exists or will be saved to if download is set to True. + target_type (string or list, optional): Type of target to use, ``category`` or + ``annotation``. Can also be a list to output a tuple with all specified + target types. ``category`` represents the target class, and + ``annotation`` is a list of points from a hand-generated outline. + Defaults to ``category``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + """ + + def __init__( + self, + root: Union[str, Path], + target_type: Union[list[str], str] = "category", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(os.path.join(root, "caltech101"), transform=transform, target_transform=target_transform) + os.makedirs(self.root, exist_ok=True) + if isinstance(target_type, str): + target_type = [target_type] + self.target_type = [verify_str_arg(t, "target_type", ("category", "annotation")) for t in target_type] + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.categories = sorted(os.listdir(os.path.join(self.root, "101_ObjectCategories"))) + self.categories.remove("BACKGROUND_Google") # this is not a real class + + # For some reason, the category names in "101_ObjectCategories" and + # "Annotations" do not always match. This is a manual map between the + # two. Defaults to using same name, since most names are fine. + name_map = { + "Faces": "Faces_2", + "Faces_easy": "Faces_3", + "Motorbikes": "Motorbikes_16", + "airplanes": "Airplanes_Side_2", + } + self.annotation_categories = list(map(lambda x: name_map[x] if x in name_map else x, self.categories)) + + self.index: list[int] = [] + self.y = [] + for i, c in enumerate(self.categories): + n = len(os.listdir(os.path.join(self.root, "101_ObjectCategories", c))) + self.index.extend(range(1, n + 1)) + self.y.extend(n * [i]) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where the type of target specified by target_type. + """ + import scipy.io + + img = Image.open( + os.path.join( + self.root, + "101_ObjectCategories", + self.categories[self.y[index]], + f"image_{self.index[index]:04d}.jpg", + ) + ) + + target: Any = [] + for t in self.target_type: + if t == "category": + target.append(self.y[index]) + elif t == "annotation": + data = scipy.io.loadmat( + os.path.join( + self.root, + "Annotations", + self.annotation_categories[self.y[index]], + f"annotation_{self.index[index]:04d}.mat", + ) + ) + target.append(data["obj_contour"]) + target = tuple(target) if len(target) > 1 else target[0] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def _check_integrity(self) -> bool: + # can be more robust and check hash of files + return os.path.exists(os.path.join(self.root, "101_ObjectCategories")) + + def __len__(self) -> int: + return len(self.index) + + def download(self) -> None: + if self._check_integrity(): + return + + download_and_extract_archive( + "https://data.caltech.edu/records/mzrjq-6wc02/files/caltech-101.zip", + download_root=self.root, + filename="caltech-101.zip", + md5="3138e1922a9193bfa496528edbbc45d0", + ) + gzip_folder = os.path.join(self.root, "caltech-101") + for gzip_file in os.listdir(gzip_folder): + if gzip_file.endswith(".gz"): + extract_archive(os.path.join(gzip_folder, gzip_file), self.root) + shutil.rmtree(gzip_folder) + os.remove(os.path.join(self.root, "caltech-101.zip")) + + def extra_repr(self) -> str: + return "Target type: {target_type}".format(**self.__dict__) + + +class Caltech256(VisionDataset): + """`Caltech 256 `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``caltech256`` exists or will be saved to if download is set to True. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + def __init__( + self, + root: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(os.path.join(root, "caltech256"), transform=transform, target_transform=target_transform) + os.makedirs(self.root, exist_ok=True) + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.categories = sorted(os.listdir(os.path.join(self.root, "256_ObjectCategories"))) + self.index: list[int] = [] + self.y = [] + for i, c in enumerate(self.categories): + n = len( + [ + item + for item in os.listdir(os.path.join(self.root, "256_ObjectCategories", c)) + if item.endswith(".jpg") + ] + ) + self.index.extend(range(1, n + 1)) + self.y.extend(n * [i]) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img = Image.open( + os.path.join( + self.root, + "256_ObjectCategories", + self.categories[self.y[index]], + f"{self.y[index] + 1:03d}_{self.index[index]:04d}.jpg", + ) + ) + + target = self.y[index] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def _check_integrity(self) -> bool: + # can be more robust and check hash of files + return os.path.exists(os.path.join(self.root, "256_ObjectCategories")) + + def __len__(self) -> int: + return len(self.index) + + def download(self) -> None: + if self._check_integrity(): + return + + download_and_extract_archive( + "https://data.caltech.edu/records/nyy15-4j048/files/256_ObjectCategories.tar", + self.root, + filename="256_ObjectCategories.tar", + md5="67b4f42ca05d46448c6bb8ecd2220f6d", + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/celeba.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/celeba.py new file mode 100644 index 0000000000000000000000000000000000000000..469af6ed3b7efa433e2a7e488e8017a78710bad5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/celeba.py @@ -0,0 +1,199 @@ +import csv +import os +from collections import namedtuple +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import PIL +import torch + +from .utils import check_integrity, download_file_from_google_drive, extract_archive, verify_str_arg +from .vision import VisionDataset + +CSV = namedtuple("CSV", ["header", "index", "data"]) + + +class CelebA(VisionDataset): + """`Large-scale CelebFaces Attributes (CelebA) Dataset `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + split (string): One of {'train', 'valid', 'test', 'all'}. + Accordingly dataset is selected. + target_type (string or list, optional): Type of target to use, ``attr``, ``identity``, ``bbox``, + or ``landmarks``. Can also be a list to output a tuple with all specified target types. + The targets represent: + + - ``attr`` (Tensor shape=(40,) dtype=int): binary (0, 1) labels for attributes + - ``identity`` (int): label for each person (data points with the same identity are the same person) + - ``bbox`` (Tensor shape=(4,) dtype=int): bounding box (x, y, width, height) + - ``landmarks`` (Tensor shape=(10,) dtype=int): landmark points (lefteye_x, lefteye_y, righteye_x, + righteye_y, nose_x, nose_y, leftmouth_x, leftmouth_y, rightmouth_x, rightmouth_y) + + Defaults to ``attr``. If empty, ``None`` will be returned as target. + + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + """ + + base_folder = "celeba" + # There currently does not appear to be an easy way to extract 7z in python (without introducing additional + # dependencies). The "in-the-wild" (not aligned+cropped) images are only in 7z, so they are not available + # right now. + file_list = [ + # File ID MD5 Hash Filename + ("0B7EVK8r0v71pZjFTYXZWM3FlRnM", "00d2c5bc6d35e252742224ab0c1e8fcb", "img_align_celeba.zip"), + # ("0B7EVK8r0v71pbWNEUjJKdDQ3dGc","b6cd7e93bc7a96c2dc33f819aa3ac651", "img_align_celeba_png.7z"), + # ("0B7EVK8r0v71peklHb0pGdDl6R28", "b6cd7e93bc7a96c2dc33f819aa3ac651", "img_celeba.7z"), + ("0B7EVK8r0v71pblRyaVFSWGxPY0U", "75e246fa4810816ffd6ee81facbd244c", "list_attr_celeba.txt"), + ("1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS", "32bd1bd63d3c78cd57e08160ec5ed1e2", "identity_CelebA.txt"), + ("0B7EVK8r0v71pbThiMVRxWXZ4dU0", "00566efa6fedff7a56946cd1c10f1c16", "list_bbox_celeba.txt"), + ("0B7EVK8r0v71pd0FJY3Blby1HUTQ", "cc24ecafdb5b50baae59b03474781f8c", "list_landmarks_align_celeba.txt"), + # ("0B7EVK8r0v71pTzJIdlJWdHczRlU", "063ee6ddb681f96bc9ca28c6febb9d1a", "list_landmarks_celeba.txt"), + ("0B7EVK8r0v71pY0NSMzRuSXJEVkk", "d32c9cbf5e040fd4025c592c306e6668", "list_eval_partition.txt"), + ] + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + target_type: Union[list[str], str] = "attr", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.split = split + if isinstance(target_type, list): + self.target_type = target_type + else: + self.target_type = [target_type] + + if not self.target_type and self.target_transform is not None: + raise RuntimeError("target_transform is specified but target_type is empty") + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + split_map = { + "train": 0, + "valid": 1, + "test": 2, + "all": None, + } + split_ = split_map[ + verify_str_arg( + split.lower() if isinstance(split, str) else split, + "split", + ("train", "valid", "test", "all"), + ) + ] + splits = self._load_csv("list_eval_partition.txt") + identity = self._load_csv("identity_CelebA.txt") + bbox = self._load_csv("list_bbox_celeba.txt", header=1) + landmarks_align = self._load_csv("list_landmarks_align_celeba.txt", header=1) + attr = self._load_csv("list_attr_celeba.txt", header=1) + + mask = slice(None) if split_ is None else (splits.data == split_).squeeze() + + if mask == slice(None): # if split == "all" + self.filename = splits.index + else: + self.filename = [splits.index[i] for i in torch.squeeze(torch.nonzero(mask))] # type: ignore[arg-type] + self.identity = identity.data[mask] + self.bbox = bbox.data[mask] + self.landmarks_align = landmarks_align.data[mask] + self.attr = attr.data[mask] + # map from {-1, 1} to {0, 1} + self.attr = torch.div(self.attr + 1, 2, rounding_mode="floor") + self.attr_names = attr.header + + def _load_csv( + self, + filename: str, + header: Optional[int] = None, + ) -> CSV: + with open(os.path.join(self.root, self.base_folder, filename)) as csv_file: + data = list(csv.reader(csv_file, delimiter=" ", skipinitialspace=True)) + + if header is not None: + headers = data[header] + data = data[header + 1 :] + else: + headers = [] + + indices = [row[0] for row in data] + data = [row[1:] for row in data] + data_int = [list(map(int, i)) for i in data] + + return CSV(headers, indices, torch.tensor(data_int)) + + def _check_integrity(self) -> bool: + for _, md5, filename in self.file_list: + fpath = os.path.join(self.root, self.base_folder, filename) + _, ext = os.path.splitext(filename) + # Allow original archive to be deleted (zip and 7z) + # Only need the extracted images + if ext not in [".zip", ".7z"] and not check_integrity(fpath, md5): + return False + + # Should check a hash of the images + return os.path.isdir(os.path.join(self.root, self.base_folder, "img_align_celeba")) + + def download(self) -> None: + if self._check_integrity(): + return + + for file_id, md5, filename in self.file_list: + download_file_from_google_drive(file_id, os.path.join(self.root, self.base_folder), filename, md5) + + extract_archive(os.path.join(self.root, self.base_folder, "img_align_celeba.zip")) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + X = PIL.Image.open(os.path.join(self.root, self.base_folder, "img_align_celeba", self.filename[index])) + + target: Any = [] + for t in self.target_type: + if t == "attr": + target.append(self.attr[index, :]) + elif t == "identity": + target.append(self.identity[index, 0]) + elif t == "bbox": + target.append(self.bbox[index, :]) + elif t == "landmarks": + target.append(self.landmarks_align[index, :]) + else: + # TODO: refactor with utils.verify_str_arg + raise ValueError(f'Target type "{t}" is not recognized.') + + if self.transform is not None: + X = self.transform(X) + + if target: + target = tuple(target) if len(target) > 1 else target[0] + + if self.target_transform is not None: + target = self.target_transform(target) + else: + target = None + + return X, target + + def __len__(self) -> int: + return len(self.attr) + + def extra_repr(self) -> str: + lines = ["Target type: {target_type}", "Split: {split}"] + return "\n".join(lines).format(**self.__dict__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/cifar.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/cifar.py new file mode 100644 index 0000000000000000000000000000000000000000..45893a4499506a43323bf53d9552adec2a457261 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/cifar.py @@ -0,0 +1,167 @@ +import os.path +import pickle +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import check_integrity, download_and_extract_archive +from .vision import VisionDataset + + +class CIFAR10(VisionDataset): + """`CIFAR10 `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``cifar-10-batches-py`` exists or will be saved to if download is set to True. + train (bool, optional): If True, creates dataset from training set, otherwise + creates from test set. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + base_folder = "cifar-10-batches-py" + url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" + filename = "cifar-10-python.tar.gz" + tgz_md5 = "c58f30108f718f92721af3b95e74349a" + train_list = [ + ["data_batch_1", "c99cafc152244af753f735de768cd75f"], + ["data_batch_2", "d4bba439e000b95fd0a9bffe97cbabec"], + ["data_batch_3", "54ebc095f3ab1f0389bbae665268c751"], + ["data_batch_4", "634d18415352ddfa80567beed471001a"], + ["data_batch_5", "482c414d41f54cd18b22e5b47cb7c3cb"], + ] + + test_list = [ + ["test_batch", "40351d587109b95175f43aff81a1287e"], + ] + meta = { + "filename": "batches.meta", + "key": "label_names", + "md5": "5ff9c542aee3614f3951f8cda6e48888", + } + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + + super().__init__(root, transform=transform, target_transform=target_transform) + + self.train = train # training set or test set + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + if self.train: + downloaded_list = self.train_list + else: + downloaded_list = self.test_list + + self.data: Any = [] + self.targets = [] + + # now load the picked numpy arrays + for file_name, checksum in downloaded_list: + file_path = os.path.join(self.root, self.base_folder, file_name) + with open(file_path, "rb") as f: + entry = pickle.load(f, encoding="latin1") + self.data.append(entry["data"]) + if "labels" in entry: + self.targets.extend(entry["labels"]) + else: + self.targets.extend(entry["fine_labels"]) + + self.data = np.vstack(self.data).reshape(-1, 3, 32, 32) + self.data = self.data.transpose((0, 2, 3, 1)) # convert to HWC + + self._load_meta() + + def _load_meta(self) -> None: + path = os.path.join(self.root, self.base_folder, self.meta["filename"]) + if not check_integrity(path, self.meta["md5"]): + raise RuntimeError("Dataset metadata file not found or corrupted. You can use download=True to download it") + with open(path, "rb") as infile: + data = pickle.load(infile, encoding="latin1") + self.classes = data[self.meta["key"]] + self.class_to_idx = {_class: i for i, _class in enumerate(self.classes)} + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], self.targets[index] + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = Image.fromarray(img) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + def _check_integrity(self) -> bool: + for filename, md5 in self.train_list + self.test_list: + fpath = os.path.join(self.root, self.base_folder, filename) + if not check_integrity(fpath, md5): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5) + + def extra_repr(self) -> str: + split = "Train" if self.train is True else "Test" + return f"Split: {split}" + + +class CIFAR100(CIFAR10): + """`CIFAR100 `_ Dataset. + + This is a subclass of the `CIFAR10` Dataset. + """ + + base_folder = "cifar-100-python" + url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz" + filename = "cifar-100-python.tar.gz" + tgz_md5 = "eb9058c3a382ffc7106e4002c42a8d85" + train_list = [ + ["train", "16019d7e3df5f24257cddd939b257f8d"], + ] + + test_list = [ + ["test", "f0ef6b0ae62326f3e7ffdfab6717acfc"], + ] + meta = { + "filename": "meta", + "key": "fine_label_names", + "md5": "7973b15100ade9c7d40fb424638fde48", + } diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/cityscapes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..a124439932f98b53d88e9ebc1db59068ae910989 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/cityscapes.py @@ -0,0 +1,222 @@ +import json +import os +from collections import namedtuple +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import extract_archive, iterable_to_str, verify_str_arg +from .vision import VisionDataset + + +class Cityscapes(VisionDataset): + """`Cityscapes `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory ``leftImg8bit`` + and ``gtFine`` or ``gtCoarse`` are located. + split (string, optional): The image split to use, ``train``, ``test`` or ``val`` if mode="fine" + otherwise ``train``, ``train_extra`` or ``val`` + mode (string, optional): The quality mode to use, ``fine`` or ``coarse`` + target_type (string or list, optional): Type of target to use, ``instance``, ``semantic``, ``polygon`` + or ``color``. Can also be a list to output a tuple with all specified target types. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + + Examples: + + Get semantic segmentation target + + .. code-block:: python + + dataset = Cityscapes('./data/cityscapes', split='train', mode='fine', + target_type='semantic') + + img, smnt = dataset[0] + + Get multiple targets + + .. code-block:: python + + dataset = Cityscapes('./data/cityscapes', split='train', mode='fine', + target_type=['instance', 'color', 'polygon']) + + img, (inst, col, poly) = dataset[0] + + Validate on the "coarse" set + + .. code-block:: python + + dataset = Cityscapes('./data/cityscapes', split='val', mode='coarse', + target_type='semantic') + + img, smnt = dataset[0] + """ + + # Based on https://github.com/mcordts/cityscapesScripts + CityscapesClass = namedtuple( + "CityscapesClass", + ["name", "id", "train_id", "category", "category_id", "has_instances", "ignore_in_eval", "color"], + ) + + classes = [ + CityscapesClass("unlabeled", 0, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("ego vehicle", 1, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("rectification border", 2, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("out of roi", 3, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("static", 4, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("dynamic", 5, 255, "void", 0, False, True, (111, 74, 0)), + CityscapesClass("ground", 6, 255, "void", 0, False, True, (81, 0, 81)), + CityscapesClass("road", 7, 0, "flat", 1, False, False, (128, 64, 128)), + CityscapesClass("sidewalk", 8, 1, "flat", 1, False, False, (244, 35, 232)), + CityscapesClass("parking", 9, 255, "flat", 1, False, True, (250, 170, 160)), + CityscapesClass("rail track", 10, 255, "flat", 1, False, True, (230, 150, 140)), + CityscapesClass("building", 11, 2, "construction", 2, False, False, (70, 70, 70)), + CityscapesClass("wall", 12, 3, "construction", 2, False, False, (102, 102, 156)), + CityscapesClass("fence", 13, 4, "construction", 2, False, False, (190, 153, 153)), + CityscapesClass("guard rail", 14, 255, "construction", 2, False, True, (180, 165, 180)), + CityscapesClass("bridge", 15, 255, "construction", 2, False, True, (150, 100, 100)), + CityscapesClass("tunnel", 16, 255, "construction", 2, False, True, (150, 120, 90)), + CityscapesClass("pole", 17, 5, "object", 3, False, False, (153, 153, 153)), + CityscapesClass("polegroup", 18, 255, "object", 3, False, True, (153, 153, 153)), + CityscapesClass("traffic light", 19, 6, "object", 3, False, False, (250, 170, 30)), + CityscapesClass("traffic sign", 20, 7, "object", 3, False, False, (220, 220, 0)), + CityscapesClass("vegetation", 21, 8, "nature", 4, False, False, (107, 142, 35)), + CityscapesClass("terrain", 22, 9, "nature", 4, False, False, (152, 251, 152)), + CityscapesClass("sky", 23, 10, "sky", 5, False, False, (70, 130, 180)), + CityscapesClass("person", 24, 11, "human", 6, True, False, (220, 20, 60)), + CityscapesClass("rider", 25, 12, "human", 6, True, False, (255, 0, 0)), + CityscapesClass("car", 26, 13, "vehicle", 7, True, False, (0, 0, 142)), + CityscapesClass("truck", 27, 14, "vehicle", 7, True, False, (0, 0, 70)), + CityscapesClass("bus", 28, 15, "vehicle", 7, True, False, (0, 60, 100)), + CityscapesClass("caravan", 29, 255, "vehicle", 7, True, True, (0, 0, 90)), + CityscapesClass("trailer", 30, 255, "vehicle", 7, True, True, (0, 0, 110)), + CityscapesClass("train", 31, 16, "vehicle", 7, True, False, (0, 80, 100)), + CityscapesClass("motorcycle", 32, 17, "vehicle", 7, True, False, (0, 0, 230)), + CityscapesClass("bicycle", 33, 18, "vehicle", 7, True, False, (119, 11, 32)), + CityscapesClass("license plate", -1, -1, "vehicle", 7, False, True, (0, 0, 142)), + ] + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + mode: str = "fine", + target_type: Union[list[str], str] = "instance", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms, transform, target_transform) + self.mode = "gtFine" if mode == "fine" else "gtCoarse" + self.images_dir = os.path.join(self.root, "leftImg8bit", split) + self.targets_dir = os.path.join(self.root, self.mode, split) + self.target_type = target_type + self.split = split + self.images = [] + self.targets = [] + + verify_str_arg(mode, "mode", ("fine", "coarse")) + if mode == "fine": + valid_modes = ("train", "test", "val") + else: + valid_modes = ("train", "train_extra", "val") + msg = "Unknown value '{}' for argument split if mode is '{}'. Valid values are {{{}}}." + msg = msg.format(split, mode, iterable_to_str(valid_modes)) + verify_str_arg(split, "split", valid_modes, msg) + + if not isinstance(target_type, list): + self.target_type = [target_type] + [ + verify_str_arg(value, "target_type", ("instance", "semantic", "polygon", "color")) + for value in self.target_type + ] + + if not os.path.isdir(self.images_dir) or not os.path.isdir(self.targets_dir): + + if split == "train_extra": + image_dir_zip = os.path.join(self.root, "leftImg8bit_trainextra.zip") + else: + image_dir_zip = os.path.join(self.root, "leftImg8bit_trainvaltest.zip") + + if self.mode == "gtFine": + target_dir_zip = os.path.join(self.root, f"{self.mode}_trainvaltest.zip") + elif self.mode == "gtCoarse": + target_dir_zip = os.path.join(self.root, f"{self.mode}.zip") + + if os.path.isfile(image_dir_zip) and os.path.isfile(target_dir_zip): + extract_archive(from_path=image_dir_zip, to_path=self.root) + extract_archive(from_path=target_dir_zip, to_path=self.root) + else: + raise RuntimeError( + "Dataset not found or incomplete. Please make sure all required folders for the" + ' specified "split" and "mode" are inside the "root" directory' + ) + + for city in os.listdir(self.images_dir): + img_dir = os.path.join(self.images_dir, city) + target_dir = os.path.join(self.targets_dir, city) + for file_name in os.listdir(img_dir): + target_types = [] + for t in self.target_type: + target_name = "{}_{}".format( + file_name.split("_leftImg8bit")[0], self._get_target_suffix(self.mode, t) + ) + target_types.append(os.path.join(target_dir, target_name)) + + self.images.append(os.path.join(img_dir, file_name)) + self.targets.append(target_types) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + Returns: + tuple: (image, target) where target is a tuple of all target types if target_type is a list with more + than one item. Otherwise, target is a json object if target_type="polygon", else the image segmentation. + """ + + image = Image.open(self.images[index]).convert("RGB") + + targets: Any = [] + for i, t in enumerate(self.target_type): + if t == "polygon": + target = self._load_json(self.targets[index][i]) + else: + target = Image.open(self.targets[index][i]) # type: ignore[assignment] + + targets.append(target) + + target = tuple(targets) if len(targets) > 1 else targets[0] # type: ignore[assignment] + + if self.transforms is not None: + image, target = self.transforms(image, target) + + return image, target + + def __len__(self) -> int: + return len(self.images) + + def extra_repr(self) -> str: + lines = ["Split: {split}", "Mode: {mode}", "Type: {target_type}"] + return "\n".join(lines).format(**self.__dict__) + + def _load_json(self, path: str) -> dict[str, Any]: + with open(path) as file: + data = json.load(file) + return data + + def _get_target_suffix(self, mode: str, target_type: str) -> str: + if target_type == "instance": + return f"{mode}_instanceIds.png" + elif target_type == "semantic": + return f"{mode}_labelIds.png" + elif target_type == "color": + return f"{mode}_color.png" + else: + return f"{mode}_polygons.json" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/clevr.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/clevr.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf24bc3c80a94aa2ca56b26fd0e1495374d03ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/clevr.py @@ -0,0 +1,93 @@ +import json +import pathlib +from typing import Any, Callable, Optional, Union +from urllib.parse import urlparse + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class CLEVRClassification(VisionDataset): + """`CLEVR `_ classification dataset. + + The number of objects in a scene are used as label. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory ``root/clevr`` exists or will be saved to if download is + set to True. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in them target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and puts it in root directory. If + dataset is already downloaded, it is not downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://dl.fbaipublicfiles.com/clevr/CLEVR_v1.0.zip" + _MD5 = "b11922020e72d0cd9154779b2d3d07d2" + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, pathlib.Path]], Any] = default_loader, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + super().__init__(root, transform=transform, target_transform=target_transform) + self.loader = loader + self._base_folder = pathlib.Path(self.root) / "clevr" + self._data_folder = self._base_folder / pathlib.Path(urlparse(self._URL).path).stem + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self._image_files = sorted(self._data_folder.joinpath("images", self._split).glob("*")) + + self._labels: list[Optional[int]] + if self._split != "test": + with open(self._data_folder / "scenes" / f"CLEVR_{self._split}_scenes.json") as file: + content = json.load(file) + num_objects = {scene["image_filename"]: len(scene["objects"]) for scene in content["scenes"]} + self._labels = [num_objects[image_file.name] for image_file in self._image_files] + else: + self._labels = [None] * len(self._image_files) + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file = self._image_files[idx] + label = self._labels[idx] + + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def _check_exists(self) -> bool: + return self._data_folder.exists() and self._data_folder.is_dir() + + def _download(self) -> None: + if self._check_exists(): + return + + download_and_extract_archive(self._URL, str(self._base_folder), md5=self._MD5) + + def extra_repr(self) -> str: + return f"split={self._split}" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/coco.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/coco.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3b5d2dfe4a9047ef49322501582ed9d09cb5a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/coco.py @@ -0,0 +1,111 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .vision import VisionDataset + + +class CocoDetection(VisionDataset): + """`MS Coco Detection `_ Dataset. + + It requires `pycocotools `_ to be installed, + which could be installed via ``pip install pycocotools`` or ``conda install conda-forge::pycocotools``. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + annFile (string): Path to json annotation file. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + """ + + def __init__( + self, + root: Union[str, Path], + annFile: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms, transform, target_transform) + from pycocotools.coco import COCO + + self.coco = COCO(annFile) + self.ids = list(sorted(self.coco.imgs.keys())) + + def _load_image(self, id: int) -> Image.Image: + path = self.coco.loadImgs(id)[0]["file_name"] + return Image.open(os.path.join(self.root, path)).convert("RGB") + + def _load_target(self, id: int) -> list[Any]: + return self.coco.loadAnns(self.coco.getAnnIds(id)) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + + if not isinstance(index, int): + raise ValueError(f"Index must be of type integer, got {type(index)} instead.") + + id = self.ids[index] + image = self._load_image(id) + target = self._load_target(id) + + if self.transforms is not None: + image, target = self.transforms(image, target) + + return image, target + + def __len__(self) -> int: + return len(self.ids) + + +class CocoCaptions(CocoDetection): + """`MS Coco Captions `_ Dataset. + + It requires `pycocotools `_ to be installed, + which could be installed via ``pip install pycocotools`` or ``conda install conda-forge::pycocotools``. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + annFile (string): Path to json annotation file. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + + Example: + + .. code:: python + + import torchvision.datasets as dset + import torchvision.transforms as transforms + cap = dset.CocoCaptions(root = 'dir where images are', + annFile = 'json annotation file', + transform=transforms.PILToTensor()) + + print('Number of samples: ', len(cap)) + img, target = cap[3] # load 4th sample + + print("Image Size: ", img.size()) + print(target) + + Output: :: + + Number of samples: 82783 + Image Size: (3L, 427L, 640L) + [u'A plane emitting smoke stream flying over a mountain.', + u'A plane darts across a bright blue sky behind a mountain covered in snow', + u'A plane leaves a contrail above the snowy mountain top.', + u'A mountain that has a plane flying overheard in the distance.', + u'A mountain view with a plume of smoke in the background'] + + """ + + def _load_target(self, id: int) -> list[str]: + return [ann["caption"] for ann in super()._load_target(id)] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/country211.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/country211.py new file mode 100644 index 0000000000000000000000000000000000000000..50d49db00a72e2592f15329b70f4f0cdbfa6b128 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/country211.py @@ -0,0 +1,67 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, ImageFolder +from .utils import download_and_extract_archive, verify_str_arg + + +class Country211(ImageFolder): + """`The Country211 Data Set `_ from OpenAI. + + This dataset was built by filtering the images from the YFCC100m dataset + that have GPS coordinate corresponding to a ISO-3166 country code. The + dataset is balanced by sampling 150 train images, 50 validation images, and + 100 test images for each country. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"valid"`` and ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and puts it into + ``root/country211/``. If dataset is already downloaded, it is not downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://openaipublic.azureedge.net/clip/data/country211.tgz" + _MD5 = "84988d7644798601126c29e9877aab6a" + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "valid", "test")) + + root = Path(root).expanduser() + self.root = str(root) + self._base_folder = root / "country211" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + super().__init__( + str(self._base_folder / self._split), + transform=transform, + target_transform=target_transform, + loader=loader, + ) + self.root = str(root) + + def _check_exists(self) -> bool: + return self._base_folder.exists() and self._base_folder.is_dir() + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/dtd.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/dtd.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb347955d420e04a68cb7055c46409293235b62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/dtd.py @@ -0,0 +1,105 @@ +import os +import pathlib +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class DTD(VisionDataset): + """`Describable Textures Dataset (DTD) `_. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. + partition (int, optional): The dataset partition. Should be ``1 <= partition <= 10``. Defaults to ``1``. + + .. note:: + + The partition only changes which split each image belongs to. Thus, regardless of the selected + partition, combining all splits will result in all images. + + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://www.robots.ox.ac.uk/~vgg/data/dtd/download/dtd-r1.0.1.tar.gz" + _MD5 = "fff73e5086ae6bdbea199a49dfb8a4c1" + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + partition: int = 1, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, pathlib.Path]], Any] = default_loader, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + if not isinstance(partition, int) and not (1 <= partition <= 10): + raise ValueError( + f"Parameter 'partition' should be an integer with `1 <= partition <= 10`, " + f"but got {partition} instead" + ) + self._partition = partition + + super().__init__(root, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / type(self).__name__.lower() + self._data_folder = self._base_folder / "dtd" + self._meta_folder = self._data_folder / "labels" + self._images_folder = self._data_folder / "images" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self._image_files = [] + classes = [] + with open(self._meta_folder / f"{self._split}{self._partition}.txt") as file: + for line in file: + cls, name = line.strip().split("/") + self._image_files.append(self._images_folder.joinpath(cls, name)) + classes.append(cls) + + self.classes = sorted(set(classes)) + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + self._labels = [self.class_to_idx[cls] for cls in classes] + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}, partition={self._partition}" + + def _check_exists(self) -> bool: + return os.path.exists(self._data_folder) and os.path.isdir(self._data_folder) + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=str(self._base_folder), md5=self._MD5) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/eurosat.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/eurosat.py new file mode 100644 index 0000000000000000000000000000000000000000..4efec57029f617b04b5822489e396bb60ba9b639 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/eurosat.py @@ -0,0 +1,71 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, ImageFolder +from .utils import download_and_extract_archive + + +class EuroSAT(ImageFolder): + """RGB version of the `EuroSAT `_ Dataset. + + For the MS version of the dataset, see + `TorchGeo `__. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``root/eurosat`` exists. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + self.root = os.path.expanduser(root) + self._base_folder = os.path.join(self.root, "eurosat") + self._data_folder = os.path.join(self._base_folder, "2750") + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + super().__init__( + self._data_folder, + transform=transform, + target_transform=target_transform, + loader=loader, + ) + self.root = os.path.expanduser(root) + + def __len__(self) -> int: + return len(self.samples) + + def _check_exists(self) -> bool: + return os.path.exists(self._data_folder) + + def download(self) -> None: + + if self._check_exists(): + return + + os.makedirs(self._base_folder, exist_ok=True) + download_and_extract_archive( + "https://huggingface.co/datasets/torchgeo/eurosat/resolve/c877bcd43f099cd0196738f714544e355477f3fd/EuroSAT.zip", + download_root=self._base_folder, + md5="c8fa014336c82ac7804f0398fcb19387", + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fakedata.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fakedata.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb413cdd32e784d962b9be46d53cf319fd677e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fakedata.py @@ -0,0 +1,67 @@ +from typing import Any, Callable, Optional + +import torch + +from .. import transforms +from .vision import VisionDataset + + +class FakeData(VisionDataset): + """A fake dataset that returns randomly generated images and returns them as PIL images + + Args: + size (int, optional): Size of the dataset. Default: 1000 images + image_size(tuple, optional): Size of the returned images. Default: (3, 224, 224) + num_classes(int, optional): Number of classes in the dataset. Default: 10 + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + random_offset (int): Offsets the index-based random seed used to + generate each image. Default: 0 + + """ + + def __init__( + self, + size: int = 1000, + image_size: tuple[int, int, int] = (3, 224, 224), + num_classes: int = 10, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + random_offset: int = 0, + ) -> None: + super().__init__(transform=transform, target_transform=target_transform) + self.size = size + self.num_classes = num_classes + self.image_size = image_size + self.random_offset = random_offset + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is class_index of the target class. + """ + # create random image that is consistent with the index id + if index >= len(self): + raise IndexError(f"{self.__class__.__name__} index out of range") + rng_state = torch.get_rng_state() + torch.manual_seed(index + self.random_offset) + img = torch.randn(*self.image_size) + target = torch.randint(0, self.num_classes, size=(1,), dtype=torch.long)[0] + torch.set_rng_state(rng_state) + + # convert to PIL Image + img = transforms.ToPILImage()(img) + if self.transform is not None: + img = self.transform(img) + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target.item() + + def __len__(self) -> int: + return self.size diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fer2013.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fer2013.py new file mode 100644 index 0000000000000000000000000000000000000000..f33afbeebc82e5bc62feb23bdefffe7a1472e22f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fer2013.py @@ -0,0 +1,120 @@ +import csv +import pathlib +from typing import Any, Callable, Optional, Union + +import torch +from PIL import Image + +from .utils import check_integrity, verify_str_arg +from .vision import VisionDataset + + +class FER2013(VisionDataset): + """`FER2013 + `_ Dataset. + + .. note:: + This dataset can return test labels only if ``fer2013.csv`` OR + ``icml_face_data.csv`` are present in ``root/fer2013/``. If only + ``train.csv`` and ``test.csv`` are present, the test labels are set to + ``None``. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``root/fer2013`` exists. This directory may contain either + ``fer2013.csv``, ``icml_face_data.csv``, or both ``train.csv`` and + ``test.csv``. Precendence is given in that order, i.e. if + ``fer2013.csv`` is present then the rest of the files will be + ignored. All these (combinations of) files contain the same data and + are supported for convenience, but only ``fer2013.csv`` and + ``icml_face_data.csv`` are able to return non-None test labels. + split (string, optional): The dataset split, supports ``"train"`` (default), or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + """ + + _RESOURCES = { + "train": ("train.csv", "3f0dfb3d3fd99c811a1299cb947e3131"), + "test": ("test.csv", "b02c2298636a634e8c2faabbf3ea9a23"), + # The fer2013.csv and icml_face_data.csv files contain both train and + # tests instances, and unlike test.csv they contain the labels for the + # test instances. We give these 2 files precedence over train.csv and + # test.csv. And yes, they both contain the same data, but with different + # column names (note the spaces) and ordering: + # $ head -n 1 fer2013.csv icml_face_data.csv train.csv test.csv + # ==> fer2013.csv <== + # emotion,pixels,Usage + # + # ==> icml_face_data.csv <== + # emotion, Usage, pixels + # + # ==> train.csv <== + # emotion,pixels + # + # ==> test.csv <== + # pixels + "fer": ("fer2013.csv", "f8428a1edbd21e88f42c73edd2a14f95"), + "icml": ("icml_face_data.csv", "b114b9e04e6949e5fe8b6a98b3892b1d"), + } + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "test")) + super().__init__(root, transform=transform, target_transform=target_transform) + + base_folder = pathlib.Path(self.root) / "fer2013" + use_fer_file = (base_folder / self._RESOURCES["fer"][0]).exists() + use_icml_file = not use_fer_file and (base_folder / self._RESOURCES["icml"][0]).exists() + file_name, md5 = self._RESOURCES["fer" if use_fer_file else "icml" if use_icml_file else self._split] + data_file = base_folder / file_name + if not check_integrity(str(data_file), md5=md5): + raise RuntimeError( + f"{file_name} not found in {base_folder} or corrupted. " + f"You can download it from " + f"https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge" + ) + + pixels_key = " pixels" if use_icml_file else "pixels" + usage_key = " Usage" if use_icml_file else "Usage" + + def get_img(row): + return torch.tensor([int(idx) for idx in row[pixels_key].split()], dtype=torch.uint8).reshape(48, 48) + + def get_label(row): + if use_fer_file or use_icml_file or self._split == "train": + return int(row["emotion"]) + else: + return None + + with open(data_file, newline="") as file: + rows = (row for row in csv.DictReader(file)) + + if use_fer_file or use_icml_file: + valid_keys = ("Training",) if self._split == "train" else ("PublicTest", "PrivateTest") + rows = (row for row in rows if row[usage_key] in valid_keys) + + self._samples = [(get_img(row), get_label(row)) for row in rows] + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_tensor, target = self._samples[idx] + image = Image.fromarray(image_tensor.numpy()) + + if self.transform is not None: + image = self.transform(image) + + if self.target_transform is not None: + target = self.target_transform(target) + + return image, target + + def extra_repr(self) -> str: + return f"split={self._split}" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fgvc_aircraft.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fgvc_aircraft.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f2277b23353fda4191bc1e6df87a805600e10d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/fgvc_aircraft.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import os +from pathlib import Path +from typing import Any, Callable + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class FGVCAircraft(VisionDataset): + """`FGVC Aircraft `_ Dataset. + + The dataset contains 10,000 images of aircraft, with 100 images for each of 100 + different aircraft model variants, most of which are airplanes. + Aircraft models are organized in a three-levels hierarchy. The three levels, from + finer to coarser, are: + + - ``variant``, e.g. Boeing 737-700. A variant collapses all the models that are visually + indistinguishable into one class. The dataset comprises 100 different variants. + - ``family``, e.g. Boeing 737. The dataset comprises 70 different families. + - ``manufacturer``, e.g. Boeing. The dataset comprises 30 different manufacturers. + + Args: + root (str or ``pathlib.Path``): Root directory of the FGVC Aircraft dataset. + split (string, optional): The dataset split, supports ``train``, ``val``, + ``trainval`` and ``test``. + annotation_level (str, optional): The annotation level, supports ``variant``, + ``family`` and ``manufacturer``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/archives/fgvc-aircraft-2013b.tar.gz" + + def __init__( + self, + root: str | Path, + split: str = "trainval", + annotation_level: str = "variant", + transform: Callable | None = None, + target_transform: Callable | None = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "val", "trainval", "test")) + self._annotation_level = verify_str_arg( + annotation_level, "annotation_level", ("variant", "family", "manufacturer") + ) + + self._data_path = os.path.join(self.root, "fgvc-aircraft-2013b") + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + annotation_file = os.path.join( + self._data_path, + "data", + { + "variant": "variants.txt", + "family": "families.txt", + "manufacturer": "manufacturers.txt", + }[self._annotation_level], + ) + with open(annotation_file) as f: + self.classes = [line.strip() for line in f] + + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + + image_data_folder = os.path.join(self._data_path, "data", "images") + labels_file = os.path.join(self._data_path, "data", f"images_{self._annotation_level}_{self._split}.txt") + + self._image_files = [] + self._labels = [] + + with open(labels_file) as f: + for line in f: + image_name, label_name = line.strip().split(" ", 1) + self._image_files.append(os.path.join(image_data_folder, f"{image_name}.jpg")) + self._labels.append(self.class_to_idx[label_name]) + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def _download(self) -> None: + """ + Download the FGVC Aircraft dataset archive and extract it under root. + """ + if self._check_exists(): + return + download_and_extract_archive(self._URL, self.root) + + def _check_exists(self) -> bool: + return os.path.exists(self._data_path) and os.path.isdir(self._data_path) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/flickr.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/flickr.py new file mode 100644 index 0000000000000000000000000000000000000000..84f1dc0e1702d0a263d8c8a05dcaad47dde35a14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/flickr.py @@ -0,0 +1,176 @@ +import glob +import os +from collections import defaultdict +from html.parser import HTMLParser +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader +from .vision import VisionDataset + + +class Flickr8kParser(HTMLParser): + """Parser for extracting captions from the Flickr8k dataset web page.""" + + def __init__(self, root: Union[str, Path]) -> None: + super().__init__() + + self.root = root + + # Data structure to store captions + self.annotations: dict[str, list[str]] = {} + + # State variables + self.in_table = False + self.current_tag: Optional[str] = None + self.current_img: Optional[str] = None + + def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: + self.current_tag = tag + + if tag == "table": + self.in_table = True + + def handle_endtag(self, tag: str) -> None: + self.current_tag = None + + if tag == "table": + self.in_table = False + + def handle_data(self, data: str) -> None: + if self.in_table: + if data == "Image Not Found": + self.current_img = None + elif self.current_tag == "a": + img_id = data.split("/")[-2] + img_id = os.path.join(self.root, img_id + "_*.jpg") + img_id = glob.glob(img_id)[0] + self.current_img = img_id + self.annotations[img_id] = [] + elif self.current_tag == "li" and self.current_img: + img_id = self.current_img + self.annotations[img_id].append(data.strip()) + + +class Flickr8k(VisionDataset): + """`Flickr8k Entities `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + ann_file (string): Path to annotation file. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + ann_file: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.ann_file = os.path.expanduser(ann_file) + + # Read annotations and store in a dict + parser = Flickr8kParser(self.root) + with open(self.ann_file) as fh: + parser.feed(fh.read()) + self.annotations = parser.annotations + + self.ids = list(sorted(self.annotations.keys())) + self.loader = loader + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target). target is a list of captions for the image. + """ + img_id = self.ids[index] + + # Image + img = self.loader(img_id) + if self.transform is not None: + img = self.transform(img) + + # Captions + target = self.annotations[img_id] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.ids) + + +class Flickr30k(VisionDataset): + """`Flickr30k Entities `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + ann_file (string): Path to annotation file. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: str, + ann_file: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.ann_file = os.path.expanduser(ann_file) + + # Read annotations and store in a dict + self.annotations = defaultdict(list) + with open(self.ann_file) as fh: + for line in fh: + img_id, caption = line.strip().split("\t") + self.annotations[img_id[:-2]].append(caption) + + self.ids = list(sorted(self.annotations.keys())) + self.loader = loader + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target). target is a list of captions for the image. + """ + img_id = self.ids[index] + + # Image + filename = os.path.join(self.root, img_id) + img = self.loader(filename) + if self.transform is not None: + img = self.transform(img) + + # Captions + target = self.annotations[img_id] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.ids) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/flowers102.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/flowers102.py new file mode 100644 index 0000000000000000000000000000000000000000..80bca71e9676869c49a9f9f01d8b6e6df7323a23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/flowers102.py @@ -0,0 +1,225 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg +from .vision import VisionDataset + + +class Flowers102(VisionDataset): + """`Oxford 102 Flower `_ Dataset. + + .. warning:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Oxford 102 Flower is an image classification dataset consisting of 102 flower categories. The + flowers were chosen to be flowers commonly occurring in the United Kingdom. Each class consists of + between 40 and 258 images. + + The images have large scale, pose and light variations. In addition, there are categories that + have large variations within the category, and several very similar categories. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _download_url_prefix = "https://www.robots.ox.ac.uk/~vgg/data/flowers/102/" + _file_dict = { # filename, md5 + "image": ("102flowers.tgz", "52808999861908f626f3c1f4e79d11fa"), + "label": ("imagelabels.mat", "e0620be6f572b9609742df49c70aed4d"), + "setid": ("setid.mat", "a5357ecc9cb78c4bef273ce3793fc85c"), + } + _splits_map = {"train": "trnid", "val": "valid", "test": "tstid"} + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, Path]], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + self._base_folder = Path(self.root) / "flowers-102" + self._images_folder = self._base_folder / "jpg" + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + from scipy.io import loadmat + + set_ids = loadmat(self._base_folder / self._file_dict["setid"][0], squeeze_me=True) + image_ids = set_ids[self._splits_map[self._split]].tolist() + + labels = loadmat(self._base_folder / self._file_dict["label"][0], squeeze_me=True) + image_id_to_label = dict(enumerate((labels["labels"] - 1).tolist(), 1)) + + self._labels = [] + self._image_files = [] + for image_id in image_ids: + self._labels.append(image_id_to_label[image_id]) + self._image_files.append(self._images_folder / f"image_{image_id:05d}.jpg") + + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}" + + def _check_integrity(self): + if not (self._images_folder.exists() and self._images_folder.is_dir()): + return False + + for id in ["label", "setid"]: + filename, md5 = self._file_dict[id] + if not check_integrity(str(self._base_folder / filename), md5): + return False + return True + + def download(self): + if self._check_integrity(): + return + download_and_extract_archive( + f"{self._download_url_prefix}{self._file_dict['image'][0]}", + str(self._base_folder), + md5=self._file_dict["image"][1], + ) + for id in ["label", "setid"]: + filename, md5 = self._file_dict[id] + download_url(self._download_url_prefix + filename, str(self._base_folder), md5=md5) + + classes = [ + "pink primrose", + "hard-leaved pocket orchid", + "canterbury bells", + "sweet pea", + "english marigold", + "tiger lily", + "moon orchid", + "bird of paradise", + "monkshood", + "globe thistle", + "snapdragon", + "colt's foot", + "king protea", + "spear thistle", + "yellow iris", + "globe-flower", + "purple coneflower", + "peruvian lily", + "balloon flower", + "giant white arum lily", + "fire lily", + "pincushion flower", + "fritillary", + "red ginger", + "grape hyacinth", + "corn poppy", + "prince of wales feathers", + "stemless gentian", + "artichoke", + "sweet william", + "carnation", + "garden phlox", + "love in the mist", + "mexican aster", + "alpine sea holly", + "ruby-lipped cattleya", + "cape flower", + "great masterwort", + "siam tulip", + "lenten rose", + "barbeton daisy", + "daffodil", + "sword lily", + "poinsettia", + "bolero deep blue", + "wallflower", + "marigold", + "buttercup", + "oxeye daisy", + "common dandelion", + "petunia", + "wild pansy", + "primula", + "sunflower", + "pelargonium", + "bishop of llandaff", + "gaura", + "geranium", + "orange dahlia", + "pink-yellow dahlia?", + "cautleya spicata", + "japanese anemone", + "black-eyed susan", + "silverbush", + "californian poppy", + "osteospermum", + "spring crocus", + "bearded iris", + "windflower", + "tree poppy", + "gazania", + "azalea", + "water lily", + "rose", + "thorn apple", + "morning glory", + "passion flower", + "lotus", + "toad lily", + "anthurium", + "frangipani", + "clematis", + "hibiscus", + "columbine", + "desert-rose", + "tree mallow", + "magnolia", + "cyclamen", + "watercress", + "canna lily", + "hippeastrum", + "bee balm", + "ball moss", + "foxglove", + "bougainvillea", + "camellia", + "mallow", + "mexican petunia", + "bromelia", + "blanket flower", + "trumpet creeper", + "blackberry lily", + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/folder.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/folder.py new file mode 100644 index 0000000000000000000000000000000000000000..387439c0433e8fa9f16163b1ad9629591639d09e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/folder.py @@ -0,0 +1,337 @@ +import os +import os.path +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union + +from PIL import Image + +from .vision import VisionDataset + + +def has_file_allowed_extension(filename: str, extensions: Union[str, tuple[str, ...]]) -> bool: + """Checks if a file is an allowed extension. + + Args: + filename (string): path to a file + extensions (tuple of strings): extensions to consider (lowercase) + + Returns: + bool: True if the filename ends with one of given extensions + """ + return filename.lower().endswith(extensions if isinstance(extensions, str) else tuple(extensions)) + + +def is_image_file(filename: str) -> bool: + """Checks if a file is an allowed image extension. + + Args: + filename (string): path to a file + + Returns: + bool: True if the filename ends with a known image extension + """ + return has_file_allowed_extension(filename, IMG_EXTENSIONS) + + +def find_classes(directory: Union[str, Path]) -> tuple[list[str], dict[str, int]]: + """Finds the class folders in a dataset. + + See :class:`DatasetFolder` for details. + """ + classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir()) + if not classes: + raise FileNotFoundError(f"Couldn't find any class folder in {directory}.") + + class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)} + return classes, class_to_idx + + +def make_dataset( + directory: Union[str, Path], + class_to_idx: Optional[dict[str, int]] = None, + extensions: Optional[Union[str, tuple[str, ...]]] = None, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, +) -> list[tuple[str, int]]: + """Generates a list of samples of a form (path_to_sample, class). + + See :class:`DatasetFolder` for details. + + Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function + by default. + """ + directory = os.path.expanduser(directory) + + if class_to_idx is None: + _, class_to_idx = find_classes(directory) + elif not class_to_idx: + raise ValueError("'class_to_index' must have at least one entry to collect any samples.") + + both_none = extensions is None and is_valid_file is None + both_something = extensions is not None and is_valid_file is not None + if both_none or both_something: + raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time") + + if extensions is not None: + + def is_valid_file(x: str) -> bool: + return has_file_allowed_extension(x, extensions) # type: ignore[arg-type] + + is_valid_file = cast(Callable[[str], bool], is_valid_file) + + instances = [] + available_classes = set() + for target_class in sorted(class_to_idx.keys()): + class_index = class_to_idx[target_class] + target_dir = os.path.join(directory, target_class) + if not os.path.isdir(target_dir): + continue + for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)): + for fname in sorted(fnames): + path = os.path.join(root, fname) + if is_valid_file(path): + item = path, class_index + instances.append(item) + + if target_class not in available_classes: + available_classes.add(target_class) + + empty_classes = set(class_to_idx.keys()) - available_classes + if empty_classes and not allow_empty: + msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. " + if extensions is not None: + msg += f"Supported extensions are: {extensions if isinstance(extensions, str) else ', '.join(extensions)}" + raise FileNotFoundError(msg) + + return instances + + +class DatasetFolder(VisionDataset): + """A generic data loader. + + This default directory structure can be customized by overriding the + :meth:`find_classes` method. + + Args: + root (str or ``pathlib.Path``): Root directory path. + loader (callable): A function to load a sample given its path. + extensions (tuple[string]): A list of allowed extensions. + both extensions and is_valid_file should not be passed. + transform (callable, optional): A function/transform that takes in + a sample and returns a transformed version. + E.g, ``transforms.RandomCrop`` for images. + target_transform (callable, optional): A function/transform that takes + in the target and transforms it. + is_valid_file (callable, optional): A function that takes path of a file + and check if the file is a valid file (used to check of corrupt files) + both extensions and is_valid_file should not be passed. + allow_empty(bool, optional): If True, empty folders are considered to be valid classes. + An error is raised on empty folders if False (default). + + Attributes: + classes (list): List of the class names sorted alphabetically. + class_to_idx (dict): Dict with items (class_name, class_index). + samples (list): List of (sample path, class_index) tuples + targets (list): The class_index value for each image in the dataset + """ + + def __init__( + self, + root: Union[str, Path], + loader: Callable[[str], Any], + extensions: Optional[tuple[str, ...]] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + classes, class_to_idx = self.find_classes(self.root) + samples = self.make_dataset( + self.root, + class_to_idx=class_to_idx, + extensions=extensions, + is_valid_file=is_valid_file, + allow_empty=allow_empty, + ) + + self.loader = loader + self.extensions = extensions + + self.classes = classes + self.class_to_idx = class_to_idx + self.samples = samples + self.targets = [s[1] for s in samples] + + @staticmethod + def make_dataset( + directory: Union[str, Path], + class_to_idx: dict[str, int], + extensions: Optional[tuple[str, ...]] = None, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, + ) -> list[tuple[str, int]]: + """Generates a list of samples of a form (path_to_sample, class). + + This can be overridden to e.g. read files from a compressed zip file instead of from the disk. + + Args: + directory (str): root dataset directory, corresponding to ``self.root``. + class_to_idx (Dict[str, int]): Dictionary mapping class name to class index. + extensions (optional): A list of allowed extensions. + Either extensions or is_valid_file should be passed. Defaults to None. + is_valid_file (optional): A function that takes path of a file + and checks if the file is a valid file + (used to check of corrupt files) both extensions and + is_valid_file should not be passed. Defaults to None. + allow_empty(bool, optional): If True, empty folders are considered to be valid classes. + An error is raised on empty folders if False (default). + + Raises: + ValueError: In case ``class_to_idx`` is empty. + ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None. + FileNotFoundError: In case no valid file was found for any class. + + Returns: + List[Tuple[str, int]]: samples of a form (path_to_sample, class) + """ + if class_to_idx is None: + # prevent potential bug since make_dataset() would use the class_to_idx logic of the + # find_classes() function, instead of using that of the find_classes() method, which + # is potentially overridden and thus could have a different logic. + raise ValueError("The class_to_idx parameter cannot be None.") + return make_dataset( + directory, class_to_idx, extensions=extensions, is_valid_file=is_valid_file, allow_empty=allow_empty + ) + + def find_classes(self, directory: Union[str, Path]) -> tuple[list[str], dict[str, int]]: + """Find the class folders in a dataset structured as follows:: + + directory/ + ├── class_x + │ ├── xxx.ext + │ ├── xxy.ext + │ └── ... + │ └── xxz.ext + └── class_y + ├── 123.ext + ├── nsdf3.ext + └── ... + └── asd932_.ext + + This method can be overridden to only consider + a subset of classes, or to adapt to a different dataset directory structure. + + Args: + directory(str): Root directory path, corresponding to ``self.root`` + + Raises: + FileNotFoundError: If ``dir`` has no class folders. + + Returns: + (Tuple[List[str], Dict[str, int]]): List of all classes and dictionary mapping each class to an index. + """ + return find_classes(directory) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (sample, target) where target is class_index of the target class. + """ + path, target = self.samples[index] + sample = self.loader(path) + if self.transform is not None: + sample = self.transform(sample) + if self.target_transform is not None: + target = self.target_transform(target) + + return sample, target + + def __len__(self) -> int: + return len(self.samples) + + +IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp") + + +def pil_loader(path: Union[str, Path]) -> Image.Image: + # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) + with open(path, "rb") as f: + img = Image.open(f) + return img.convert("RGB") + + +# TODO: specify the return type +def accimage_loader(path: Union[str, Path]) -> Any: + import accimage + + try: + return accimage.Image(path) + except OSError: + # Potentially a decoding problem, fall back to PIL.Image + return pil_loader(path) + + +def default_loader(path: Union[str, Path]) -> Any: + from torchvision import get_image_backend + + if get_image_backend() == "accimage": + return accimage_loader(path) + else: + return pil_loader(path) + + +class ImageFolder(DatasetFolder): + """A generic data loader where the images are arranged in this way by default: :: + + root/dog/xxx.png + root/dog/xxy.png + root/dog/[...]/xxz.png + + root/cat/123.png + root/cat/nsdf3.png + root/cat/[...]/asd932_.png + + This class inherits from :class:`~torchvision.datasets.DatasetFolder` so + the same methods can be overridden to customize the dataset. + + Args: + root (str or ``pathlib.Path``): Root directory path. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + is_valid_file (callable, optional): A function that takes path of an Image file + and check if the file is a valid file (used to check of corrupt files) + allow_empty(bool, optional): If True, empty folders are considered to be valid classes. + An error is raised on empty folders if False (default). + + Attributes: + classes (list): List of the class names sorted alphabetically. + class_to_idx (dict): Dict with items (class_name, class_index). + imgs (list): List of (image path, class_index) tuples + """ + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, + ): + super().__init__( + root, + loader, + IMG_EXTENSIONS if is_valid_file is None else None, + transform=transform, + target_transform=target_transform, + is_valid_file=is_valid_file, + allow_empty=allow_empty, + ) + self.imgs = self.samples diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/food101.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/food101.py new file mode 100644 index 0000000000000000000000000000000000000000..fee23680b05255029c1e3b433e7890df754f0fe0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/food101.py @@ -0,0 +1,98 @@ +import json +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Food101(VisionDataset): + """`The Food-101 Data Set `_. + + The Food-101 is a challenging data set of 101 food categories with 101,000 images. + For each class, 250 manually reviewed test images are provided as well as 750 training images. + On purpose, the training images were not cleaned, and thus still contain some amount of noise. + This comes mostly in the form of intense colors and sometimes wrong labels. All images were + rescaled to have a maximum side length of 512 pixels. + + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default) and ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "http://data.vision.ee.ethz.ch/cvl/food-101.tar.gz" + _MD5 = "85eeb15f3717b99a5da872d97d918f87" + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, Path]], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "test")) + self._base_folder = Path(self.root) / "food-101" + self._meta_folder = self._base_folder / "meta" + self._images_folder = self._base_folder / "images" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self._labels = [] + self._image_files = [] + with open(self._meta_folder / f"{split}.json") as f: + metadata = json.loads(f.read()) + + self.classes = sorted(metadata.keys()) + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + + for class_label, im_rel_paths in metadata.items(): + self._labels += [self.class_to_idx[class_label]] * len(im_rel_paths) + self._image_files += [ + self._images_folder.joinpath(*f"{im_rel_path}.jpg".split("/")) for im_rel_path in im_rel_paths + ] + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}" + + def _check_exists(self) -> bool: + return all(folder.exists() and folder.is_dir() for folder in (self._meta_folder, self._images_folder)) + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/gtsrb.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/gtsrb.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b60116c401dd7819f527f095990dea2193b8ec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/gtsrb.py @@ -0,0 +1,103 @@ +import csv +import pathlib +from typing import Any, Callable, Optional, Union + +import PIL + +from .folder import make_dataset +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class GTSRB(VisionDataset): + """`German Traffic Sign Recognition Benchmark (GTSRB) `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + + super().__init__(root, transform=transform, target_transform=target_transform) + + self._split = verify_str_arg(split, "split", ("train", "test")) + self._base_folder = pathlib.Path(root) / "gtsrb" + self._target_folder = ( + self._base_folder / "GTSRB" / ("Training" if self._split == "train" else "Final_Test/Images") + ) + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + if self._split == "train": + samples = make_dataset(str(self._target_folder), extensions=(".ppm",)) + else: + with open(self._base_folder / "GT-final_test.csv") as csv_file: + samples = [ + (str(self._target_folder / row["Filename"]), int(row["ClassId"])) + for row in csv.DictReader(csv_file, delimiter=";", skipinitialspace=True) + ] + + self._samples = samples + self.transform = transform + self.target_transform = target_transform + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + + path, target = self._samples[index] + sample = PIL.Image.open(path).convert("RGB") + + if self.transform is not None: + sample = self.transform(sample) + + if self.target_transform is not None: + target = self.target_transform(target) + + return sample, target + + def _check_exists(self) -> bool: + return self._target_folder.is_dir() + + def download(self) -> None: + if self._check_exists(): + return + + base_url = "https://sid.erda.dk/public/archives/daaeac0d7ce1152aea9b61d9f1e19370/" + + if self._split == "train": + download_and_extract_archive( + f"{base_url}GTSRB-Training_fixed.zip", + download_root=str(self._base_folder), + md5="513f3c79a4c5141765e10e952eaa2478", + ) + else: + download_and_extract_archive( + f"{base_url}GTSRB_Final_Test_Images.zip", + download_root=str(self._base_folder), + md5="c7e4e6327067d32654124b0fe9e82185", + ) + download_and_extract_archive( + f"{base_url}GTSRB_Final_Test_GT.zip", + download_root=str(self._base_folder), + md5="fe31e9c9270bbcd7b84b7f21a9d9d9e5", + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/hmdb51.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/hmdb51.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b84771cac21e41cc27b2e18f18922ec7e74952 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/hmdb51.py @@ -0,0 +1,152 @@ +import glob +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from torch import Tensor + +from .folder import find_classes, make_dataset +from .video_utils import VideoClips +from .vision import VisionDataset + + +class HMDB51(VisionDataset): + """ + `HMDB51 `_ + dataset. + + HMDB51 is an action recognition video dataset. + This dataset consider every video as a collection of video clips of fixed size, specified + by ``frames_per_clip``, where the step in frames between each clip is given by + ``step_between_clips``. + + To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5`` + and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two + elements will come from video 1, and the next three elements from video 2. + Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all + frames in a video might be present. + + Internally, it uses a VideoClips object to handle clip creation. + + Args: + root (str or ``pathlib.Path``): Root directory of the HMDB51 Dataset. + annotation_path (str): Path to the folder containing the split files. + frames_per_clip (int): Number of frames in a clip. + step_between_clips (int): Number of frames between each clip. + fold (int, optional): Which fold to use. Should be between 1 and 3. + train (bool, optional): If ``True``, creates a dataset from the train split, + otherwise from the ``test`` split. + transform (callable, optional): A function/transform that takes in a TxHxWxC video + and returns a transformed version. + output_format (str, optional): The format of the output video tensors (before transforms). + Can be either "THWC" (default) or "TCHW". + + Returns: + tuple: A 3-tuple with the following entries: + + - video (Tensor[T, H, W, C] or Tensor[T, C, H, W]): The `T` video frames + - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels + and `L` is the number of points + - label (int): class of the video clip + """ + + data_url = "https://serre-lab.clps.brown.edu/wp-content/uploads/2013/10/hmdb51_org.rar" + splits = { + "url": "https://serre-lab.clps.brown.edu/wp-content/uploads/2013/10/test_train_splits.rar", + "md5": "15e67781e70dcfbdce2d7dbb9b3344b5", + } + TRAIN_TAG = 1 + TEST_TAG = 2 + + def __init__( + self, + root: Union[str, Path], + annotation_path: str, + frames_per_clip: int, + step_between_clips: int = 1, + frame_rate: Optional[int] = None, + fold: int = 1, + train: bool = True, + transform: Optional[Callable] = None, + _precomputed_metadata: Optional[dict[str, Any]] = None, + num_workers: int = 1, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _audio_samples: int = 0, + output_format: str = "THWC", + ) -> None: + super().__init__(root) + if fold not in (1, 2, 3): + raise ValueError(f"fold should be between 1 and 3, got {fold}") + + extensions = ("avi",) + self.classes, class_to_idx = find_classes(self.root) + self.samples = make_dataset( + self.root, + class_to_idx, + extensions, + ) + + video_paths = [path for (path, _) in self.samples] + video_clips = VideoClips( + video_paths, + frames_per_clip, + step_between_clips, + frame_rate, + _precomputed_metadata, + num_workers=num_workers, + _video_width=_video_width, + _video_height=_video_height, + _video_min_dimension=_video_min_dimension, + _audio_samples=_audio_samples, + output_format=output_format, + ) + # we bookkeep the full version of video clips because we want to be able + # to return the metadata of full version rather than the subset version of + # video clips + self.full_video_clips = video_clips + self.fold = fold + self.train = train + self.indices = self._select_fold(video_paths, annotation_path, fold, train) + self.video_clips = video_clips.subset(self.indices) + self.transform = transform + + @property + def metadata(self) -> dict[str, Any]: + return self.full_video_clips.metadata + + def _select_fold(self, video_list: list[str], annotations_dir: str, fold: int, train: bool) -> list[int]: + target_tag = self.TRAIN_TAG if train else self.TEST_TAG + split_pattern_name = f"*test_split{fold}.txt" + split_pattern_path = os.path.join(annotations_dir, split_pattern_name) + annotation_paths = glob.glob(split_pattern_path) + selected_files = set() + for filepath in annotation_paths: + with open(filepath) as fid: + lines = fid.readlines() + for line in lines: + video_filename, tag_string = line.split() + tag = int(tag_string) + if tag == target_tag: + selected_files.add(video_filename) + + indices = [] + for video_index, video_path in enumerate(video_list): + if os.path.basename(video_path) in selected_files: + indices.append(video_index) + + return indices + + def __len__(self) -> int: + return self.video_clips.num_clips() + + def __getitem__(self, idx: int) -> tuple[Tensor, Tensor, int]: + video, audio, _, video_idx = self.video_clips.get_clip(idx) + sample_index = self.indices[video_idx] + _, class_index = self.samples[sample_index] + + if self.transform is not None: + video = self.transform(video) + + return video, audio, class_index diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/imagenet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/imagenet.py new file mode 100644 index 0000000000000000000000000000000000000000..1808dc4f85b0bb77ac2fa469f17b5f903621f608 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/imagenet.py @@ -0,0 +1,222 @@ +import os +import shutil +import tempfile +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Optional, Union + +import torch + +from .folder import ImageFolder +from .utils import check_integrity, extract_archive, verify_str_arg + +ARCHIVE_META = { + "train": ("ILSVRC2012_img_train.tar", "1d675b47d978889d74fa0da5fadfb00e"), + "val": ("ILSVRC2012_img_val.tar", "29b22e2961454d5413ddabcf34fc5622"), + "devkit": ("ILSVRC2012_devkit_t12.tar.gz", "fa75699e90414af021442c21a62c3abf"), +} + +META_FILE = "meta.bin" + + +class ImageNet(ImageFolder): + """`ImageNet `_ 2012 Classification Dataset. + + .. note:: + Before using this class, it is required to download ImageNet 2012 dataset from + `here `_ and + place the files ``ILSVRC2012_devkit_t12.tar.gz`` and ``ILSVRC2012_img_train.tar`` + or ``ILSVRC2012_img_val.tar`` based on ``split`` in the root directory. + + Args: + root (str or ``pathlib.Path``): Root directory of the ImageNet Dataset. + split (string, optional): The dataset split, supports ``train``, or ``val``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + + Attributes: + classes (list): List of the class name tuples. + class_to_idx (dict): Dict with items (class_name, class_index). + wnids (list): List of the WordNet IDs. + wnid_to_idx (dict): Dict with items (wordnet_id, class_index). + imgs (list): List of (image path, class_index) tuples + targets (list): The class_index value for each image in the dataset + """ + + def __init__(self, root: Union[str, Path], split: str = "train", **kwargs: Any) -> None: + root = self.root = os.path.expanduser(root) + self.split = verify_str_arg(split, "split", ("train", "val")) + + self.parse_archives() + wnid_to_classes = load_meta_file(self.root)[0] + + super().__init__(self.split_folder, **kwargs) + self.root = root + + self.wnids = self.classes + self.wnid_to_idx = self.class_to_idx + self.classes = [wnid_to_classes[wnid] for wnid in self.wnids] + self.class_to_idx = {cls: idx for idx, clss in enumerate(self.classes) for cls in clss} + + def parse_archives(self) -> None: + if not check_integrity(os.path.join(self.root, META_FILE)): + parse_devkit_archive(self.root) + + if not os.path.isdir(self.split_folder): + if self.split == "train": + parse_train_archive(self.root) + elif self.split == "val": + parse_val_archive(self.root) + + @property + def split_folder(self) -> str: + return os.path.join(self.root, self.split) + + def extra_repr(self) -> str: + return "Split: {split}".format(**self.__dict__) + + +def load_meta_file(root: Union[str, Path], file: Optional[str] = None) -> tuple[dict[str, str], list[str]]: + if file is None: + file = META_FILE + file = os.path.join(root, file) + + if check_integrity(file): + return torch.load(file, weights_only=True) + else: + msg = ( + "The meta file {} is not present in the root directory or is corrupted. " + "This file is automatically created by the ImageNet dataset." + ) + raise RuntimeError(msg.format(file, root)) + + +def _verify_archive(root: Union[str, Path], file: str, md5: str) -> None: + if not check_integrity(os.path.join(root, file), md5): + msg = ( + "The archive {} is not present in the root directory or is corrupted. " + "You need to download it externally and place it in {}." + ) + raise RuntimeError(msg.format(file, root)) + + +def parse_devkit_archive(root: Union[str, Path], file: Optional[str] = None) -> None: + """Parse the devkit archive of the ImageNet2012 classification dataset and save + the meta information in a binary file. + + Args: + root (str or ``pathlib.Path``): Root directory containing the devkit archive + file (str, optional): Name of devkit archive. Defaults to + 'ILSVRC2012_devkit_t12.tar.gz' + """ + import scipy.io as sio + + def parse_meta_mat(devkit_root: str) -> tuple[dict[int, str], dict[str, tuple[str, ...]]]: + metafile = os.path.join(devkit_root, "data", "meta.mat") + meta = sio.loadmat(metafile, squeeze_me=True)["synsets"] + nums_children = list(zip(*meta))[4] + meta = [meta[idx] for idx, num_children in enumerate(nums_children) if num_children == 0] + idcs, wnids, classes = list(zip(*meta))[:3] + classes = [tuple(clss.split(", ")) for clss in classes] + idx_to_wnid = {idx: wnid for idx, wnid in zip(idcs, wnids)} + wnid_to_classes = {wnid: clss for wnid, clss in zip(wnids, classes)} + return idx_to_wnid, wnid_to_classes + + def parse_val_groundtruth_txt(devkit_root: str) -> list[int]: + file = os.path.join(devkit_root, "data", "ILSVRC2012_validation_ground_truth.txt") + with open(file) as txtfh: + val_idcs = txtfh.readlines() + return [int(val_idx) for val_idx in val_idcs] + + @contextmanager + def get_tmp_dir() -> Iterator[str]: + tmp_dir = tempfile.mkdtemp() + try: + yield tmp_dir + finally: + shutil.rmtree(tmp_dir) + + archive_meta = ARCHIVE_META["devkit"] + if file is None: + file = archive_meta[0] + md5 = archive_meta[1] + + _verify_archive(root, file, md5) + + with get_tmp_dir() as tmp_dir: + extract_archive(os.path.join(root, file), tmp_dir) + + devkit_root = os.path.join(tmp_dir, "ILSVRC2012_devkit_t12") + idx_to_wnid, wnid_to_classes = parse_meta_mat(devkit_root) + val_idcs = parse_val_groundtruth_txt(devkit_root) + val_wnids = [idx_to_wnid[idx] for idx in val_idcs] + + torch.save((wnid_to_classes, val_wnids), os.path.join(root, META_FILE)) + + +def parse_train_archive(root: Union[str, Path], file: Optional[str] = None, folder: str = "train") -> None: + """Parse the train images archive of the ImageNet2012 classification dataset and + prepare it for usage with the ImageNet dataset. + + Args: + root (str or ``pathlib.Path``): Root directory containing the train images archive + file (str, optional): Name of train images archive. Defaults to + 'ILSVRC2012_img_train.tar' + folder (str, optional): Optional name for train images folder. Defaults to + 'train' + """ + archive_meta = ARCHIVE_META["train"] + if file is None: + file = archive_meta[0] + md5 = archive_meta[1] + + _verify_archive(root, file, md5) + + train_root = os.path.join(root, folder) + extract_archive(os.path.join(root, file), train_root) + + archives = [os.path.join(train_root, archive) for archive in os.listdir(train_root)] + for archive in archives: + extract_archive(archive, os.path.splitext(archive)[0], remove_finished=True) + + +def parse_val_archive( + root: Union[str, Path], file: Optional[str] = None, wnids: Optional[list[str]] = None, folder: str = "val" +) -> None: + """Parse the validation images archive of the ImageNet2012 classification dataset + and prepare it for usage with the ImageNet dataset. + + Args: + root (str or ``pathlib.Path``): Root directory containing the validation images archive + file (str, optional): Name of validation images archive. Defaults to + 'ILSVRC2012_img_val.tar' + wnids (list, optional): List of WordNet IDs of the validation images. If None + is given, the IDs are loaded from the meta file in the root directory + folder (str, optional): Optional name for validation images folder. Defaults to + 'val' + """ + archive_meta = ARCHIVE_META["val"] + if file is None: + file = archive_meta[0] + md5 = archive_meta[1] + if wnids is None: + wnids = load_meta_file(root)[1] + + _verify_archive(root, file, md5) + + val_root = os.path.join(root, folder) + extract_archive(os.path.join(root, file), val_root) + + images = sorted(os.path.join(val_root, image) for image in os.listdir(val_root)) + + for wnid in set(wnids): + os.mkdir(os.path.join(val_root, wnid)) + + for wnid, img_file in zip(wnids, images): + shutil.move(img_file, os.path.join(val_root, wnid, os.path.basename(img_file))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/imagenette.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/imagenette.py new file mode 100644 index 0000000000000000000000000000000000000000..16bac9bfadcb99ebf16736cfa89bebc1dcc32e46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/imagenette.py @@ -0,0 +1,104 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, find_classes, make_dataset +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Imagenette(VisionDataset): + """`Imagenette `_ image classification dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the Imagenette dataset. + split (string, optional): The dataset split. Supports ``"train"`` (default), and ``"val"``. + size (string, optional): The image size. Supports ``"full"`` (default), ``"320px"``, and ``"160px"``. + download (bool, optional): If ``True``, downloads the dataset components and places them in ``root``. Already + downloaded archives are not downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + + Attributes: + classes (list): List of the class name tuples. + class_to_idx (dict): Dict with items (class name, class index). + wnids (list): List of the WordNet IDs. + wnid_to_idx (dict): Dict with items (WordNet ID, class index). + """ + + _ARCHIVES = { + "full": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2.tgz", "fe2fc210e6bb7c5664d602c3cd71e612"), + "320px": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-320.tgz", "3df6f0d01a2c9592104656642f5e78a3"), + "160px": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-160.tgz", "e793b78cc4c9e9a4ccc0c1155377a412"), + } + _WNID_TO_CLASS = { + "n01440764": ("tench", "Tinca tinca"), + "n02102040": ("English springer", "English springer spaniel"), + "n02979186": ("cassette player",), + "n03000684": ("chain saw", "chainsaw"), + "n03028079": ("church", "church building"), + "n03394916": ("French horn", "horn"), + "n03417042": ("garbage truck", "dustcart"), + "n03425413": ("gas pump", "gasoline pump", "petrol pump", "island dispenser"), + "n03445777": ("golf ball",), + "n03888257": ("parachute", "chute"), + } + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + size: str = "full", + download=False, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + self._split = verify_str_arg(split, "split", ["train", "val"]) + self._size = verify_str_arg(size, "size", ["full", "320px", "160px"]) + + self._url, self._md5 = self._ARCHIVES[self._size] + self._size_root = Path(self.root) / Path(self._url).stem + self._image_root = str(self._size_root / self._split) + + if download: + self._download() + elif not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it.") + + self.wnids, self.wnid_to_idx = find_classes(self._image_root) + self.classes = [self._WNID_TO_CLASS[wnid] for wnid in self.wnids] + self.class_to_idx = { + class_name: idx for wnid, idx in self.wnid_to_idx.items() for class_name in self._WNID_TO_CLASS[wnid] + } + self._samples = make_dataset(self._image_root, self.wnid_to_idx, extensions=".jpeg") + self.loader = loader + + def _check_exists(self) -> bool: + return self._size_root.exists() + + def _download(self): + if self._check_exists(): + return + + download_and_extract_archive(self._url, self.root, md5=self._md5) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + path, label = self._samples[idx] + image = self.loader(path) + + if self.transform is not None: + image = self.transform(image) + + if self.target_transform is not None: + label = self.target_transform(label) + + return image, label + + def __len__(self) -> int: + return len(self._samples) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/inaturalist.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/inaturalist.py new file mode 100644 index 0000000000000000000000000000000000000000..a47483e158d04830b607d2f2cca42650f5b077e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/inaturalist.py @@ -0,0 +1,245 @@ +import os +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + +CATEGORIES_2021 = ["kingdom", "phylum", "class", "order", "family", "genus"] + +DATASET_URLS = { + "2017": "https://ml-inat-competition-datasets.s3.amazonaws.com/2017/train_val_images.tar.gz", + "2018": "https://ml-inat-competition-datasets.s3.amazonaws.com/2018/train_val2018.tar.gz", + "2019": "https://ml-inat-competition-datasets.s3.amazonaws.com/2019/train_val2019.tar.gz", + "2021_train": "https://ml-inat-competition-datasets.s3.amazonaws.com/2021/train.tar.gz", + "2021_train_mini": "https://ml-inat-competition-datasets.s3.amazonaws.com/2021/train_mini.tar.gz", + "2021_valid": "https://ml-inat-competition-datasets.s3.amazonaws.com/2021/val.tar.gz", +} + +DATASET_MD5 = { + "2017": "7c784ea5e424efaec655bd392f87301f", + "2018": "b1c6952ce38f31868cc50ea72d066cc3", + "2019": "c60a6e2962c9b8ccbd458d12c8582644", + "2021_train": "e0526d53c7f7b2e3167b2b43bb2690ed", + "2021_train_mini": "db6ed8330e634445efc8fec83ae81442", + "2021_valid": "f6f6e0e242e3d4c9569ba56400938afc", +} + + +class INaturalist(VisionDataset): + """`iNaturalist `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where the image files are stored. + This class does not require/use annotation files. + version (string, optional): Which version of the dataset to download/use. One of + '2017', '2018', '2019', '2021_train', '2021_train_mini', '2021_valid'. + Default: `2021_train`. + target_type (string or list, optional): Type of target to use, for 2021 versions, one of: + + - ``full``: the full category (species) + - ``kingdom``: e.g. "Animalia" + - ``phylum``: e.g. "Arthropoda" + - ``class``: e.g. "Insecta" + - ``order``: e.g. "Coleoptera" + - ``family``: e.g. "Cleridae" + - ``genus``: e.g. "Trichodes" + + for 2017-2019 versions, one of: + + - ``full``: the full (numeric) category + - ``super``: the super category, e.g. "Amphibians" + + Can also be a list to output a tuple with all specified target types. + Defaults to ``full``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + version: str = "2021_train", + target_type: Union[list[str], str] = "full", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Optional[Callable[[Union[str, Path]], Any]] = None, + ) -> None: + self.version = verify_str_arg(version, "version", DATASET_URLS.keys()) + + super().__init__(os.path.join(root, version), transform=transform, target_transform=target_transform) + + os.makedirs(root, exist_ok=True) + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.all_categories: list[str] = [] + + # map: category type -> name of category -> index + self.categories_index: dict[str, dict[str, int]] = {} + + # list indexed by category id, containing mapping from category type -> index + self.categories_map: list[dict[str, int]] = [] + + if not isinstance(target_type, list): + target_type = [target_type] + if self.version[:4] == "2021": + self.target_type = [verify_str_arg(t, "target_type", ("full", *CATEGORIES_2021)) for t in target_type] + self._init_2021() + else: + self.target_type = [verify_str_arg(t, "target_type", ("full", "super")) for t in target_type] + self._init_pre2021() + + # index of all files: (full category id, filename) + self.index: list[tuple[int, str]] = [] + + for dir_index, dir_name in enumerate(self.all_categories): + files = os.listdir(os.path.join(self.root, dir_name)) + for fname in files: + self.index.append((dir_index, fname)) + + self.loader = loader + + def _init_2021(self) -> None: + """Initialize based on 2021 layout""" + + self.all_categories = sorted(os.listdir(self.root)) + + # map: category type -> name of category -> index + self.categories_index = {k: {} for k in CATEGORIES_2021} + + for dir_index, dir_name in enumerate(self.all_categories): + pieces = dir_name.split("_") + if len(pieces) != 8: + raise RuntimeError(f"Unexpected category name {dir_name}, wrong number of pieces") + if pieces[0] != f"{dir_index:05d}": + raise RuntimeError(f"Unexpected category id {pieces[0]}, expecting {dir_index:05d}") + cat_map = {} + for cat, name in zip(CATEGORIES_2021, pieces[1:7]): + if name in self.categories_index[cat]: + cat_id = self.categories_index[cat][name] + else: + cat_id = len(self.categories_index[cat]) + self.categories_index[cat][name] = cat_id + cat_map[cat] = cat_id + self.categories_map.append(cat_map) + + def _init_pre2021(self) -> None: + """Initialize based on 2017-2019 layout""" + + # map: category type -> name of category -> index + self.categories_index = {"super": {}} + + cat_index = 0 + super_categories = sorted(os.listdir(self.root)) + for sindex, scat in enumerate(super_categories): + self.categories_index["super"][scat] = sindex + subcategories = sorted(os.listdir(os.path.join(self.root, scat))) + for subcat in subcategories: + if self.version == "2017": + # this version does not use ids as directory names + subcat_i = cat_index + cat_index += 1 + else: + try: + subcat_i = int(subcat) + except ValueError: + raise RuntimeError(f"Unexpected non-numeric dir name: {subcat}") + if subcat_i >= len(self.categories_map): + old_len = len(self.categories_map) + self.categories_map.extend([{}] * (subcat_i - old_len + 1)) + self.all_categories.extend([""] * (subcat_i - old_len + 1)) + if self.categories_map[subcat_i]: + raise RuntimeError(f"Duplicate category {subcat}") + self.categories_map[subcat_i] = {"super": sindex} + self.all_categories[subcat_i] = os.path.join(scat, subcat) + + # validate the dictionary + for cindex, c in enumerate(self.categories_map): + if not c: + raise RuntimeError(f"Missing category {cindex}") + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where the type of target specified by target_type. + """ + + cat_id, fname = self.index[index] + image_path = os.path.join(self.root, self.all_categories[cat_id], fname) + img = self.loader(image_path) if self.loader is not None else Image.open(image_path) + + target: Any = [] + for t in self.target_type: + if t == "full": + target.append(cat_id) + else: + target.append(self.categories_map[cat_id][t]) + target = tuple(target) if len(target) > 1 else target[0] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.index) + + def category_name(self, category_type: str, category_id: int) -> str: + """ + Args: + category_type(str): one of "full", "kingdom", "phylum", "class", "order", "family", "genus" or "super" + category_id(int): an index (class id) from this category + + Returns: + the name of the category + """ + if category_type == "full": + return self.all_categories[category_id] + else: + if category_type not in self.categories_index: + raise ValueError(f"Invalid category type '{category_type}'") + else: + for name, id in self.categories_index[category_type].items(): + if id == category_id: + return name + raise ValueError(f"Invalid category id {category_id} for {category_type}") + + def _check_exists(self) -> bool: + return os.path.exists(self.root) and len(os.listdir(self.root)) > 0 + + def download(self) -> None: + if self._check_exists(): + return + + base_root = os.path.dirname(self.root) + + download_and_extract_archive( + DATASET_URLS[self.version], base_root, filename=f"{self.version}.tgz", md5=DATASET_MD5[self.version] + ) + + orig_dir_name = os.path.join(base_root, os.path.basename(DATASET_URLS[self.version]).rstrip(".tar.gz")) + if not os.path.exists(orig_dir_name): + raise RuntimeError(f"Unable to find downloaded files at {orig_dir_name}") + os.rename(orig_dir_name, self.root) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/kinetics.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/kinetics.py new file mode 100644 index 0000000000000000000000000000000000000000..c568e46a62d5d8f92c0bfcdb7ce79b6b60f234ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/kinetics.py @@ -0,0 +1,237 @@ +import csv +import os +import urllib +from functools import partial +from multiprocessing import Pool +from os import path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from torch import Tensor + +from .folder import find_classes, make_dataset +from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg +from .video_utils import VideoClips +from .vision import VisionDataset + + +def _dl_wrap(tarpath: Union[str, Path], videopath: Union[str, Path], line: str) -> None: + download_and_extract_archive(line, tarpath, videopath) + + +class Kinetics(VisionDataset): + """`Generic Kinetics `_ + dataset. + + Kinetics-400/600/700 are action recognition video datasets. + This dataset consider every video as a collection of video clips of fixed size, specified + by ``frames_per_clip``, where the step in frames between each clip is given by + ``step_between_clips``. + + To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5`` + and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two + elements will come from video 1, and the next three elements from video 2. + Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all + frames in a video might be present. + + Args: + root (str or ``pathlib.Path``): Root directory of the Kinetics Dataset. + Directory should be structured as follows: + .. code:: + + root/ + ├── split + │ ├── class1 + │ │ ├── vid1.mp4 + │ │ ├── vid2.mp4 + │ │ ├── vid3.mp4 + │ │ ├── ... + │ ├── class2 + │ │ ├── vidx.mp4 + │ │ └── ... + + Note: split is appended automatically using the split argument. + frames_per_clip (int): number of frames in a clip + num_classes (int): select between Kinetics-400 (default), Kinetics-600, and Kinetics-700 + split (str): split of the dataset to consider; supports ``"train"`` (default) ``"val"`` ``"test"`` + frame_rate (float): If omitted, interpolate different frame rate for each clip. + step_between_clips (int): number of frames between each clip + transform (callable, optional): A function/transform that takes in a TxHxWxC video + and returns a transformed version. + download (bool): Download the official version of the dataset to root folder. + num_workers (int): Use multiple workers for VideoClips creation + num_download_workers (int): Use multiprocessing in order to speed up download. + output_format (str, optional): The format of the output video tensors (before transforms). + Can be either "THWC" or "TCHW" (default). + Note that in most other utils and datasets, the default is actually "THWC". + + Returns: + tuple: A 3-tuple with the following entries: + + - video (Tensor[T, C, H, W] or Tensor[T, H, W, C]): the `T` video frames in torch.uint8 tensor + - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels + and `L` is the number of points in torch.float tensor + - label (int): class of the video clip + + Raises: + RuntimeError: If ``download is True`` and the video archives are already extracted. + """ + + _TAR_URLS = { + "400": "https://s3.amazonaws.com/kinetics/400/{split}/k400_{split}_path.txt", + "600": "https://s3.amazonaws.com/kinetics/600/{split}/k600_{split}_path.txt", + "700": "https://s3.amazonaws.com/kinetics/700_2020/{split}/k700_2020_{split}_path.txt", + } + _ANNOTATION_URLS = { + "400": "https://s3.amazonaws.com/kinetics/400/annotations/{split}.csv", + "600": "https://s3.amazonaws.com/kinetics/600/annotations/{split}.csv", + "700": "https://s3.amazonaws.com/kinetics/700_2020/annotations/{split}.csv", + } + + def __init__( + self, + root: Union[str, Path], + frames_per_clip: int, + num_classes: str = "400", + split: str = "train", + frame_rate: Optional[int] = None, + step_between_clips: int = 1, + transform: Optional[Callable] = None, + extensions: tuple[str, ...] = ("avi", "mp4"), + download: bool = False, + num_download_workers: int = 1, + num_workers: int = 1, + _precomputed_metadata: Optional[dict[str, Any]] = None, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _audio_samples: int = 0, + _audio_channels: int = 0, + _legacy: bool = False, + output_format: str = "TCHW", + ) -> None: + + # TODO: support test + self.num_classes = verify_str_arg(num_classes, arg="num_classes", valid_values=["400", "600", "700"]) + self.extensions = extensions + self.num_download_workers = num_download_workers + + self.root = root + self._legacy = _legacy + + if _legacy: + self.split_folder = root + self.split = "unknown" + output_format = "THWC" + if download: + raise ValueError("Cannot download the videos using legacy_structure.") + else: + self.split_folder = path.join(root, split) + self.split = verify_str_arg(split, arg="split", valid_values=["train", "val", "test"]) + + if download: + self.download_and_process_videos() + + super().__init__(self.root) + + self.classes, class_to_idx = find_classes(self.split_folder) + self.samples = make_dataset(self.split_folder, class_to_idx, extensions, is_valid_file=None) + video_list = [x[0] for x in self.samples] + self.video_clips = VideoClips( + video_list, + frames_per_clip, + step_between_clips, + frame_rate, + _precomputed_metadata, + num_workers=num_workers, + _video_width=_video_width, + _video_height=_video_height, + _video_min_dimension=_video_min_dimension, + _audio_samples=_audio_samples, + _audio_channels=_audio_channels, + output_format=output_format, + ) + self.transform = transform + + def download_and_process_videos(self) -> None: + """Downloads all the videos to the _root_ folder in the expected format.""" + self._download_videos() + self._make_ds_structure() + + def _download_videos(self) -> None: + """download tarballs containing the video to "tars" folder and extract them into the _split_ folder where + split is one of the official dataset splits. + + Raises: + RuntimeError: if download folder exists, break to prevent downloading entire dataset again. + """ + if path.exists(self.split_folder): + return + tar_path = path.join(self.root, "tars") + file_list_path = path.join(self.root, "files") + + split_url = self._TAR_URLS[self.num_classes].format(split=self.split) + split_url_filepath = path.join(file_list_path, path.basename(split_url)) + if not check_integrity(split_url_filepath): + download_url(split_url, file_list_path) + with open(split_url_filepath) as file: + list_video_urls = [urllib.parse.quote(line, safe="/,:") for line in file.read().splitlines()] + + if self.num_download_workers == 1: + for line in list_video_urls: + download_and_extract_archive(line, tar_path, self.split_folder) + else: + part = partial(_dl_wrap, tar_path, self.split_folder) + poolproc = Pool(self.num_download_workers) + poolproc.map(part, list_video_urls) + + def _make_ds_structure(self) -> None: + """move videos from + split_folder/ + ├── clip1.avi + ├── clip2.avi + + to the correct format as described below: + split_folder/ + ├── class1 + │ ├── clip1.avi + + """ + annotation_path = path.join(self.root, "annotations") + if not check_integrity(path.join(annotation_path, f"{self.split}.csv")): + download_url(self._ANNOTATION_URLS[self.num_classes].format(split=self.split), annotation_path) + annotations = path.join(annotation_path, f"{self.split}.csv") + + file_fmtstr = "{ytid}_{start:06}_{end:06}.mp4" + with open(annotations) as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + f = file_fmtstr.format( + ytid=row["youtube_id"], + start=int(row["time_start"]), + end=int(row["time_end"]), + ) + label = row["label"].replace(" ", "_").replace("'", "").replace("(", "").replace(")", "") + os.makedirs(path.join(self.split_folder, label), exist_ok=True) + downloaded_file = path.join(self.split_folder, f) + if path.isfile(downloaded_file): + os.replace( + downloaded_file, + path.join(self.split_folder, label, f), + ) + + @property + def metadata(self) -> dict[str, Any]: + return self.video_clips.metadata + + def __len__(self) -> int: + return self.video_clips.num_clips() + + def __getitem__(self, idx: int) -> tuple[Tensor, Tensor, int]: + video, audio, info, video_idx = self.video_clips.get_clip(idx) + label = self.samples[video_idx][1] + + if self.transform is not None: + video = self.transform(video) + + return video, audio, label diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/kitti.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/kitti.py new file mode 100644 index 0000000000000000000000000000000000000000..d275248d92a5cad4efe8dfaf7ec89c6dda6dd8ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/kitti.py @@ -0,0 +1,158 @@ +import csv +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive +from .vision import VisionDataset + + +class Kitti(VisionDataset): + """`KITTI `_ Dataset. + + It corresponds to the "left color images of object" dataset, for object detection. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + Expects the following folder structure if download=False: + + .. code:: + + + └── Kitti + └─ raw + ├── training + | ├── image_2 + | └── label_2 + └── testing + └── image_2 + train (bool, optional): Use ``train`` split if true, else ``test`` split. + Defaults to ``train``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample + and its target as entry and returns a transformed version. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + data_url = "https://s3.eu-central-1.amazonaws.com/avg-kitti/" + resources = [ + "data_object_image_2.zip", + "data_object_label_2.zip", + ] + image_dir_name = "image_2" + labels_dir_name = "label_2" + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + download: bool = False, + ): + super().__init__( + root, + transform=transform, + target_transform=target_transform, + transforms=transforms, + ) + self.images = [] + self.targets = [] + self.train = train + self._location = "training" if self.train else "testing" + + if download: + self.download() + if not self._check_exists(): + raise RuntimeError("Dataset not found. You may use download=True to download it.") + + image_dir = os.path.join(self._raw_folder, self._location, self.image_dir_name) + if self.train: + labels_dir = os.path.join(self._raw_folder, self._location, self.labels_dir_name) + for img_file in os.listdir(image_dir): + self.images.append(os.path.join(image_dir, img_file)) + if self.train: + self.targets.append(os.path.join(labels_dir, f"{img_file.split('.')[0]}.txt")) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """Get item at a given index. + + Args: + index (int): Index + Returns: + tuple: (image, target), where + target is a list of dictionaries with the following keys: + + - type: str + - truncated: float + - occluded: int + - alpha: float + - bbox: float[4] + - dimensions: float[3] + - locations: float[3] + - rotation_y: float + + """ + image = Image.open(self.images[index]) + target = self._parse_target(index) if self.train else None + if self.transforms: + image, target = self.transforms(image, target) + return image, target + + def _parse_target(self, index: int) -> list: + target = [] + with open(self.targets[index]) as inp: + content = csv.reader(inp, delimiter=" ") + for line in content: + target.append( + { + "type": line[0], + "truncated": float(line[1]), + "occluded": int(line[2]), + "alpha": float(line[3]), + "bbox": [float(x) for x in line[4:8]], + "dimensions": [float(x) for x in line[8:11]], + "location": [float(x) for x in line[11:14]], + "rotation_y": float(line[14]), + } + ) + return target + + def __len__(self) -> int: + return len(self.images) + + @property + def _raw_folder(self) -> str: + return os.path.join(self.root, self.__class__.__name__, "raw") + + def _check_exists(self) -> bool: + """Check if the data directory exists.""" + folders = [self.image_dir_name] + if self.train: + folders.append(self.labels_dir_name) + return all(os.path.isdir(os.path.join(self._raw_folder, self._location, fname)) for fname in folders) + + def download(self) -> None: + """Download the KITTI data if it doesn't exist already.""" + + if self._check_exists(): + return + + os.makedirs(self._raw_folder, exist_ok=True) + + # download files + for fname in self.resources: + download_and_extract_archive( + url=f"{self.data_url}{fname}", + download_root=self._raw_folder, + filename=fname, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/lfw.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/lfw.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff17af5328cbc0995432560c86288f405cd5a46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/lfw.py @@ -0,0 +1,268 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader +from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg +from .vision import VisionDataset + + +class _LFW(VisionDataset): + + base_folder = "lfw-py" + download_url_prefix = "http://vis-www.cs.umass.edu/lfw/" + + file_dict = { + "original": ("lfw", "lfw.tgz", "a17d05bd522c52d84eca14327a23d494"), + "funneled": ("lfw_funneled", "lfw-funneled.tgz", "1b42dfed7d15c9b2dd63d5e5840c86ad"), + "deepfunneled": ("lfw-deepfunneled", "lfw-deepfunneled.tgz", "68331da3eb755a505a502b5aacb3c201"), + } + checksums = { + "pairs.txt": "9f1ba174e4e1c508ff7cdf10ac338a7d", + "pairsDevTest.txt": "5132f7440eb68cf58910c8a45a2ac10b", + "pairsDevTrain.txt": "4f27cbf15b2da4a85c1907eb4181ad21", + "people.txt": "450f0863dd89e85e73936a6d71a3474b", + "peopleDevTest.txt": "e4bf5be0a43b5dcd9dc5ccfcb8fb19c5", + "peopleDevTrain.txt": "54eaac34beb6d042ed3a7d883e247a21", + "lfw-names.txt": "a6d0a479bd074669f656265a6e693f6d", + } + annot_file = {"10fold": "", "train": "DevTrain", "test": "DevTest"} + names = "lfw-names.txt" + + def __init__( + self, + root: Union[str, Path], + split: str, + image_set: str, + view: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(os.path.join(root, self.base_folder), transform=transform, target_transform=target_transform) + + self.image_set = verify_str_arg(image_set.lower(), "image_set", self.file_dict.keys()) + images_dir, self.filename, self.md5 = self.file_dict[self.image_set] + + self.view = verify_str_arg(view.lower(), "view", ["people", "pairs"]) + self.split = verify_str_arg(split.lower(), "split", ["10fold", "train", "test"]) + self.labels_file = f"{self.view}{self.annot_file[self.split]}.txt" + self.data: list[Any] = [] + + if download: + raise ValueError( + "LFW dataset is no longer available for download." + "Please download the dataset manually and place it in the specified directory" + ) + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.images_dir = os.path.join(self.root, images_dir) + self._loader = loader + + def _check_integrity(self) -> bool: + st1 = check_integrity(os.path.join(self.root, self.filename), self.md5) + st2 = check_integrity(os.path.join(self.root, self.labels_file), self.checksums[self.labels_file]) + if not st1 or not st2: + return False + if self.view == "people": + return check_integrity(os.path.join(self.root, self.names), self.checksums[self.names]) + return True + + def download(self) -> None: + if self._check_integrity(): + return + url = f"{self.download_url_prefix}{self.filename}" + download_and_extract_archive(url, self.root, filename=self.filename, md5=self.md5) + download_url(f"{self.download_url_prefix}{self.labels_file}", self.root) + if self.view == "people": + download_url(f"{self.download_url_prefix}{self.names}", self.root) + + def _get_path(self, identity: str, no: Union[int, str]) -> str: + return os.path.join(self.images_dir, identity, f"{identity}_{int(no):04d}.jpg") + + def extra_repr(self) -> str: + return f"Alignment: {self.image_set}\nSplit: {self.split}" + + def __len__(self) -> int: + return len(self.data) + + +class LFWPeople(_LFW): + """`LFW `_ Dataset. + + .. warning: + + The LFW dataset is no longer available for automatic download. Please + download it manually and place it in the specified directory. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``lfw-py`` exists or will be saved to if download is set to True. + split (string, optional): The image split to use. Can be one of ``train``, ``test``, + ``10fold`` (default). + image_set (str, optional): Type of image funneling to use, ``original``, ``funneled`` or + ``deepfunneled``. Defaults to ``funneled``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): NOT SUPPORTED ANYMORE, leave to False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: str, + split: str = "10fold", + image_set: str = "funneled", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, split, image_set, "people", transform, target_transform, download, loader=loader) + + self.class_to_idx = self._get_classes() + self.data, self.targets = self._get_people() + + def _get_people(self) -> tuple[list[str], list[int]]: + data, targets = [], [] + with open(os.path.join(self.root, self.labels_file)) as f: + lines = f.readlines() + n_folds, s = (int(lines[0]), 1) if self.split == "10fold" else (1, 0) + + for fold in range(n_folds): + n_lines = int(lines[s]) + people = [line.strip().split("\t") for line in lines[s + 1 : s + n_lines + 1]] + s += n_lines + 1 + for i, (identity, num_imgs) in enumerate(people): + for num in range(1, int(num_imgs) + 1): + img = self._get_path(identity, num) + data.append(img) + targets.append(self.class_to_idx[identity]) + + return data, targets + + def _get_classes(self) -> dict[str, int]: + with open(os.path.join(self.root, self.names)) as f: + lines = f.readlines() + names = [line.strip().split()[0] for line in lines] + class_to_idx = {name: i for i, name in enumerate(names)} + return class_to_idx + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target) where target is the identity of the person. + """ + img = self._loader(self.data[index]) + target = self.targets[index] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def extra_repr(self) -> str: + return super().extra_repr() + f"\nClasses (identities): {len(self.class_to_idx)}" + + +class LFWPairs(_LFW): + """`LFW `_ Dataset. + + .. warning: + + The LFW dataset is no longer available for automatic download. Please + download it manually and place it in the specified directory. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``lfw-py`` exists or will be saved to if download is set to True. + split (string, optional): The image split to use. Can be one of ``train``, ``test``, + ``10fold``. Defaults to ``10fold``. + image_set (str, optional): Type of image funneling to use, ``original``, ``funneled`` or + ``deepfunneled``. Defaults to ``funneled``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomRotation`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): NOT SUPPORTED ANYMORE, leave to False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + + """ + + def __init__( + self, + root: str, + split: str = "10fold", + image_set: str = "funneled", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, split, image_set, "pairs", transform, target_transform, download, loader=loader) + + self.pair_names, self.data, self.targets = self._get_pairs(self.images_dir) + + def _get_pairs(self, images_dir: str) -> tuple[list[tuple[str, str]], list[tuple[str, str]], list[int]]: + pair_names, data, targets = [], [], [] + with open(os.path.join(self.root, self.labels_file)) as f: + lines = f.readlines() + if self.split == "10fold": + n_folds, n_pairs = lines[0].split("\t") + n_folds, n_pairs = int(n_folds), int(n_pairs) + else: + n_folds, n_pairs = 1, int(lines[0]) + s = 1 + + for fold in range(n_folds): + matched_pairs = [line.strip().split("\t") for line in lines[s : s + n_pairs]] + unmatched_pairs = [line.strip().split("\t") for line in lines[s + n_pairs : s + (2 * n_pairs)]] + s += 2 * n_pairs + for pair in matched_pairs: + img1, img2, same = self._get_path(pair[0], pair[1]), self._get_path(pair[0], pair[2]), 1 + pair_names.append((pair[0], pair[0])) + data.append((img1, img2)) + targets.append(same) + for pair in unmatched_pairs: + img1, img2, same = self._get_path(pair[0], pair[1]), self._get_path(pair[2], pair[3]), 0 + pair_names.append((pair[0], pair[2])) + data.append((img1, img2)) + targets.append(same) + + return pair_names, data, targets + + def __getitem__(self, index: int) -> tuple[Any, Any, int]: + """ + Args: + index (int): Index + + Returns: + tuple: (image1, image2, target) where target is `0` for different indentities and `1` for same identities. + """ + img1, img2 = self.data[index] + img1, img2 = self._loader(img1), self._loader(img2) + target = self.targets[index] + + if self.transform is not None: + img1, img2 = self.transform(img1), self.transform(img2) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img1, img2, target diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/lsun.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/lsun.py new file mode 100644 index 0000000000000000000000000000000000000000..6f6c7a5eb63c21e042b4be0e059fa5df581acbaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/lsun.py @@ -0,0 +1,168 @@ +import io +import os.path +import pickle +import string +from collections.abc import Iterable +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union + +from PIL import Image + +from .utils import iterable_to_str, verify_str_arg +from .vision import VisionDataset + + +class LSUNClass(VisionDataset): + def __init__( + self, root: str, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None + ) -> None: + import lmdb + + super().__init__(root, transform=transform, target_transform=target_transform) + + self.env = lmdb.open(root, max_readers=1, readonly=True, lock=False, readahead=False, meminit=False) + with self.env.begin(write=False) as txn: + self.length = txn.stat()["entries"] + cache_file = "_cache_" + "".join(c for c in root if c in string.ascii_letters) + if os.path.isfile(cache_file): + self.keys = pickle.load(open(cache_file, "rb")) + else: + with self.env.begin(write=False) as txn: + self.keys = [key for key in txn.cursor().iternext(keys=True, values=False)] + pickle.dump(self.keys, open(cache_file, "wb")) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + img, target = None, None + env = self.env + with env.begin(write=False) as txn: + imgbuf = txn.get(self.keys[index]) + + buf = io.BytesIO() + buf.write(imgbuf) + buf.seek(0) + img = Image.open(buf).convert("RGB") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return self.length + + +class LSUN(VisionDataset): + """`LSUN `_ dataset. + + You will need to install the ``lmdb`` package to use this dataset: run + ``pip install lmdb`` + + Args: + root (str or ``pathlib.Path``): Root directory for the database files. + classes (string or list): One of {'train', 'val', 'test'} or a list of + categories to load. e,g. ['bedroom_train', 'church_outdoor_train']. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + """ + + def __init__( + self, + root: Union[str, Path], + classes: Union[str, list[str]] = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.classes = self._verify_classes(classes) + + # for each class, create an LSUNClassDataset + self.dbs = [] + for c in self.classes: + self.dbs.append(LSUNClass(root=os.path.join(root, f"{c}_lmdb"), transform=transform)) + + self.indices = [] + count = 0 + for db in self.dbs: + count += len(db) + self.indices.append(count) + + self.length = count + + def _verify_classes(self, classes: Union[str, list[str]]) -> list[str]: + categories = [ + "bedroom", + "bridge", + "church_outdoor", + "classroom", + "conference_room", + "dining_room", + "kitchen", + "living_room", + "restaurant", + "tower", + ] + dset_opts = ["train", "val", "test"] + + try: + classes = cast(str, classes) + verify_str_arg(classes, "classes", dset_opts) + if classes == "test": + classes = [classes] + else: + classes = [c + "_" + classes for c in categories] + except ValueError: + if not isinstance(classes, Iterable): + msg = "Expected type str or Iterable for argument classes, but got type {}." + raise ValueError(msg.format(type(classes))) + + classes = list(classes) + msg_fmtstr_type = "Expected type str for elements in argument classes, but got type {}." + for c in classes: + verify_str_arg(c, custom_msg=msg_fmtstr_type.format(type(c))) + c_short = c.split("_") + category, dset_opt = "_".join(c_short[:-1]), c_short[-1] + + msg_fmtstr = "Unknown value '{}' for {}. Valid values are {{{}}}." + msg = msg_fmtstr.format(category, "LSUN class", iterable_to_str(categories)) + verify_str_arg(category, valid_values=categories, custom_msg=msg) + + msg = msg_fmtstr.format(dset_opt, "postfix", iterable_to_str(dset_opts)) + verify_str_arg(dset_opt, valid_values=dset_opts, custom_msg=msg) + + return classes + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target) where target is the index of the target category. + """ + target = 0 + sub = 0 + for ind in self.indices: + if index < ind: + break + target += 1 + sub = ind + + db = self.dbs[target] + index = index - sub + + if self.target_transform is not None: + target = self.target_transform(target) + + img, _ = db[index] + return img, target + + def __len__(self) -> int: + return self.length + + def extra_repr(self) -> str: + return "Classes: {classes}".format(**self.__dict__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/mnist.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..06a658cbea476aaa5a286b8902649944889998d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/mnist.py @@ -0,0 +1,560 @@ +import codecs +import os +import os.path +import shutil +import string +import sys +import warnings +from pathlib import Path +from typing import Any, Callable, Optional, Union +from urllib.error import URLError + +import numpy as np +import torch + +from ..utils import _Image_fromarray +from .utils import _flip_byte_order, check_integrity, download_and_extract_archive, extract_archive, verify_str_arg +from .vision import VisionDataset + + +class MNIST(VisionDataset): + """`MNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``MNIST/raw/train-images-idx3-ubyte`` + and ``MNIST/raw/t10k-images-idx3-ubyte`` exist. + train (bool, optional): If True, creates dataset from ``train-images-idx3-ubyte``, + otherwise from ``t10k-images-idx3-ubyte``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + mirrors = [ + "https://ossci-datasets.s3.amazonaws.com/mnist/", + "http://yann.lecun.com/exdb/mnist/", + ] + + resources = [ + ("train-images-idx3-ubyte.gz", "f68b3c2dcbeaaa9fbdd348bbdeb94873"), + ("train-labels-idx1-ubyte.gz", "d53e105ee54ea40749a09fcbcd1e9432"), + ("t10k-images-idx3-ubyte.gz", "9fb629c4189551a2d022fa330f9573f3"), + ("t10k-labels-idx1-ubyte.gz", "ec29112dd5afa0611ce80d1b7f02629c"), + ] + + training_file = "training.pt" + test_file = "test.pt" + classes = [ + "0 - zero", + "1 - one", + "2 - two", + "3 - three", + "4 - four", + "5 - five", + "6 - six", + "7 - seven", + "8 - eight", + "9 - nine", + ] + + @property + def train_labels(self): + warnings.warn("train_labels has been renamed targets") + return self.targets + + @property + def test_labels(self): + warnings.warn("test_labels has been renamed targets") + return self.targets + + @property + def train_data(self): + warnings.warn("train_data has been renamed data") + return self.data + + @property + def test_data(self): + warnings.warn("test_data has been renamed data") + return self.data + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.train = train # training set or test set + + if self._check_legacy_exist(): + self.data, self.targets = self._load_legacy_data() + return + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self.data, self.targets = self._load_data() + + def _check_legacy_exist(self): + processed_folder_exists = os.path.exists(self.processed_folder) + if not processed_folder_exists: + return False + + return all( + check_integrity(os.path.join(self.processed_folder, file)) for file in (self.training_file, self.test_file) + ) + + def _load_legacy_data(self): + # This is for BC only. We no longer cache the data in a custom binary, but simply read from the raw data + # directly. + data_file = self.training_file if self.train else self.test_file + return torch.load(os.path.join(self.processed_folder, data_file), weights_only=True) + + def _load_data(self): + image_file = f"{'train' if self.train else 't10k'}-images-idx3-ubyte" + data = read_image_file(os.path.join(self.raw_folder, image_file)) + + label_file = f"{'train' if self.train else 't10k'}-labels-idx1-ubyte" + targets = read_label_file(os.path.join(self.raw_folder, label_file)) + + return data, targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.targets[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = _Image_fromarray(img.numpy(), mode="L") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + @property + def raw_folder(self) -> str: + return os.path.join(self.root, self.__class__.__name__, "raw") + + @property + def processed_folder(self) -> str: + return os.path.join(self.root, self.__class__.__name__, "processed") + + @property + def class_to_idx(self) -> dict[str, int]: + return {_class: i for i, _class in enumerate(self.classes)} + + def _check_exists(self) -> bool: + return all( + check_integrity(os.path.join(self.raw_folder, os.path.splitext(os.path.basename(url))[0])) + for url, _ in self.resources + ) + + def download(self) -> None: + """Download the MNIST data if it doesn't exist already.""" + + if self._check_exists(): + return + + os.makedirs(self.raw_folder, exist_ok=True) + + # download files + for filename, md5 in self.resources: + errors = [] + for mirror in self.mirrors: + url = f"{mirror}{filename}" + try: + download_and_extract_archive(url, download_root=self.raw_folder, filename=filename, md5=md5) + except URLError as e: + errors.append(e) + continue + break + else: + s = f"Error downloading {filename}:\n" + for mirror, err in zip(self.mirrors, errors): + s += f"Tried {mirror}, got:\n{str(err)}\n" + raise RuntimeError(s) + + def extra_repr(self) -> str: + split = "Train" if self.train is True else "Test" + return f"Split: {split}" + + +class FashionMNIST(MNIST): + """`Fashion-MNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``FashionMNIST/raw/train-images-idx3-ubyte`` + and ``FashionMNIST/raw/t10k-images-idx3-ubyte`` exist. + train (bool, optional): If True, creates dataset from ``train-images-idx3-ubyte``, + otherwise from ``t10k-images-idx3-ubyte``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + mirrors = ["http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/"] + + resources = [ + ("train-images-idx3-ubyte.gz", "8d4fb7e6c68d591d4c3dfef9ec88bf0d"), + ("train-labels-idx1-ubyte.gz", "25c81989df183df01b3e8a0aad5dffbe"), + ("t10k-images-idx3-ubyte.gz", "bef4ecab320f06d8554ea6380940ec79"), + ("t10k-labels-idx1-ubyte.gz", "bb300cfdad3c16e7a12a480ee83cd310"), + ] + classes = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"] + + +class KMNIST(MNIST): + """`Kuzushiji-MNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``KMNIST/raw/train-images-idx3-ubyte`` + and ``KMNIST/raw/t10k-images-idx3-ubyte`` exist. + train (bool, optional): If True, creates dataset from ``train-images-idx3-ubyte``, + otherwise from ``t10k-images-idx3-ubyte``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + mirrors = ["http://codh.rois.ac.jp/kmnist/dataset/kmnist/"] + + resources = [ + ("train-images-idx3-ubyte.gz", "bdb82020997e1d708af4cf47b453dcf7"), + ("train-labels-idx1-ubyte.gz", "e144d726b3acfaa3e44228e80efcd344"), + ("t10k-images-idx3-ubyte.gz", "5c965bf0a639b31b8f53240b1b52f4d7"), + ("t10k-labels-idx1-ubyte.gz", "7320c461ea6c1c855c0b718fb2a4b134"), + ] + classes = ["o", "ki", "su", "tsu", "na", "ha", "ma", "ya", "re", "wo"] + + +class EMNIST(MNIST): + """`EMNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``EMNIST/raw/train-images-idx3-ubyte`` + and ``EMNIST/raw/t10k-images-idx3-ubyte`` exist. + split (string): The dataset has 6 different splits: ``byclass``, ``bymerge``, + ``balanced``, ``letters``, ``digits`` and ``mnist``. This argument specifies + which one to use. + train (bool, optional): If True, creates dataset from ``training.pt``, + otherwise from ``test.pt``. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + """ + + url = "https://biometrics.nist.gov/cs_links/EMNIST/gzip.zip" + md5 = "58c8d27c78d21e728a6bc7b3cc06412e" + splits = ("byclass", "bymerge", "balanced", "letters", "digits", "mnist") + # Merged Classes assumes Same structure for both uppercase and lowercase version + _merged_classes = {"c", "i", "j", "k", "l", "m", "o", "p", "s", "u", "v", "w", "x", "y", "z"} + _all_classes = set(string.digits + string.ascii_letters) + classes_split_dict = { + "byclass": sorted(list(_all_classes)), + "bymerge": sorted(list(_all_classes - _merged_classes)), + "balanced": sorted(list(_all_classes - _merged_classes)), + "letters": ["N/A"] + list(string.ascii_lowercase), + "digits": list(string.digits), + "mnist": list(string.digits), + } + + def __init__(self, root: Union[str, Path], split: str, **kwargs: Any) -> None: + self.split = verify_str_arg(split, "split", self.splits) + self.training_file = self._training_file(split) + self.test_file = self._test_file(split) + super().__init__(root, **kwargs) + self.classes = self.classes_split_dict[self.split] + + @staticmethod + def _training_file(split) -> str: + return f"training_{split}.pt" + + @staticmethod + def _test_file(split) -> str: + return f"test_{split}.pt" + + @property + def _file_prefix(self) -> str: + return f"emnist-{self.split}-{'train' if self.train else 'test'}" + + @property + def images_file(self) -> str: + return os.path.join(self.raw_folder, f"{self._file_prefix}-images-idx3-ubyte") + + @property + def labels_file(self) -> str: + return os.path.join(self.raw_folder, f"{self._file_prefix}-labels-idx1-ubyte") + + def _load_data(self): + return read_image_file(self.images_file), read_label_file(self.labels_file) + + def _check_exists(self) -> bool: + return all(check_integrity(file) for file in (self.images_file, self.labels_file)) + + def download(self) -> None: + """Download the EMNIST data if it doesn't exist already.""" + + if self._check_exists(): + return + + os.makedirs(self.raw_folder, exist_ok=True) + + download_and_extract_archive(self.url, download_root=self.raw_folder, md5=self.md5) + gzip_folder = os.path.join(self.raw_folder, "gzip") + for gzip_file in os.listdir(gzip_folder): + if gzip_file.endswith(".gz"): + extract_archive(os.path.join(gzip_folder, gzip_file), self.raw_folder) + shutil.rmtree(gzip_folder) + + +class QMNIST(MNIST): + """`QMNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset whose ``raw`` + subdir contains binary files of the datasets. + what (string,optional): Can be 'train', 'test', 'test10k', + 'test50k', or 'nist' for respectively the mnist compatible + training set, the 60k qmnist testing set, the 10k qmnist + examples that match the mnist testing set, the 50k + remaining qmnist testing examples, or all the nist + digits. The default is to select 'train' or 'test' + according to the compatibility argument 'train'. + compat (bool,optional): A boolean that says whether the target + for each example is class number (for compatibility with + the MNIST dataloader) or a torch vector containing the + full qmnist information. Default=True. + train (bool,optional,compatibility): When argument 'what' is + not specified, this boolean decides whether to load the + training set or the testing set. Default: True. + download (bool, optional): If True, downloads the dataset from + the internet and puts it in root directory. If dataset is + already downloaded, it is not downloaded again. + transform (callable, optional): A function/transform that + takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform + that takes in the target and transforms it. + """ + + subsets = {"train": "train", "test": "test", "test10k": "test", "test50k": "test", "nist": "nist"} + resources: dict[str, list[tuple[str, str]]] = { # type: ignore[assignment] + "train": [ + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-train-images-idx3-ubyte.gz", + "ed72d4157d28c017586c42bc6afe6370", + ), + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-train-labels-idx2-int.gz", + "0058f8dd561b90ffdd0f734c6a30e5e4", + ), + ], + "test": [ + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-test-images-idx3-ubyte.gz", + "1394631089c404de565df7b7aeaf9412", + ), + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-test-labels-idx2-int.gz", + "5b5b05890a5e13444e108efe57b788aa", + ), + ], + "nist": [ + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/xnist-images-idx3-ubyte.xz", + "7f124b3b8ab81486c9d8c2749c17f834", + ), + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/xnist-labels-idx2-int.xz", + "5ed0e788978e45d4a8bd4b7caec3d79d", + ), + ], + } + classes = [ + "0 - zero", + "1 - one", + "2 - two", + "3 - three", + "4 - four", + "5 - five", + "6 - six", + "7 - seven", + "8 - eight", + "9 - nine", + ] + + def __init__( + self, root: Union[str, Path], what: Optional[str] = None, compat: bool = True, train: bool = True, **kwargs: Any + ) -> None: + if what is None: + what = "train" if train else "test" + self.what = verify_str_arg(what, "what", tuple(self.subsets.keys())) + self.compat = compat + self.data_file = what + ".pt" + self.training_file = self.data_file + self.test_file = self.data_file + super().__init__(root, train, **kwargs) + + @property + def images_file(self) -> str: + (url, _), _ = self.resources[self.subsets[self.what]] + return os.path.join(self.raw_folder, os.path.splitext(os.path.basename(url))[0]) + + @property + def labels_file(self) -> str: + _, (url, _) = self.resources[self.subsets[self.what]] + return os.path.join(self.raw_folder, os.path.splitext(os.path.basename(url))[0]) + + def _check_exists(self) -> bool: + return all(check_integrity(file) for file in (self.images_file, self.labels_file)) + + def _load_data(self): + data = read_sn3_pascalvincent_tensor(self.images_file) + if data.dtype != torch.uint8: + raise TypeError(f"data should be of dtype torch.uint8 instead of {data.dtype}") + if data.ndimension() != 3: + raise ValueError("data should have 3 dimensions instead of {data.ndimension()}") + + targets = read_sn3_pascalvincent_tensor(self.labels_file).long() + if targets.ndimension() != 2: + raise ValueError(f"targets should have 2 dimensions instead of {targets.ndimension()}") + + if self.what == "test10k": + data = data[0:10000, :, :].clone() + targets = targets[0:10000, :].clone() + elif self.what == "test50k": + data = data[10000:, :, :].clone() + targets = targets[10000:, :].clone() + + return data, targets + + def download(self) -> None: + """Download the QMNIST data if it doesn't exist already. + Note that we only download what has been asked for (argument 'what'). + """ + if self._check_exists(): + return + + os.makedirs(self.raw_folder, exist_ok=True) + split = self.resources[self.subsets[self.what]] + + for url, md5 in split: + download_and_extract_archive(url, self.raw_folder, md5=md5) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + # redefined to handle the compat flag + img, target = self.data[index], self.targets[index] + img = _Image_fromarray(img.numpy(), mode="L") + if self.transform is not None: + img = self.transform(img) + if self.compat: + target = int(target[0]) + if self.target_transform is not None: + target = self.target_transform(target) + return img, target + + def extra_repr(self) -> str: + return f"Split: {self.what}" + + +def get_int(b: bytes) -> int: + return int(codecs.encode(b, "hex"), 16) + + +SN3_PASCALVINCENT_TYPEMAP = { + 8: torch.uint8, + 9: torch.int8, + 11: torch.int16, + 12: torch.int32, + 13: torch.float32, + 14: torch.float64, +} + + +def read_sn3_pascalvincent_tensor(path: str, strict: bool = True) -> torch.Tensor: + """Read a SN3 file in "Pascal Vincent" format (Lush file 'libidx/idx-io.lsh'). + Argument may be a filename, compressed filename, or file object. + """ + # read + with open(path, "rb") as f: + data = f.read() + + # parse + if sys.byteorder == "little" or sys.platform == "aix": + magic = get_int(data[0:4]) + nd = magic % 256 + ty = magic // 256 + else: + nd = get_int(data[0:1]) + ty = get_int(data[1:2]) + get_int(data[2:3]) * 256 + get_int(data[3:4]) * 256 * 256 + + assert 1 <= nd <= 3 + assert 8 <= ty <= 14 + torch_type = SN3_PASCALVINCENT_TYPEMAP[ty] + s = [get_int(data[4 * (i + 1) : 4 * (i + 2)]) for i in range(nd)] + + if sys.byteorder == "big" and not sys.platform == "aix": + for i in range(len(s)): + s[i] = int.from_bytes(s[i].to_bytes(4, byteorder="little"), byteorder="big", signed=False) + + parsed = torch.frombuffer(bytearray(data), dtype=torch_type, offset=(4 * (nd + 1))) + + # The MNIST format uses the big endian byte order, while `torch.frombuffer` uses whatever the system uses. In case + # that is little endian and the dtype has more than one byte, we need to flip them. + if sys.byteorder == "little" and parsed.element_size() > 1: + parsed = _flip_byte_order(parsed) + + assert parsed.shape[0] == np.prod(s) or not strict + return parsed.view(*s) + + +def read_label_file(path: str) -> torch.Tensor: + x = read_sn3_pascalvincent_tensor(path, strict=False) + if x.dtype != torch.uint8: + raise TypeError(f"x should be of dtype torch.uint8 instead of {x.dtype}") + if x.ndimension() != 1: + raise ValueError(f"x should have 1 dimension instead of {x.ndimension()}") + return x.long() + + +def read_image_file(path: str) -> torch.Tensor: + x = read_sn3_pascalvincent_tensor(path, strict=False) + if x.dtype != torch.uint8: + raise TypeError(f"x should be of dtype torch.uint8 instead of {x.dtype}") + if x.ndimension() != 3: + raise ValueError(f"x should have 3 dimension instead of {x.ndimension()}") + return x diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/moving_mnist.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/moving_mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..4466d82291bfa908aff424bb66ae704289b97274 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/moving_mnist.py @@ -0,0 +1,94 @@ +import os.path +from pathlib import Path +from typing import Callable, Optional, Union + +import numpy as np +import torch +from torchvision.datasets.utils import download_url, verify_str_arg +from torchvision.datasets.vision import VisionDataset + + +class MovingMNIST(VisionDataset): + """`MovingMNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``MovingMNIST/mnist_test_seq.npy`` exists. + split (string, optional): The dataset split, supports ``None`` (default), ``"train"`` and ``"test"``. + If ``split=None``, the full data is returned. + split_ratio (int, optional): The split ratio of number of frames. If ``split="train"``, the first split + frames ``data[:, :split_ratio]`` is returned. If ``split="test"``, the last split frames ``data[:, split_ratio:]`` + is returned. If ``split=None``, this parameter is ignored and the all frames data is returned. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transform (callable, optional): A function/transform that takes in a torch Tensor + and returns a transformed version. E.g, ``transforms.RandomCrop`` + """ + + _URL = "http://www.cs.toronto.edu/~nitish/unsupervised_video/mnist_test_seq.npy" + + def __init__( + self, + root: Union[str, Path], + split: Optional[str] = None, + split_ratio: int = 10, + download: bool = False, + transform: Optional[Callable] = None, + ) -> None: + super().__init__(root, transform=transform) + + self._base_folder = os.path.join(self.root, self.__class__.__name__) + self._filename = self._URL.split("/")[-1] + + if split is not None: + verify_str_arg(split, "split", ("train", "test")) + self.split = split + + if not isinstance(split_ratio, int): + raise TypeError(f"`split_ratio` should be an integer, but got {type(split_ratio)}") + elif not (1 <= split_ratio <= 19): + raise ValueError(f"`split_ratio` should be `1 <= split_ratio <= 19`, but got {split_ratio} instead.") + self.split_ratio = split_ratio + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it.") + + data = torch.from_numpy(np.load(os.path.join(self._base_folder, self._filename))) + if self.split == "train": + data = data[: self.split_ratio] + elif self.split == "test": + data = data[self.split_ratio :] + self.data = data.transpose(0, 1).unsqueeze(2).contiguous() + + def __getitem__(self, idx: int) -> torch.Tensor: + """ + Args: + idx (int): Index + Returns: + torch.Tensor: Video frames (torch Tensor[T, C, H, W]). The `T` is the number of frames. + """ + data = self.data[idx] + if self.transform is not None: + data = self.transform(data) + + return data + + def __len__(self) -> int: + return len(self.data) + + def _check_exists(self) -> bool: + return os.path.exists(os.path.join(self._base_folder, self._filename)) + + def download(self) -> None: + if self._check_exists(): + return + + download_url( + url=self._URL, + root=self._base_folder, + filename=self._filename, + md5="be083ec986bfe91a449d63653c411eb2", + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/omniglot.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/omniglot.py new file mode 100644 index 0000000000000000000000000000000000000000..22fd59aa9c2f107864eda6a79f1bea7ac643710c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/omniglot.py @@ -0,0 +1,107 @@ +from os.path import join +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import check_integrity, download_and_extract_archive, list_dir, list_files +from .vision import VisionDataset + + +class Omniglot(VisionDataset): + """`Omniglot `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``omniglot-py`` exists. + background (bool, optional): If True, creates dataset from the "background" set, otherwise + creates from the "evaluation" set. This terminology is defined by the authors. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset zip files from the internet and + puts it in root directory. If the zip files are already downloaded, they are not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + folder = "omniglot-py" + download_url_prefix = "https://raw.githubusercontent.com/brendenlake/omniglot/master/python" + zips_md5 = { + "images_background": "68d2efa1b9178cc56df9314c21c6e718", + "images_evaluation": "6b91aef0f799c5bb55b94e3f2daec811", + } + + def __init__( + self, + root: Union[str, Path], + background: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Optional[Callable[[Union[str, Path]], Any]] = None, + ) -> None: + super().__init__(join(root, self.folder), transform=transform, target_transform=target_transform) + self.background = background + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.target_folder = join(self.root, self._get_target_folder()) + self._alphabets = list_dir(self.target_folder) + self._characters: list[str] = sum( + ([join(a, c) for c in list_dir(join(self.target_folder, a))] for a in self._alphabets), [] + ) + self._character_images = [ + [(image, idx) for image in list_files(join(self.target_folder, character), ".png")] + for idx, character in enumerate(self._characters) + ] + self._flat_character_images: list[tuple[str, int]] = sum(self._character_images, []) + self.loader = loader + + def __len__(self) -> int: + return len(self._flat_character_images) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target character class. + """ + image_name, character_class = self._flat_character_images[index] + image_path = join(self.target_folder, self._characters[character_class], image_name) + image = Image.open(image_path, mode="r").convert("L") if self.loader is None else self.loader(image_path) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + character_class = self.target_transform(character_class) + + return image, character_class + + def _check_integrity(self) -> bool: + zip_filename = self._get_target_folder() + if not check_integrity(join(self.root, zip_filename + ".zip"), self.zips_md5[zip_filename]): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + + filename = self._get_target_folder() + zip_filename = filename + ".zip" + url = self.download_url_prefix + "/" + zip_filename + download_and_extract_archive(url, self.root, filename=zip_filename, md5=self.zips_md5[filename]) + + def _get_target_folder(self) -> str: + return "images_background" if self.background else "images_evaluation" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/oxford_iiit_pet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/oxford_iiit_pet.py new file mode 100644 index 0000000000000000000000000000000000000000..e598920f8fe392f45a212dc7251ec84d5bb399b4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/oxford_iiit_pet.py @@ -0,0 +1,135 @@ +import os +import os.path +import pathlib +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class OxfordIIITPet(VisionDataset): + """`Oxford-IIIT Pet Dataset `_. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"trainval"`` (default) or ``"test"``. + target_types (string, sequence of strings, optional): Types of target to use. Can be ``category`` (default) or + ``segmentation``. Can also be a list to output a tuple with all specified target types. The types represent: + + - ``category`` (int): Label for one of the 37 pet categories. + - ``binary-category`` (int): Binary label for cat or dog. + - ``segmentation`` (PIL image): Segmentation trimap of the image. + + If empty, ``None`` will be returned as target. + + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + transforms (callable, optional): A function/transform that takes input sample + and its target as entry and returns a transformed version. + download (bool, optional): If True, downloads the dataset from the internet and puts it into + ``root/oxford-iiit-pet``. If dataset is already downloaded, it is not downloaded again. + """ + + _RESOURCES = ( + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz", "5c4f3ee8e5d25df40f4fd59a7f44e54c"), + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz", "95a8c909bbe2e81eed6a22bccdf3f68f"), + ) + _VALID_TARGET_TYPES = ("category", "binary-category", "segmentation") + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "trainval", + target_types: Union[Sequence[str], str] = "category", + transforms: Optional[Callable] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ): + self._split = verify_str_arg(split, "split", ("trainval", "test")) + if isinstance(target_types, str): + target_types = [target_types] + self._target_types = [ + verify_str_arg(target_type, "target_types", self._VALID_TARGET_TYPES) for target_type in target_types + ] + + super().__init__(root, transforms=transforms, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / "oxford-iiit-pet" + self._images_folder = self._base_folder / "images" + self._anns_folder = self._base_folder / "annotations" + self._segs_folder = self._anns_folder / "trimaps" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + image_ids = [] + self._labels = [] + self._bin_labels = [] + with open(self._anns_folder / f"{self._split}.txt") as file: + for line in file: + image_id, label, bin_label, _ = line.strip().split() + image_ids.append(image_id) + self._labels.append(int(label) - 1) + self._bin_labels.append(int(bin_label) - 1) + + self.bin_classes = ["Cat", "Dog"] + self.classes = [ + " ".join(part.title() for part in raw_cls.split("_")) + for raw_cls, _ in sorted( + {(image_id.rsplit("_", 1)[0], label) for image_id, label in zip(image_ids, self._labels)}, + key=lambda image_id_and_label: image_id_and_label[1], + ) + ] + self.bin_class_to_idx = dict(zip(self.bin_classes, range(len(self.bin_classes)))) + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + + self._images = [self._images_folder / f"{image_id}.jpg" for image_id in image_ids] + self._segs = [self._segs_folder / f"{image_id}.png" for image_id in image_ids] + + def __len__(self) -> int: + return len(self._images) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image = Image.open(self._images[idx]).convert("RGB") + + target: Any = [] + for target_type in self._target_types: + if target_type == "category": + target.append(self._labels[idx]) + elif target_type == "binary-category": + target.append(self._bin_labels[idx]) + else: # target_type == "segmentation" + target.append(Image.open(self._segs[idx])) + + if not target: + target = None + elif len(target) == 1: + target = target[0] + else: + target = tuple(target) + + if self.transforms: + image, target = self.transforms(image, target) + + return image, target + + def _check_exists(self) -> bool: + for folder in (self._images_folder, self._anns_folder): + if not (os.path.exists(folder) and os.path.isdir(folder)): + return False + else: + return True + + def _download(self) -> None: + if self._check_exists(): + return + + for url, md5 in self._RESOURCES: + download_and_extract_archive(url, download_root=str(self._base_folder), md5=md5) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/pcam.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/pcam.py new file mode 100644 index 0000000000000000000000000000000000000000..00d10f6a01035bf4cafa57231176c826c463c6f3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/pcam.py @@ -0,0 +1,134 @@ +import pathlib +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import _decompress, download_file_from_google_drive, verify_str_arg +from .vision import VisionDataset + + +class PCAM(VisionDataset): + """`PCAM Dataset `_. + + The PatchCamelyon dataset is a binary classification dataset with 327,680 + color images (96px x 96px), extracted from histopathologic scans of lymph node + sections. Each image is annotated with a binary label indicating presence of + metastatic tissue. + + This dataset requires the ``h5py`` package which you can install with ``pip install h5py``. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"test"`` or ``"val"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and puts it into ``root/pcam``. If + dataset is already downloaded, it is not downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + """ + + _FILES = { + "train": { + "images": ( + "camelyonpatch_level_2_split_train_x.h5", # Data file name + "1Ka0XfEMiwgCYPdTI-vv6eUElOBnKFKQ2", # Google Drive ID + "1571f514728f59376b705fc836ff4b63", # md5 hash + ), + "targets": ( + "camelyonpatch_level_2_split_train_y.h5", + "1269yhu3pZDP8UYFQs-NYs3FPwuK-nGSG", + "35c2d7259d906cfc8143347bb8e05be7", + ), + }, + "test": { + "images": ( + "camelyonpatch_level_2_split_test_x.h5", + "1qV65ZqZvWzuIVthK8eVDhIwrbnsJdbg_", + "d8c2d60d490dbd479f8199bdfa0cf6ec", + ), + "targets": ( + "camelyonpatch_level_2_split_test_y.h5", + "17BHrSrwWKjYsOgTMmoqrIjDy6Fa2o_gP", + "60a7035772fbdb7f34eb86d4420cf66a", + ), + }, + "val": { + "images": ( + "camelyonpatch_level_2_split_valid_x.h5", + "1hgshYGWK8V-eGRy8LToWJJgDU_rXWVJ3", + "d5b63470df7cfa627aeec8b9dc0c066e", + ), + "targets": ( + "camelyonpatch_level_2_split_valid_y.h5", + "1bH8ZRbhSVAhScTS0p9-ZzGnX91cHT3uO", + "2b85f58b927af9964a4c15b8f7e8f179", + ), + }, + } + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ): + try: + import h5py + + self.h5py = h5py + except ImportError: + raise RuntimeError( + "h5py is not found. This dataset needs to have h5py installed: please run pip install h5py" + ) + + self._split = verify_str_arg(split, "split", ("train", "test", "val")) + + super().__init__(root, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / "pcam" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + def __len__(self) -> int: + images_file = self._FILES[self._split]["images"][0] + with self.h5py.File(self._base_folder / images_file) as images_data: + return images_data["x"].shape[0] + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + images_file = self._FILES[self._split]["images"][0] + with self.h5py.File(self._base_folder / images_file) as images_data: + image = Image.fromarray(images_data["x"][idx]).convert("RGB") + + targets_file = self._FILES[self._split]["targets"][0] + with self.h5py.File(self._base_folder / targets_file) as targets_data: + target = int(targets_data["y"][idx, 0, 0, 0]) # shape is [num_images, 1, 1, 1] + + if self.transform: + image = self.transform(image) + if self.target_transform: + target = self.target_transform(target) + + return image, target + + def _check_exists(self) -> bool: + images_file = self._FILES[self._split]["images"][0] + targets_file = self._FILES[self._split]["targets"][0] + return all(self._base_folder.joinpath(h5_file).exists() for h5_file in (images_file, targets_file)) + + def _download(self) -> None: + if self._check_exists(): + return + + for file_name, file_id, md5 in self._FILES[self._split].values(): + archive_name = file_name + ".gz" + download_file_from_google_drive(file_id, str(self._base_folder), filename=archive_name, md5=md5) + _decompress(str(self._base_folder / archive_name)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/phototour.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/phototour.py new file mode 100644 index 0000000000000000000000000000000000000000..5d625b51ecef08164b82328ec0d18338eecda31c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/phototour.py @@ -0,0 +1,230 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +import torch +from PIL import Image + +from .utils import download_url +from .vision import VisionDataset + + +class PhotoTour(VisionDataset): + """`Multi-view Stereo Correspondence `_ Dataset. + + .. note:: + + We only provide the newer version of the dataset, since the authors state that it + + is more suitable for training descriptors based on difference of Gaussian, or Harris corners, as the + patches are centred on real interest point detections, rather than being projections of 3D points as is the + case in the old dataset. + + The original dataset is available under http://phototour.cs.washington.edu/patches/default.htm. + + + Args: + root (str or ``pathlib.Path``): Root directory where images are. + name (string): Name of the dataset to load. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + urls = { + "notredame_harris": [ + "http://matthewalunbrown.com/patchdata/notredame_harris.zip", + "notredame_harris.zip", + "69f8c90f78e171349abdf0307afefe4d", + ], + "yosemite_harris": [ + "http://matthewalunbrown.com/patchdata/yosemite_harris.zip", + "yosemite_harris.zip", + "a73253d1c6fbd3ba2613c45065c00d46", + ], + "liberty_harris": [ + "http://matthewalunbrown.com/patchdata/liberty_harris.zip", + "liberty_harris.zip", + "c731fcfb3abb4091110d0ae8c7ba182c", + ], + "notredame": [ + "http://icvl.ee.ic.ac.uk/vbalnt/notredame.zip", + "notredame.zip", + "509eda8535847b8c0a90bbb210c83484", + ], + "yosemite": ["http://icvl.ee.ic.ac.uk/vbalnt/yosemite.zip", "yosemite.zip", "533b2e8eb7ede31be40abc317b2fd4f0"], + "liberty": ["http://icvl.ee.ic.ac.uk/vbalnt/liberty.zip", "liberty.zip", "fdd9152f138ea5ef2091746689176414"], + } + means = { + "notredame": 0.4854, + "yosemite": 0.4844, + "liberty": 0.4437, + "notredame_harris": 0.4854, + "yosemite_harris": 0.4844, + "liberty_harris": 0.4437, + } + stds = { + "notredame": 0.1864, + "yosemite": 0.1818, + "liberty": 0.2019, + "notredame_harris": 0.1864, + "yosemite_harris": 0.1818, + "liberty_harris": 0.2019, + } + lens = { + "notredame": 468159, + "yosemite": 633587, + "liberty": 450092, + "liberty_harris": 379587, + "yosemite_harris": 450912, + "notredame_harris": 325295, + } + image_ext = "bmp" + info_file = "info.txt" + matches_files = "m50_100000_100000_0.txt" + + def __init__( + self, + root: Union[str, Path], + name: str, + train: bool = True, + transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform) + self.name = name + self.data_dir = os.path.join(self.root, name) + self.data_down = os.path.join(self.root, f"{name}.zip") + self.data_file = os.path.join(self.root, f"{name}.pt") + + self.train = train + self.mean = self.means[name] + self.std = self.stds[name] + + if download: + self.download() + + if not self._check_datafile_exists(): + self.cache() + + # load the serialized data + self.data, self.labels, self.matches = torch.load(self.data_file, weights_only=True) + + def __getitem__(self, index: int) -> Union[torch.Tensor, tuple[Any, Any, torch.Tensor]]: + """ + Args: + index (int): Index + + Returns: + tuple: (data1, data2, matches) + """ + if self.train: + data = self.data[index] + if self.transform is not None: + data = self.transform(data) + return data + m = self.matches[index] + data1, data2 = self.data[m[0]], self.data[m[1]] + if self.transform is not None: + data1 = self.transform(data1) + data2 = self.transform(data2) + return data1, data2, m[2] + + def __len__(self) -> int: + return len(self.data if self.train else self.matches) + + def _check_datafile_exists(self) -> bool: + return os.path.exists(self.data_file) + + def _check_downloaded(self) -> bool: + return os.path.exists(self.data_dir) + + def download(self) -> None: + if self._check_datafile_exists(): + return + + if not self._check_downloaded(): + # download files + url = self.urls[self.name][0] + filename = self.urls[self.name][1] + md5 = self.urls[self.name][2] + fpath = os.path.join(self.root, filename) + + download_url(url, self.root, filename, md5) + + import zipfile + + with zipfile.ZipFile(fpath, "r") as z: + z.extractall(self.data_dir) + + os.unlink(fpath) + + def cache(self) -> None: + # process and save as torch files + + dataset = ( + read_image_file(self.data_dir, self.image_ext, self.lens[self.name]), + read_info_file(self.data_dir, self.info_file), + read_matches_files(self.data_dir, self.matches_files), + ) + + with open(self.data_file, "wb") as f: + torch.save(dataset, f) + + def extra_repr(self) -> str: + split = "Train" if self.train is True else "Test" + return f"Split: {split}" + + +def read_image_file(data_dir: str, image_ext: str, n: int) -> torch.Tensor: + """Return a Tensor containing the patches""" + + def PIL2array(_img: Image.Image) -> np.ndarray: + """Convert PIL image type to numpy 2D array""" + return np.array(_img.getdata(), dtype=np.uint8).reshape(64, 64) + + def find_files(_data_dir: str, _image_ext: str) -> list[str]: + """Return a list with the file names of the images containing the patches""" + files = [] + # find those files with the specified extension + for file_dir in os.listdir(_data_dir): + if file_dir.endswith(_image_ext): + files.append(os.path.join(_data_dir, file_dir)) + return sorted(files) # sort files in ascend order to keep relations + + patches = [] + list_files = find_files(data_dir, image_ext) + + for fpath in list_files: + img = Image.open(fpath) + for y in range(0, img.height, 64): + for x in range(0, img.width, 64): + patch = img.crop((x, y, x + 64, y + 64)) + patches.append(PIL2array(patch)) + return torch.ByteTensor(np.array(patches[:n])) + + +def read_info_file(data_dir: str, info_file: str) -> torch.Tensor: + """Return a Tensor containing the list of labels + Read the file and keep only the ID of the 3D point. + """ + with open(os.path.join(data_dir, info_file)) as f: + labels = [int(line.split()[0]) for line in f] + return torch.LongTensor(labels) + + +def read_matches_files(data_dir: str, matches_file: str) -> torch.Tensor: + """Return a Tensor containing the ground truth matches + Read the file and keep only 3D point ID. + Matches are represented with a 1, non matches with a 0. + """ + matches = [] + with open(os.path.join(data_dir, matches_file)) as f: + for line in f: + line_split = line.split() + matches.append([int(line_split[0]), int(line_split[3]), int(line_split[1] == line_split[4])]) + return torch.LongTensor(matches) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/places365.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/places365.py new file mode 100644 index 0000000000000000000000000000000000000000..51b845de7234635a17a6ef87a9649898c9cdc0b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/places365.py @@ -0,0 +1,176 @@ +import os +from os import path +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union +from urllib.parse import urljoin + +from .folder import default_loader +from .utils import check_integrity, download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Places365(VisionDataset): + r"""`Places365 `_ classification dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the Places365 dataset. + split (string, optional): The dataset split. Can be one of ``train-standard`` (default), ``train-challenge``, + ``val``, ``test``. + small (bool, optional): If ``True``, uses the small images, i.e. resized to 256 x 256 pixels, instead of the + high resolution ones. + download (bool, optional): If ``True``, downloads the dataset components and places them in ``root``. Already + downloaded archives are not downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + + Attributes: + classes (list): List of the class names. + class_to_idx (dict): Dict with items (class_name, class_index). + imgs (list): List of (image path, class_index) tuples + targets (list): The class_index value for each image in the dataset + + Raises: + RuntimeError: If ``download is False`` and the meta files, i.e. the devkit, are not present or corrupted. + RuntimeError: If ``download is True`` and the image archive is already extracted. + """ + + _SPLITS = ("train-standard", "train-challenge", "val", "test") + _BASE_URL = "http://data.csail.mit.edu/places/places365/" + # {variant: (archive, md5)} + _DEVKIT_META = { + "standard": ("filelist_places365-standard.tar", "35a0585fee1fa656440f3ab298f8479c"), + "challenge": ("filelist_places365-challenge.tar", "70a8307e459c3de41690a7c76c931734"), + } + # (file, md5) + _CATEGORIES_META = ("categories_places365.txt", "06c963b85866bd0649f97cb43dd16673") + # {split: (file, md5)} + _FILE_LIST_META = { + "train-standard": ("places365_train_standard.txt", "30f37515461640559006b8329efbed1a"), + "train-challenge": ("places365_train_challenge.txt", "b2931dc997b8c33c27e7329c073a6b57"), + "val": ("places365_val.txt", "e9f2fd57bfd9d07630173f4e8708e4b1"), + "test": ("places365_test.txt", "2fce8233fe493576d724142e45d93653"), + } + # {(split, small): (file, md5)} + _IMAGES_META = { + ("train-standard", False): ("train_large_places365standard.tar", "67e186b496a84c929568076ed01a8aa1"), + ("train-challenge", False): ("train_large_places365challenge.tar", "605f18e68e510c82b958664ea134545f"), + ("val", False): ("val_large.tar", "9b71c4993ad89d2d8bcbdc4aef38042f"), + ("test", False): ("test_large.tar", "41a4b6b724b1d2cd862fb3871ed59913"), + ("train-standard", True): ("train_256_places365standard.tar", "53ca1c756c3d1e7809517cc47c5561c5"), + ("train-challenge", True): ("train_256_places365challenge.tar", "741915038a5e3471ec7332404dfb64ef"), + ("val", True): ("val_256.tar", "e27b17d8d44f4af9a78502beb927f808"), + ("test", True): ("test_256.tar", "f532f6ad7b582262a2ec8009075e186b"), + } + + def __init__( + self, + root: Union[str, Path], + split: str = "train-standard", + small: bool = False, + download: bool = False, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + self.split = self._verify_split(split) + self.small = small + self.loader = loader + + self.classes, self.class_to_idx = self.load_categories(download) + self.imgs, self.targets = self.load_file_list(download) + + if download: + self.download_images() + + def __getitem__(self, index: int) -> tuple[Any, Any]: + file, target = self.imgs[index] + image = self.loader(file) + + if self.transforms is not None: + image, target = self.transforms(image, target) + + return image, target + + def __len__(self) -> int: + return len(self.imgs) + + @property + def variant(self) -> str: + return "challenge" if "challenge" in self.split else "standard" + + @property + def images_dir(self) -> str: + size = "256" if self.small else "large" + if self.split.startswith("train"): + dir = f"data_{size}_{self.variant}" + else: + dir = f"{self.split}_{size}" + return path.join(self.root, dir) + + def load_categories(self, download: bool = True) -> tuple[list[str], dict[str, int]]: + def process(line: str) -> tuple[str, int]: + cls, idx = line.split() + return cls, int(idx) + + file, md5 = self._CATEGORIES_META + file = path.join(self.root, file) + if not self._check_integrity(file, md5, download): + self.download_devkit() + + with open(file) as fh: + class_to_idx = dict(process(line) for line in fh) + + return sorted(class_to_idx.keys()), class_to_idx + + def load_file_list( + self, download: bool = True + ) -> tuple[list[tuple[str, Union[int, None]]], list[Union[int, None]]]: + def process(line: str, sep="/") -> tuple[str, Union[int, None]]: + image, idx = (line.split() + [None])[:2] + image = cast(str, image) + idx = int(idx) if idx is not None else None + return path.join(self.images_dir, image.lstrip(sep).replace(sep, os.sep)), idx + + file, md5 = self._FILE_LIST_META[self.split] + file = path.join(self.root, file) + if not self._check_integrity(file, md5, download): + self.download_devkit() + + with open(file) as fh: + images = [process(line) for line in fh] + + _, targets = zip(*images) + return images, list(targets) + + def download_devkit(self) -> None: + file, md5 = self._DEVKIT_META[self.variant] + download_and_extract_archive(urljoin(self._BASE_URL, file), self.root, md5=md5) + + def download_images(self) -> None: + if path.exists(self.images_dir): + return + + file, md5 = self._IMAGES_META[(self.split, self.small)] + download_and_extract_archive(urljoin(self._BASE_URL, file), self.root, md5=md5) + + if self.split.startswith("train"): + os.rename(self.images_dir.rsplit("_", 1)[0], self.images_dir) + + def extra_repr(self) -> str: + return "\n".join(("Split: {split}", "Small: {small}")).format(**self.__dict__) + + def _verify_split(self, split: str) -> str: + return verify_str_arg(split, "split", self._SPLITS) + + def _check_integrity(self, file: str, md5: str, download: bool) -> bool: + integrity = check_integrity(file, md5=md5) + if not integrity and not download: + raise RuntimeError( + f"The file {file} does not exist or is corrupted. You can set download=True to download it." + ) + return integrity diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/rendered_sst2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/rendered_sst2.py new file mode 100644 index 0000000000000000000000000000000000000000..62ad3bc6d0018a3c297607d6ad4e221ed0b7595a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/rendered_sst2.py @@ -0,0 +1,89 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, make_dataset +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class RenderedSST2(VisionDataset): + """`The Rendered SST2 Dataset `_. + + Rendered SST2 is an image classification dataset used to evaluate the models capability on optical + character recognition. This dataset was generated by rendering sentences in the Standford Sentiment + Treebank v2 dataset. + + This dataset contains two classes (positive and negative) and is divided in three splits: a train + split containing 6920 images (3610 positive and 3310 negative), a validation split containing 872 images + (444 positive and 428 negative), and a test split containing 1821 images (909 positive and 912 negative). + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), `"val"` and ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://openaipublic.azureedge.net/clip/data/rendered-sst2.tgz" + _MD5 = "2384d08e9dcfa4bd55b324e610496ee5" + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + self._split_to_folder = {"train": "train", "val": "valid", "test": "test"} + self._base_folder = Path(self.root) / "rendered-sst2" + self.classes = ["negative", "positive"] + self.class_to_idx = {"negative": 0, "positive": 1} + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self._samples = make_dataset(str(self._base_folder / self._split_to_folder[self._split]), extensions=("png",)) + self.loader = loader + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._samples[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}" + + def _check_exists(self) -> bool: + for class_label in set(self.classes): + if not (self._base_folder / self._split_to_folder[self._split] / class_label).is_dir(): + return False + return True + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/samplers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58b2d2abd936d885221174d194a633a8e413935f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/samplers/__init__.py @@ -0,0 +1,3 @@ +from .clip_sampler import DistributedSampler, RandomClipSampler, UniformClipSampler + +__all__ = ("DistributedSampler", "UniformClipSampler", "RandomClipSampler") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/samplers/clip_sampler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/samplers/clip_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..570bc85eee906686a63f114eff6db08480737a8a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/samplers/clip_sampler.py @@ -0,0 +1,173 @@ +import math +from collections.abc import Iterator, Sized +from typing import cast, Optional, Union + +import torch +import torch.distributed as dist +from torch.utils.data import Sampler +from torchvision.datasets.video_utils import VideoClips + + +class DistributedSampler(Sampler): + """ + Extension of DistributedSampler, as discussed in + https://github.com/pytorch/pytorch/issues/23430 + + Example: + dataset: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + num_replicas: 4 + shuffle: False + + when group_size = 1 + RANK | shard_dataset + ========================= + rank_0 | [0, 4, 8, 12] + rank_1 | [1, 5, 9, 13] + rank_2 | [2, 6, 10, 0] + rank_3 | [3, 7, 11, 1] + + when group_size = 2 + + RANK | shard_dataset + ========================= + rank_0 | [0, 1, 8, 9] + rank_1 | [2, 3, 10, 11] + rank_2 | [4, 5, 12, 13] + rank_3 | [6, 7, 0, 1] + + """ + + def __init__( + self, + dataset: Sized, + num_replicas: Optional[int] = None, + rank: Optional[int] = None, + shuffle: bool = False, + group_size: int = 1, + ) -> None: + if num_replicas is None: + if not dist.is_available(): + raise RuntimeError("Requires distributed package to be available") + num_replicas = dist.get_world_size() + if rank is None: + if not dist.is_available(): + raise RuntimeError("Requires distributed package to be available") + rank = dist.get_rank() + if len(dataset) % group_size != 0: + raise ValueError( + f"dataset length must be a multiplier of group size dataset length: {len(dataset)}, group size: {group_size}" + ) + self.dataset = dataset + self.group_size = group_size + self.num_replicas = num_replicas + self.rank = rank + self.epoch = 0 + dataset_group_length = len(dataset) // group_size + self.num_group_samples = int(math.ceil(dataset_group_length * 1.0 / self.num_replicas)) + self.num_samples = self.num_group_samples * group_size + self.total_size = self.num_samples * self.num_replicas + self.shuffle = shuffle + + def __iter__(self) -> Iterator[int]: + # deterministically shuffle based on epoch + g = torch.Generator() + g.manual_seed(self.epoch) + indices: Union[torch.Tensor, list[int]] + if self.shuffle: + indices = torch.randperm(len(self.dataset), generator=g).tolist() + else: + indices = list(range(len(self.dataset))) + + # add extra samples to make it evenly divisible + indices += indices[: (self.total_size - len(indices))] + assert len(indices) == self.total_size + + total_group_size = self.total_size // self.group_size + indices = torch.reshape(torch.LongTensor(indices), (total_group_size, self.group_size)) + + # subsample + indices = indices[self.rank : total_group_size : self.num_replicas, :] + indices = torch.reshape(indices, (-1,)).tolist() + assert len(indices) == self.num_samples + + if isinstance(self.dataset, Sampler): + orig_indices = list(iter(self.dataset)) + indices = [orig_indices[i] for i in indices] + + return iter(indices) + + def __len__(self) -> int: + return self.num_samples + + def set_epoch(self, epoch: int) -> None: + self.epoch = epoch + + +class UniformClipSampler(Sampler): + """ + Sample `num_video_clips_per_video` clips for each video, equally spaced. + When number of unique clips in the video is fewer than num_video_clips_per_video, + repeat the clips until `num_video_clips_per_video` clips are collected + + Args: + video_clips (VideoClips): video clips to sample from + num_clips_per_video (int): number of clips to be sampled per video + """ + + def __init__(self, video_clips: VideoClips, num_clips_per_video: int) -> None: + if not isinstance(video_clips, VideoClips): + raise TypeError(f"Expected video_clips to be an instance of VideoClips, got {type(video_clips)}") + self.video_clips = video_clips + self.num_clips_per_video = num_clips_per_video + + def __iter__(self) -> Iterator[int]: + idxs = [] + s = 0 + # select num_clips_per_video for each video, uniformly spaced + for c in self.video_clips.clips: + length = len(c) + if length == 0: + # corner case where video decoding fails + continue + + sampled = torch.linspace(s, s + length - 1, steps=self.num_clips_per_video).floor().to(torch.int64) + s += length + idxs.append(sampled) + return iter(cast(list[int], torch.cat(idxs).tolist())) + + def __len__(self) -> int: + return sum(self.num_clips_per_video for c in self.video_clips.clips if len(c) > 0) + + +class RandomClipSampler(Sampler): + """ + Samples at most `max_video_clips_per_video` clips for each video randomly + + Args: + video_clips (VideoClips): video clips to sample from + max_clips_per_video (int): maximum number of clips to be sampled per video + """ + + def __init__(self, video_clips: VideoClips, max_clips_per_video: int) -> None: + if not isinstance(video_clips, VideoClips): + raise TypeError(f"Expected video_clips to be an instance of VideoClips, got {type(video_clips)}") + self.video_clips = video_clips + self.max_clips_per_video = max_clips_per_video + + def __iter__(self) -> Iterator[int]: + idxs = [] + s = 0 + # select at most max_clips_per_video for each video, randomly + for c in self.video_clips.clips: + length = len(c) + size = min(length, self.max_clips_per_video) + sampled = torch.randperm(length)[:size] + s + s += length + idxs.append(sampled) + idxs_ = torch.cat(idxs) + # shuffle all clips randomly + perm = torch.randperm(len(idxs_)) + return iter(idxs_[perm].tolist()) + + def __len__(self) -> int: + return sum(min(len(c), self.max_clips_per_video) for c in self.video_clips.clips) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sbd.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sbd.py new file mode 100644 index 0000000000000000000000000000000000000000..091e8698197584064974664474083a87d64f2908 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sbd.py @@ -0,0 +1,126 @@ +import os +import shutil +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import download_and_extract_archive, download_url, verify_str_arg +from .vision import VisionDataset + + +class SBDataset(VisionDataset): + """`Semantic Boundaries Dataset `_ + + The SBD currently contains annotations from 11355 images taken from the PASCAL VOC 2011 dataset. + + .. note :: + + Please note that the train and val splits included with this dataset are different from + the splits in the PASCAL VOC dataset. In particular some "train" images might be part of + VOC2012 val. + If you are interested in testing on VOC 2012 val, then use `image_set='train_noval'`, + which excludes all val images. + + .. warning:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of the Semantic Boundaries Dataset + image_set (string, optional): Select the image_set to use, ``train``, ``val`` or ``train_noval``. + Image set ``train_noval`` excludes VOC 2012 val images. + mode (string, optional): Select target type. Possible values 'boundaries' or 'segmentation'. + In case of 'boundaries', the target is an array of shape `[num_classes, H, W]`, + where `num_classes=20`. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. Input sample is PIL image and target is a numpy array + if `mode='boundaries'` or PIL image if `mode='segmentation'`. + """ + + url = "https://www2.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz" + md5 = "82b4d87ceb2ed10f6038a1cba92111cb" + filename = "benchmark.tgz" + + voc_train_url = "https://www.cs.cornell.edu/~bharathh/train_noval.txt" + voc_split_filename = "train_noval.txt" + voc_split_md5 = "79bff800c5f0b1ec6b21080a3c066722" + + def __init__( + self, + root: Union[str, Path], + image_set: str = "train", + mode: str = "boundaries", + download: bool = False, + transforms: Optional[Callable] = None, + ) -> None: + + try: + from scipy.io import loadmat + + self._loadmat = loadmat + except ImportError: + raise RuntimeError("Scipy is not found. This dataset needs to have scipy installed: pip install scipy") + + super().__init__(root, transforms) + self.image_set = verify_str_arg(image_set, "image_set", ("train", "val", "train_noval")) + self.mode = verify_str_arg(mode, "mode", ("segmentation", "boundaries")) + self.num_classes = 20 + + sbd_root = self.root + image_dir = os.path.join(sbd_root, "img") + mask_dir = os.path.join(sbd_root, "cls") + + if download: + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.md5) + extracted_ds_root = os.path.join(self.root, "benchmark_RELEASE", "dataset") + for f in ["cls", "img", "inst", "train.txt", "val.txt"]: + old_path = os.path.join(extracted_ds_root, f) + shutil.move(old_path, sbd_root) + if self.image_set == "train_noval": + # Note: this is failing as of June 2024 https://github.com/pytorch/vision/issues/8471 + download_url(self.voc_train_url, sbd_root, self.voc_split_filename, self.voc_split_md5) + + if not os.path.isdir(sbd_root): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + split_f = os.path.join(sbd_root, image_set.rstrip("\n") + ".txt") + + with open(os.path.join(split_f)) as fh: + file_names = [x.strip() for x in fh.readlines()] + + self.images = [os.path.join(image_dir, x + ".jpg") for x in file_names] + self.masks = [os.path.join(mask_dir, x + ".mat") for x in file_names] + + self._get_target = self._get_segmentation_target if self.mode == "segmentation" else self._get_boundaries_target + + def _get_segmentation_target(self, filepath: str) -> Image.Image: + mat = self._loadmat(filepath) + return Image.fromarray(mat["GTcls"][0]["Segmentation"][0]) + + def _get_boundaries_target(self, filepath: str) -> np.ndarray: + mat = self._loadmat(filepath) + return np.concatenate( + [np.expand_dims(mat["GTcls"][0]["Boundaries"][0][i][0].toarray(), axis=0) for i in range(self.num_classes)], + axis=0, + ) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + img = Image.open(self.images[index]).convert("RGB") + target = self._get_target(self.masks[index]) + + if self.transforms is not None: + img, target = self.transforms(img, target) + + return img, target + + def __len__(self) -> int: + return len(self.images) + + def extra_repr(self) -> str: + lines = ["Image set: {image_set}", "Mode: {mode}"] + return "\n".join(lines).format(**self.__dict__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sbu.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sbu.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c97503eec5f886fe1a188bdd797c710f93daa6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sbu.py @@ -0,0 +1,114 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import check_integrity, download_and_extract_archive, download_url +from .vision import VisionDataset + + +class SBU(VisionDataset): + """`SBU Captioned Photo `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where tarball + ``SBUCaptionedPhotoDataset.tar.gz`` exists. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + url = "https://www.cs.rice.edu/~vo9/sbucaptions/SBUCaptionedPhotoDataset.tar.gz" + filename = "SBUCaptionedPhotoDataset.tar.gz" + md5_checksum = "9aec147b3488753cf758b4d493422285" + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = True, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.loader = loader + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + # Read the caption for each photo + self.photos = [] + self.captions = [] + + file1 = os.path.join(self.root, "dataset", "SBU_captioned_photo_dataset_urls.txt") + file2 = os.path.join(self.root, "dataset", "SBU_captioned_photo_dataset_captions.txt") + + for line1, line2 in zip(open(file1), open(file2)): + url = line1.rstrip() + photo = os.path.basename(url) + filename = os.path.join(self.root, "dataset", photo) + if os.path.exists(filename): + caption = line2.rstrip() + self.photos.append(photo) + self.captions.append(caption) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is a caption for the photo. + """ + filename = os.path.join(self.root, "dataset", self.photos[index]) + img = self.loader(filename) + if self.transform is not None: + img = self.transform(img) + + target = self.captions[index] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + """The number of photos in the dataset.""" + return len(self.photos) + + def _check_integrity(self) -> bool: + """Check the md5 checksum of the downloaded tarball.""" + root = self.root + fpath = os.path.join(root, self.filename) + if not check_integrity(fpath, self.md5_checksum): + return False + return True + + def download(self) -> None: + """Download and extract the tarball, and download each individual photo.""" + + if self._check_integrity(): + return + + download_and_extract_archive(self.url, self.root, self.root, self.filename, self.md5_checksum) + + # Download individual photos + with open(os.path.join(self.root, "dataset", "SBU_captioned_photo_dataset_urls.txt")) as fh: + for line in fh: + url = line.rstrip() + try: + download_url(url, os.path.join(self.root, "dataset")) + except OSError: + # The images point to public images on Flickr. + # Note: Images might be removed by users at anytime. + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/semeion.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/semeion.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8d139cb21fcd4e2a8157f7071ac43f62b72288 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/semeion.py @@ -0,0 +1,92 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np + +from ..utils import _Image_fromarray +from .utils import check_integrity, download_url +from .vision import VisionDataset + + +class SEMEION(VisionDataset): + r"""`SEMEION `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``semeion.py`` exists. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + url = "http://archive.ics.uci.edu/ml/machine-learning-databases/semeion/semeion.data" + filename = "semeion.data" + md5_checksum = "cb545d371d2ce14ec121470795a77432" + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = True, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + fp = os.path.join(self.root, self.filename) + data = np.loadtxt(fp) + # convert value to 8 bit unsigned integer + # color (white #255) the pixels + self.data = (data[:, :256] * 255).astype("uint8") + self.data = np.reshape(self.data, (-1, 16, 16)) + self.labels = np.nonzero(data[:, 256:])[1] + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.labels[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = _Image_fromarray(img, mode="L") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + def _check_integrity(self) -> bool: + root = self.root + fpath = os.path.join(root, self.filename) + if not check_integrity(fpath, self.md5_checksum): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + + root = self.root + download_url(self.url, root, self.filename, self.md5_checksum) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/stanford_cars.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/stanford_cars.py new file mode 100644 index 0000000000000000000000000000000000000000..e73fb1f3141dad7689ad3ed0ef0a580a2bc02b14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/stanford_cars.py @@ -0,0 +1,105 @@ +import pathlib +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import verify_str_arg +from .vision import VisionDataset + + +class StanfordCars(VisionDataset): + """Stanford Cars Dataset + + The Cars dataset contains 16,185 images of 196 classes of cars. The data is + split into 8,144 training images and 8,041 testing images, where each class + has been split roughly in a 50-50 split + + The original URL is https://ai.stanford.edu/~jkrause/cars/car_dataset.html, + the dataset isn't available online anymore. + + .. note:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset + split (string, optional): The dataset split, supports ``"train"`` (default) or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): This parameter exists for backward compatibility but it does not + download the dataset, since the original URL is not available anymore. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + + try: + import scipy.io as sio + except ImportError: + raise RuntimeError("Scipy is not found. This dataset needs to have scipy installed: pip install scipy") + + super().__init__(root, transform=transform, target_transform=target_transform) + + self._split = verify_str_arg(split, "split", ("train", "test")) + self._base_folder = pathlib.Path(root) / "stanford_cars" + devkit = self._base_folder / "devkit" + + if self._split == "train": + self._annotations_mat_path = devkit / "cars_train_annos.mat" + self._images_base_path = self._base_folder / "cars_train" + else: + self._annotations_mat_path = self._base_folder / "cars_test_annos_withlabels.mat" + self._images_base_path = self._base_folder / "cars_test" + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found.") + + self._samples = [ + ( + str(self._images_base_path / annotation["fname"]), + annotation["class"] - 1, # Original target mapping starts from 1, hence -1 + ) + for annotation in sio.loadmat(self._annotations_mat_path, squeeze_me=True)["annotations"] + ] + + self.classes = sio.loadmat(str(devkit / "cars_meta.mat"), squeeze_me=True)["class_names"].tolist() + self.class_to_idx = {cls: i for i, cls in enumerate(self.classes)} + self.loader = loader + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + """Returns pil_image and class_id for given index""" + image_path, target = self._samples[idx] + image = self.loader(image_path) + + if self.transform is not None: + image = self.transform(image) + if self.target_transform is not None: + target = self.target_transform(target) + return image, target + + def _check_exists(self) -> bool: + if not (self._base_folder / "devkit").is_dir(): + return False + + return self._annotations_mat_path.exists() and self._images_base_path.is_dir() + + def download(self): + raise ValueError("The original URL is broken so the StanfordCars dataset cannot be downloaded anymore.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/stl10.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/stl10.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7212a1b55578334efcfe55861165d4b196326c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/stl10.py @@ -0,0 +1,174 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import check_integrity, download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class STL10(VisionDataset): + """`STL10 `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``stl10_binary`` exists. + split (string): One of {'train', 'test', 'unlabeled', 'train+unlabeled'}. + Accordingly, dataset is selected. + folds (int, optional): One of {0-9} or None. + For training, loads one of the 10 pre-defined folds of 1k samples for the + standard evaluation procedure. If no value is passed, loads the 5k samples. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + base_folder = "stl10_binary" + url = "http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz" + filename = "stl10_binary.tar.gz" + tgz_md5 = "91f7769df0f17e558f3565bffb0c7dfb" + class_names_file = "class_names.txt" + folds_list_file = "fold_indices.txt" + train_list = [ + ["train_X.bin", "918c2871b30a85fa023e0c44e0bee87f"], + ["train_y.bin", "5a34089d4802c674881badbb80307741"], + ["unlabeled_X.bin", "5242ba1fed5e4be9e1e742405eb56ca4"], + ] + + test_list = [["test_X.bin", "7f263ba9f9e0b06b93213547f721ac82"], ["test_y.bin", "36f9794fa4beb8a2c72628de14fa638e"]] + splits = ("train", "train+unlabeled", "unlabeled", "test") + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + folds: Optional[int] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.split = verify_str_arg(split, "split", self.splits) + self.folds = self._verify_folds(folds) + + if download: + self.download() + elif not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + # now load the picked numpy arrays + self.labels: Optional[np.ndarray] + if self.split == "train": + self.data, self.labels = self.__loadfile(self.train_list[0][0], self.train_list[1][0]) + self.labels = cast(np.ndarray, self.labels) + self.__load_folds(folds) + + elif self.split == "train+unlabeled": + self.data, self.labels = self.__loadfile(self.train_list[0][0], self.train_list[1][0]) + self.labels = cast(np.ndarray, self.labels) + self.__load_folds(folds) + unlabeled_data, _ = self.__loadfile(self.train_list[2][0]) + self.data = np.concatenate((self.data, unlabeled_data)) + self.labels = np.concatenate((self.labels, np.asarray([-1] * unlabeled_data.shape[0]))) + + elif self.split == "unlabeled": + self.data, _ = self.__loadfile(self.train_list[2][0]) + self.labels = np.asarray([-1] * self.data.shape[0]) + else: # self.split == 'test': + self.data, self.labels = self.__loadfile(self.test_list[0][0], self.test_list[1][0]) + + class_file = os.path.join(self.root, self.base_folder, self.class_names_file) + if os.path.isfile(class_file): + with open(class_file) as f: + self.classes = f.read().splitlines() + + def _verify_folds(self, folds: Optional[int]) -> Optional[int]: + if folds is None: + return folds + elif isinstance(folds, int): + if folds in range(10): + return folds + msg = "Value for argument folds should be in the range [0, 10), but got {}." + raise ValueError(msg.format(folds)) + else: + msg = "Expected type None or int for argument folds, but got type {}." + raise ValueError(msg.format(type(folds))) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + target: Optional[int] + if self.labels is not None: + img, target = self.data[index], int(self.labels[index]) + else: + img, target = self.data[index], None + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = Image.fromarray(np.transpose(img, (1, 2, 0))) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return self.data.shape[0] + + def __loadfile(self, data_file: str, labels_file: Optional[str] = None) -> tuple[np.ndarray, Optional[np.ndarray]]: + labels = None + if labels_file: + path_to_labels = os.path.join(self.root, self.base_folder, labels_file) + with open(path_to_labels, "rb") as f: + labels = np.fromfile(f, dtype=np.uint8) - 1 # 0-based + + path_to_data = os.path.join(self.root, self.base_folder, data_file) + with open(path_to_data, "rb") as f: + # read whole file in uint8 chunks + everything = np.fromfile(f, dtype=np.uint8) + images = np.reshape(everything, (-1, 3, 96, 96)) + images = np.transpose(images, (0, 1, 3, 2)) + + return images, labels + + def _check_integrity(self) -> bool: + for filename, md5 in self.train_list + self.test_list: + fpath = os.path.join(self.root, self.base_folder, filename) + if not check_integrity(fpath, md5): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5) + self._check_integrity() + + def extra_repr(self) -> str: + return "Split: {split}".format(**self.__dict__) + + def __load_folds(self, folds: Optional[int]) -> None: + # loads one of the folds if specified + if folds is None: + return + path_to_folds = os.path.join(self.root, self.base_folder, self.folds_list_file) + with open(path_to_folds) as f: + str_idx = f.read().splitlines()[folds] + list_idx = np.fromstring(str_idx, dtype=np.int64, sep=" ") + self.data = self.data[list_idx, :, :, :] + if self.labels is not None: + self.labels = self.labels[list_idx] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sun397.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sun397.py new file mode 100644 index 0000000000000000000000000000000000000000..a27f86d95795641c475bbf508c22734e2cf37412 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/sun397.py @@ -0,0 +1,81 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import download_and_extract_archive +from .vision import VisionDataset + + +class SUN397(VisionDataset): + """`The SUN397 Data Set `_. + + The SUN397 or Scene UNderstanding (SUN) is a dataset for scene recognition consisting of + 397 categories with 108'754 images. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _DATASET_URL = "http://vision.princeton.edu/projects/2010/SUN/SUN397.tar.gz" + _DATASET_MD5 = "8ca2778205c41d23104230ba66911c7a" + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, Path]], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._data_dir = Path(self.root) / "SUN397" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + with open(self._data_dir / "ClassName.txt") as f: + self.classes = [c[3:].strip() for c in f] + + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + self._image_files = list(self._data_dir.rglob("sun_*.jpg")) + + self._labels = [ + self.class_to_idx["/".join(path.relative_to(self._data_dir).parts[1:-1])] for path in self._image_files + ] + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def _check_exists(self) -> bool: + return self._data_dir.is_dir() + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._DATASET_URL, download_root=self.root, md5=self._DATASET_MD5) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/svhn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/svhn.py new file mode 100644 index 0000000000000000000000000000000000000000..b59f78ec050d045bbf8099434b8cd579bba12c72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/svhn.py @@ -0,0 +1,130 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import check_integrity, download_url, verify_str_arg +from .vision import VisionDataset + + +class SVHN(VisionDataset): + """`SVHN `_ Dataset. + Note: The SVHN dataset assigns the label `10` to the digit `0`. However, in this Dataset, + we assign the label `0` to the digit `0` to be compatible with PyTorch loss functions which + expect the class labels to be in the range `[0, C-1]` + + .. warning:: + + This class needs `scipy `_ to load data from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset where the data is stored. + split (string): One of {'train', 'test', 'extra'}. + Accordingly dataset is selected. 'extra' is Extra training set. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + split_list = { + "train": [ + "http://ufldl.stanford.edu/housenumbers/train_32x32.mat", + "train_32x32.mat", + "e26dedcc434d2e4c54c9b2d4a06d8373", + ], + "test": [ + "http://ufldl.stanford.edu/housenumbers/test_32x32.mat", + "test_32x32.mat", + "eb5a983be6a315427106f1b164d9cef3", + ], + "extra": [ + "http://ufldl.stanford.edu/housenumbers/extra_32x32.mat", + "extra_32x32.mat", + "a93ce644f1a588dc4d68dda5feec44a7", + ], + } + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.split = verify_str_arg(split, "split", tuple(self.split_list.keys())) + self.url = self.split_list[split][0] + self.filename = self.split_list[split][1] + self.file_md5 = self.split_list[split][2] + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + # import here rather than at top of file because this is + # an optional dependency for torchvision + import scipy.io as sio + + # reading(loading) mat file as array + loaded_mat = sio.loadmat(os.path.join(self.root, self.filename)) + + self.data = loaded_mat["X"] + # loading from the .mat file gives an np.ndarray of type np.uint8 + # converting to np.int64, so that we have a LongTensor after + # the conversion from the numpy array + # the squeeze is needed to obtain a 1D tensor + self.labels = loaded_mat["y"].astype(np.int64).squeeze() + + # the svhn dataset assigns the class label "10" to the digit 0 + # this makes it inconsistent with several loss functions + # which expect the class labels to be in the range [0, C-1] + np.place(self.labels, self.labels == 10, 0) + self.data = np.transpose(self.data, (3, 2, 0, 1)) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.labels[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = Image.fromarray(np.transpose(img, (1, 2, 0))) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + def _check_integrity(self) -> bool: + root = self.root + md5 = self.split_list[self.split][2] + fpath = os.path.join(root, self.filename) + return check_integrity(fpath, md5) + + def download(self) -> None: + md5 = self.split_list[self.split][2] + download_url(self.url, self.root, self.filename, md5) + + def extra_repr(self) -> str: + return "Split: {split}".format(**self.__dict__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/ucf101.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/ucf101.py new file mode 100644 index 0000000000000000000000000000000000000000..85930dbc742beb0dcfdac6e515f16966b92b9634 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/ucf101.py @@ -0,0 +1,131 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from torch import Tensor + +from .folder import find_classes, make_dataset +from .video_utils import VideoClips +from .vision import VisionDataset + + +class UCF101(VisionDataset): + """ + `UCF101 `_ dataset. + + UCF101 is an action recognition video dataset. + This dataset consider every video as a collection of video clips of fixed size, specified + by ``frames_per_clip``, where the step in frames between each clip is given by + ``step_between_clips``. The dataset itself can be downloaded from the dataset website; + annotations that ``annotation_path`` should be pointing to can be downloaded from `here + `_. + + To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5`` + and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two + elements will come from video 1, and the next three elements from video 2. + Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all + frames in a video might be present. + + Internally, it uses a VideoClips object to handle clip creation. + + Args: + root (str or ``pathlib.Path``): Root directory of the UCF101 Dataset. + annotation_path (str): path to the folder containing the split files; + see docstring above for download instructions of these files + frames_per_clip (int): number of frames in a clip. + step_between_clips (int, optional): number of frames between each clip. + fold (int, optional): which fold to use. Should be between 1 and 3. + train (bool, optional): if ``True``, creates a dataset from the train split, + otherwise from the ``test`` split. + transform (callable, optional): A function/transform that takes in a TxHxWxC video + and returns a transformed version. + output_format (str, optional): The format of the output video tensors (before transforms). + Can be either "THWC" (default) or "TCHW". + + Returns: + tuple: A 3-tuple with the following entries: + + - video (Tensor[T, H, W, C] or Tensor[T, C, H, W]): The `T` video frames + - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels + and `L` is the number of points + - label (int): class of the video clip + """ + + def __init__( + self, + root: Union[str, Path], + annotation_path: str, + frames_per_clip: int, + step_between_clips: int = 1, + frame_rate: Optional[int] = None, + fold: int = 1, + train: bool = True, + transform: Optional[Callable] = None, + _precomputed_metadata: Optional[dict[str, Any]] = None, + num_workers: int = 1, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _audio_samples: int = 0, + output_format: str = "THWC", + ) -> None: + super().__init__(root) + if not 1 <= fold <= 3: + raise ValueError(f"fold should be between 1 and 3, got {fold}") + + extensions = ("avi",) + self.fold = fold + self.train = train + + self.classes, class_to_idx = find_classes(self.root) + self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) + video_list = [x[0] for x in self.samples] + video_clips = VideoClips( + video_list, + frames_per_clip, + step_between_clips, + frame_rate, + _precomputed_metadata, + num_workers=num_workers, + _video_width=_video_width, + _video_height=_video_height, + _video_min_dimension=_video_min_dimension, + _audio_samples=_audio_samples, + output_format=output_format, + ) + # we bookkeep the full version of video clips because we want to be able + # to return the metadata of full version rather than the subset version of + # video clips + self.full_video_clips = video_clips + self.indices = self._select_fold(video_list, annotation_path, fold, train) + self.video_clips = video_clips.subset(self.indices) + self.transform = transform + + @property + def metadata(self) -> dict[str, Any]: + return self.full_video_clips.metadata + + def _select_fold(self, video_list: list[str], annotation_path: str, fold: int, train: bool) -> list[int]: + name = "train" if train else "test" + name = f"{name}list{fold:02d}.txt" + f = os.path.join(annotation_path, name) + selected_files = set() + with open(f) as fid: + data = fid.readlines() + data = [x.strip().split(" ")[0] for x in data] + data = [os.path.join(self.root, *x.split("/")) for x in data] + selected_files.update(data) + indices = [i for i in range(len(video_list)) if video_list[i] in selected_files] + return indices + + def __len__(self) -> int: + return self.video_clips.num_clips() + + def __getitem__(self, idx: int) -> tuple[Tensor, Tensor, int]: + video, audio, info, video_idx = self.video_clips.get_clip(idx) + label = self.samples[self.indices[video_idx]][1] + + if self.transform is not None: + video = self.transform(video) + + return video, audio, label diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/usps.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/usps.py new file mode 100644 index 0000000000000000000000000000000000000000..e09ac96e45eefd8ae2458a196baa4f07630d3d43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/usps.py @@ -0,0 +1,96 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np + +from ..utils import _Image_fromarray +from .utils import download_url +from .vision import VisionDataset + + +class USPS(VisionDataset): + """`USPS `_ Dataset. + The data-format is : [label [index:value ]*256 \\n] * num_lines, where ``label`` lies in ``[1, 10]``. + The value for each pixel lies in ``[-1, 1]``. Here we transform the ``label`` into ``[0, 9]`` + and make pixel values in ``[0, 255]``. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset to store``USPS`` data files. + train (bool, optional): If True, creates dataset from ``usps.bz2``, + otherwise from ``usps.t.bz2``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + split_list = { + "train": [ + "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/usps.bz2", + "usps.bz2", + "ec16c51db3855ca6c91edd34d0e9b197", + ], + "test": [ + "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/usps.t.bz2", + "usps.t.bz2", + "8ea070ee2aca1ac39742fdd1ef5ed118", + ], + } + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + split = "train" if train else "test" + url, filename, checksum = self.split_list[split] + full_path = os.path.join(self.root, filename) + + if download and not os.path.exists(full_path): + download_url(url, self.root, filename, md5=checksum) + + import bz2 + + with bz2.open(full_path) as fp: + raw_data = [line.decode().split() for line in fp.readlines()] + tmp_list = [[x.split(":")[-1] for x in data[1:]] for data in raw_data] + imgs = np.asarray(tmp_list, dtype=np.float32).reshape((-1, 16, 16)) + imgs = ((imgs + 1) / 2 * 255).astype(dtype=np.uint8) + targets = [int(d[0]) - 1 for d in raw_data] + + self.data = imgs + self.targets = targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.targets[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = _Image_fromarray(img, mode="L") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b6670800d2b012829bdf06b887f82ff3f554108 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/utils.py @@ -0,0 +1,468 @@ +import bz2 +import gzip +import hashlib +import lzma +import os +import os.path +import pathlib +import re +import tarfile +import urllib +import urllib.error +import urllib.request +import zipfile +from collections.abc import Iterable +from typing import Any, Callable, IO, Optional, TypeVar, Union +from urllib.parse import urlparse + +import numpy as np +import torch +from torch.utils.model_zoo import tqdm + +from .._internally_replaced_utils import _download_file_from_remote_location, _is_remote_location_available + +USER_AGENT = "pytorch/vision" + + +def _urlretrieve(url: str, filename: Union[str, pathlib.Path], chunk_size: int = 1024 * 32) -> None: + with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": USER_AGENT})) as response: + with open(filename, "wb") as fh, tqdm(total=response.length, unit="B", unit_scale=True) as pbar: + while chunk := response.read(chunk_size): + fh.write(chunk) + pbar.update(len(chunk)) + + +def calculate_md5(fpath: Union[str, pathlib.Path], chunk_size: int = 1024 * 1024) -> str: + # Setting the `usedforsecurity` flag does not change anything about the functionality, but indicates that we are + # not using the MD5 checksum for cryptography. This enables its usage in restricted environments like FIPS. Without + # it torchvision.datasets is unusable in these environments since we perform a MD5 check everywhere. + md5 = hashlib.md5(usedforsecurity=False) + with open(fpath, "rb") as f: + while chunk := f.read(chunk_size): + md5.update(chunk) + return md5.hexdigest() + + +def check_md5(fpath: Union[str, pathlib.Path], md5: str, **kwargs: Any) -> bool: + return md5 == calculate_md5(fpath, **kwargs) + + +def check_integrity(fpath: Union[str, pathlib.Path], md5: Optional[str] = None) -> bool: + if not os.path.isfile(fpath): + return False + if md5 is None: + return True + return check_md5(fpath, md5) + + +def _get_redirect_url(url: str, max_hops: int = 3) -> str: + initial_url = url + headers = {"Method": "HEAD", "User-Agent": USER_AGENT} + + for _ in range(max_hops + 1): + with urllib.request.urlopen(urllib.request.Request(url, headers=headers)) as response: + if response.url == url or response.url is None: + return url + + url = response.url + else: + raise RecursionError( + f"Request to {initial_url} exceeded {max_hops} redirects. The last redirect points to {url}." + ) + + +def _get_google_drive_file_id(url: str) -> Optional[str]: + parts = urlparse(url) + + if re.match(r"(drive|docs)[.]google[.]com", parts.netloc) is None: + return None + + match = re.match(r"/file/d/(?P[^/]*)", parts.path) + if match is None: + return None + + return match.group("id") + + +def download_url( + url: str, + root: Union[str, pathlib.Path], + filename: Optional[Union[str, pathlib.Path]] = None, + md5: Optional[str] = None, + max_redirect_hops: int = 3, +) -> None: + """Download a file from a url and place it in root. + + Args: + url (str): URL to download file from + root (str): Directory to place downloaded file in + filename (str, optional): Name to save the file under. If None, use the basename of the URL + md5 (str, optional): MD5 checksum of the download. If None, do not check + max_redirect_hops (int, optional): Maximum number of redirect hops allowed + """ + root = os.path.expanduser(root) + if not filename: + filename = os.path.basename(url) + fpath = os.fspath(os.path.join(root, filename)) + + os.makedirs(root, exist_ok=True) + + # check if file is already present locally + if check_integrity(fpath, md5): + return + + if _is_remote_location_available(): + _download_file_from_remote_location(fpath, url) + else: + # expand redirect chain if needed + url = _get_redirect_url(url, max_hops=max_redirect_hops) + + # check if file is located on Google Drive + file_id = _get_google_drive_file_id(url) + if file_id is not None: + return download_file_from_google_drive(file_id, root, filename, md5) + + # download the file + try: + _urlretrieve(url, fpath) + except (urllib.error.URLError, OSError) as e: # type: ignore[attr-defined] + if url[:5] == "https": + url = url.replace("https:", "http:") + _urlretrieve(url, fpath) + else: + raise e + + # check integrity of downloaded file + if not check_integrity(fpath, md5): + raise RuntimeError("File not found or corrupted.") + + +def list_dir(root: Union[str, pathlib.Path], prefix: bool = False) -> list[str]: + """List all directories at a given root + + Args: + root (str): Path to directory whose folders need to be listed + prefix (bool, optional): If true, prepends the path to each result, otherwise + only returns the name of the directories found + """ + root = os.path.expanduser(root) + directories = [p for p in os.listdir(root) if os.path.isdir(os.path.join(root, p))] + if prefix is True: + directories = [os.path.join(root, d) for d in directories] + return directories + + +def list_files(root: Union[str, pathlib.Path], suffix: str, prefix: bool = False) -> list[str]: + """List all files ending with a suffix at a given root + + Args: + root (str): Path to directory whose folders need to be listed + suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png'). + It uses the Python "str.endswith" method and is passed directly + prefix (bool, optional): If true, prepends the path to each result, otherwise + only returns the name of the files found + """ + root = os.path.expanduser(root) + files = [p for p in os.listdir(root) if os.path.isfile(os.path.join(root, p)) and p.endswith(suffix)] + if prefix is True: + files = [os.path.join(root, d) for d in files] + return files + + +def download_file_from_google_drive( + file_id: str, + root: Union[str, pathlib.Path], + filename: Optional[Union[str, pathlib.Path]] = None, + md5: Optional[str] = None, +): + """Download a Google Drive file from and place it in root. + + Args: + file_id (str): id of file to be downloaded + root (str): Directory to place downloaded file in + filename (str, optional): Name to save the file under. If None, use the id of the file. + md5 (str, optional): MD5 checksum of the download. If None, do not check + """ + try: + import gdown + except ModuleNotFoundError: + raise RuntimeError( + "To download files from GDrive, 'gdown' is required. You can install it with 'pip install gdown'." + ) + + root = os.path.expanduser(root) + if not filename: + filename = file_id + fpath = os.fspath(os.path.join(root, filename)) + + os.makedirs(root, exist_ok=True) + + if check_integrity(fpath, md5): + return + + gdown.download(id=file_id, output=fpath, quiet=False, user_agent=USER_AGENT) + + if not check_integrity(fpath, md5): + raise RuntimeError("File not found or corrupted.") + + +def _extract_tar( + from_path: Union[str, pathlib.Path], to_path: Union[str, pathlib.Path], compression: Optional[str] +) -> None: + with tarfile.open(from_path, f"r:{compression[1:]}" if compression else "r") as tar: + tar.extractall(to_path) + + +_ZIP_COMPRESSION_MAP: dict[str, int] = { + ".bz2": zipfile.ZIP_BZIP2, + ".xz": zipfile.ZIP_LZMA, +} + + +def _extract_zip( + from_path: Union[str, pathlib.Path], to_path: Union[str, pathlib.Path], compression: Optional[str] +) -> None: + with zipfile.ZipFile( + from_path, "r", compression=_ZIP_COMPRESSION_MAP[compression] if compression else zipfile.ZIP_STORED + ) as zip: + zip.extractall(to_path) + + +_ARCHIVE_EXTRACTORS: dict[str, Callable[[Union[str, pathlib.Path], Union[str, pathlib.Path], Optional[str]], None]] = { + ".tar": _extract_tar, + ".zip": _extract_zip, +} +_COMPRESSED_FILE_OPENERS: dict[str, Callable[..., IO]] = { + ".bz2": bz2.open, + ".gz": gzip.open, + ".xz": lzma.open, +} +_FILE_TYPE_ALIASES: dict[str, tuple[Optional[str], Optional[str]]] = { + ".tbz": (".tar", ".bz2"), + ".tbz2": (".tar", ".bz2"), + ".tgz": (".tar", ".gz"), +} + + +def _detect_file_type(file: Union[str, pathlib.Path]) -> tuple[str, Optional[str], Optional[str]]: + """Detect the archive type and/or compression of a file. + + Args: + file (str): the filename + + Returns: + (tuple): tuple of suffix, archive type, and compression + + Raises: + RuntimeError: if file has no suffix or suffix is not supported + """ + suffixes = pathlib.Path(file).suffixes + if not suffixes: + raise RuntimeError( + f"File '{file}' has no suffixes that could be used to detect the archive type and compression." + ) + suffix = suffixes[-1] + + # check if the suffix is a known alias + if suffix in _FILE_TYPE_ALIASES: + return (suffix, *_FILE_TYPE_ALIASES[suffix]) + + # check if the suffix is an archive type + if suffix in _ARCHIVE_EXTRACTORS: + return suffix, suffix, None + + # check if the suffix is a compression + if suffix in _COMPRESSED_FILE_OPENERS: + # check for suffix hierarchy + if len(suffixes) > 1: + suffix2 = suffixes[-2] + + # check if the suffix2 is an archive type + if suffix2 in _ARCHIVE_EXTRACTORS: + return suffix2 + suffix, suffix2, suffix + + return suffix, None, suffix + + valid_suffixes = sorted(set(_FILE_TYPE_ALIASES) | set(_ARCHIVE_EXTRACTORS) | set(_COMPRESSED_FILE_OPENERS)) + raise RuntimeError(f"Unknown compression or archive type: '{suffix}'.\nKnown suffixes are: '{valid_suffixes}'.") + + +def _decompress( + from_path: Union[str, pathlib.Path], + to_path: Optional[Union[str, pathlib.Path]] = None, + remove_finished: bool = False, +) -> pathlib.Path: + r"""Decompress a file. + + The compression is automatically detected from the file name. + + Args: + from_path (str): Path to the file to be decompressed. + to_path (str): Path to the decompressed file. If omitted, ``from_path`` without compression extension is used. + remove_finished (bool): If ``True``, remove the file after the extraction. + + Returns: + (str): Path to the decompressed file. + """ + suffix, archive_type, compression = _detect_file_type(from_path) + if not compression: + raise RuntimeError(f"Couldn't detect a compression from suffix {suffix}.") + + if to_path is None: + to_path = pathlib.Path(os.fspath(from_path).replace(suffix, archive_type if archive_type is not None else "")) + + # We don't need to check for a missing key here, since this was already done in _detect_file_type() + compressed_file_opener = _COMPRESSED_FILE_OPENERS[compression] + + with compressed_file_opener(from_path, "rb") as rfh, open(to_path, "wb") as wfh: + wfh.write(rfh.read()) + + if remove_finished: + os.remove(from_path) + + return pathlib.Path(to_path) + + +def extract_archive( + from_path: Union[str, pathlib.Path], + to_path: Optional[Union[str, pathlib.Path]] = None, + remove_finished: bool = False, +) -> Union[str, pathlib.Path]: + """Extract an archive. + + The archive type and a possible compression is automatically detected from the file name. If the file is compressed + but not an archive the call is dispatched to :func:`decompress`. + + Args: + from_path (str): Path to the file to be extracted. + to_path (str): Path to the directory the file will be extracted to. If omitted, the directory of the file is + used. + remove_finished (bool): If ``True``, remove the file after the extraction. + + Returns: + (str): Path to the directory the file was extracted to. + """ + + def path_or_str(ret_path: pathlib.Path) -> Union[str, pathlib.Path]: + if isinstance(from_path, str): + return os.fspath(ret_path) + else: + return ret_path + + if to_path is None: + to_path = os.path.dirname(from_path) + + suffix, archive_type, compression = _detect_file_type(from_path) + if not archive_type: + ret_path = _decompress( + from_path, + os.path.join(to_path, os.path.basename(from_path).replace(suffix, "")), + remove_finished=remove_finished, + ) + return path_or_str(ret_path) + + # We don't need to check for a missing key here, since this was already done in _detect_file_type() + extractor = _ARCHIVE_EXTRACTORS[archive_type] + + extractor(from_path, to_path, compression) + if remove_finished: + os.remove(from_path) + + return path_or_str(pathlib.Path(to_path)) + + +def download_and_extract_archive( + url: str, + download_root: Union[str, pathlib.Path], + extract_root: Optional[Union[str, pathlib.Path]] = None, + filename: Optional[Union[str, pathlib.Path]] = None, + md5: Optional[str] = None, + remove_finished: bool = False, +) -> None: + download_root = os.path.expanduser(download_root) + if extract_root is None: + extract_root = download_root + if not filename: + filename = os.path.basename(url) + + download_url(url, download_root, filename, md5) + + archive = os.path.join(download_root, filename) + extract_archive(archive, extract_root, remove_finished) + + +def iterable_to_str(iterable: Iterable) -> str: + return "'" + "', '".join([str(item) for item in iterable]) + "'" + + +T = TypeVar("T", str, bytes) + + +def verify_str_arg( + value: T, + arg: Optional[str] = None, + valid_values: Optional[Iterable[T]] = None, + custom_msg: Optional[str] = None, +) -> T: + if not isinstance(value, str): + if arg is None: + msg = "Expected type str, but got type {type}." + else: + msg = "Expected type str for argument {arg}, but got type {type}." + msg = msg.format(type=type(value), arg=arg) + raise ValueError(msg) + + if valid_values is None: + return value + + if value not in valid_values: + if custom_msg is not None: + msg = custom_msg + else: + msg = "Unknown value '{value}' for argument {arg}. Valid values are {{{valid_values}}}." + msg = msg.format(value=value, arg=arg, valid_values=iterable_to_str(valid_values)) + raise ValueError(msg) + + return value + + +def _read_pfm(file_name: Union[str, pathlib.Path], slice_channels: int = 2) -> np.ndarray: + """Read file in .pfm format. Might contain either 1 or 3 channels of data. + + Args: + file_name (str): Path to the file. + slice_channels (int): Number of channels to slice out of the file. + Useful for reading different data formats stored in .pfm files: Optical Flows, Stereo Disparity Maps, etc. + """ + + with open(file_name, "rb") as f: + header = f.readline().rstrip() + if header not in [b"PF", b"Pf"]: + raise ValueError("Invalid PFM file") + + dim_match = re.match(rb"^(\d+)\s(\d+)\s$", f.readline()) + if not dim_match: + raise Exception("Malformed PFM header.") + w, h = (int(dim) for dim in dim_match.groups()) + + scale = float(f.readline().rstrip()) + if scale < 0: # little-endian + endian = "<" + scale = -scale + else: + endian = ">" # big-endian + + data = np.fromfile(f, dtype=endian + "f") + + pfm_channels = 3 if header == b"PF" else 1 + + data = data.reshape(h, w, pfm_channels).transpose(2, 0, 1) + data = np.flip(data, axis=1) # flip on h dimension + data = data[:slice_channels, :, :] + return data.astype(np.float32) + + +def _flip_byte_order(t: torch.Tensor) -> torch.Tensor: + return ( + t.contiguous().view(torch.uint8).view(*t.shape, t.element_size()).flip(-1).view(*t.shape[:-1], -1).view(t.dtype) + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/video_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/video_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d9214beaa680057ae10a414244b6c88310be8513 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/video_utils.py @@ -0,0 +1,419 @@ +import bisect +import math +import warnings +from fractions import Fraction +from typing import Any, Callable, cast, Optional, TypeVar, Union + +import torch +from torchvision.io import _probe_video_from_file, _read_video_from_file, read_video, read_video_timestamps + +from .utils import tqdm + +T = TypeVar("T") + + +def pts_convert(pts: int, timebase_from: Fraction, timebase_to: Fraction, round_func: Callable = math.floor) -> int: + """convert pts between different time bases + Args: + pts: presentation timestamp, float + timebase_from: original timebase. Fraction + timebase_to: new timebase. Fraction + round_func: rounding function. + """ + new_pts = Fraction(pts, 1) * timebase_from / timebase_to + return round_func(new_pts) + + +def unfold(tensor: torch.Tensor, size: int, step: int, dilation: int = 1) -> torch.Tensor: + """ + similar to tensor.unfold, but with the dilation + and specialized for 1d tensors + + Returns all consecutive windows of `size` elements, with + `step` between windows. The distance between each element + in a window is given by `dilation`. + """ + if tensor.dim() != 1: + raise ValueError(f"tensor should have 1 dimension instead of {tensor.dim()}") + o_stride = tensor.stride(0) + numel = tensor.numel() + new_stride = (step * o_stride, dilation * o_stride) + new_size = ((numel - (dilation * (size - 1) + 1)) // step + 1, size) + if new_size[0] < 1: + new_size = (0, size) + return torch.as_strided(tensor, new_size, new_stride) + + +class _VideoTimestampsDataset: + """ + Dataset used to parallelize the reading of the timestamps + of a list of videos, given their paths in the filesystem. + + Used in VideoClips and defined at top level, so it can be + pickled when forking. + """ + + def __init__(self, video_paths: list[str]) -> None: + self.video_paths = video_paths + + def __len__(self) -> int: + return len(self.video_paths) + + def __getitem__(self, idx: int) -> tuple[list[int], Optional[float]]: + return read_video_timestamps(self.video_paths[idx]) + + +def _collate_fn(x: T) -> T: + """ + Dummy collate function to be used with _VideoTimestampsDataset + """ + return x + + +class VideoClips: + """ + Given a list of video files, computes all consecutive subvideos of size + `clip_length_in_frames`, where the distance between each subvideo in the + same video is defined by `frames_between_clips`. + If `frame_rate` is specified, it will also resample all the videos to have + the same frame rate, and the clips will refer to this frame rate. + + Creating this instance the first time is time-consuming, as it needs to + decode all the videos in `video_paths`. It is recommended that you + cache the results after instantiation of the class. + + Recreating the clips for different clip lengths is fast, and can be done + with the `compute_clips` method. + + Args: + video_paths (List[str]): paths to the video files + clip_length_in_frames (int): size of a clip in number of frames + frames_between_clips (int): step (in frames) between each clip + frame_rate (float, optional): if specified, it will resample the video + so that it has `frame_rate`, and then the clips will be defined + on the resampled video + num_workers (int): how many subprocesses to use for data loading. + 0 means that the data will be loaded in the main process. (default: 0) + output_format (str): The format of the output video tensors. Can be either "THWC" (default) or "TCHW". + """ + + def __init__( + self, + video_paths: list[str], + clip_length_in_frames: int = 16, + frames_between_clips: int = 1, + frame_rate: Optional[float] = None, + _precomputed_metadata: Optional[dict[str, Any]] = None, + num_workers: int = 0, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _video_max_dimension: int = 0, + _audio_samples: int = 0, + _audio_channels: int = 0, + output_format: str = "THWC", + ) -> None: + + self.video_paths = video_paths + self.num_workers = num_workers + + # these options are not valid for pyav backend + self._video_width = _video_width + self._video_height = _video_height + self._video_min_dimension = _video_min_dimension + self._video_max_dimension = _video_max_dimension + self._audio_samples = _audio_samples + self._audio_channels = _audio_channels + self.output_format = output_format.upper() + if self.output_format not in ("THWC", "TCHW"): + raise ValueError(f"output_format should be either 'THWC' or 'TCHW', got {output_format}.") + + if _precomputed_metadata is None: + self._compute_frame_pts() + else: + self._init_from_metadata(_precomputed_metadata) + self.compute_clips(clip_length_in_frames, frames_between_clips, frame_rate) + + def _compute_frame_pts(self) -> None: + self.video_pts = [] # len = num_videos. Each entry is a tensor of shape (num_frames_in_video,) + self.video_fps: list[float] = [] # len = num_videos + + # strategy: use a DataLoader to parallelize read_video_timestamps + # so need to create a dummy dataset first + import torch.utils.data + + dl: torch.utils.data.DataLoader = torch.utils.data.DataLoader( + _VideoTimestampsDataset(self.video_paths), # type: ignore[arg-type] + batch_size=16, + num_workers=self.num_workers, + collate_fn=_collate_fn, + ) + + with tqdm(total=len(dl)) as pbar: + for batch in dl: + pbar.update(1) + batch_pts, batch_fps = list(zip(*batch)) + # we need to specify dtype=torch.long because for empty list, + # torch.as_tensor will use torch.float as default dtype. This + # happens when decoding fails and no pts is returned in the list. + batch_pts = [torch.as_tensor(pts, dtype=torch.long) for pts in batch_pts] + self.video_pts.extend(batch_pts) + self.video_fps.extend(batch_fps) + + def _init_from_metadata(self, metadata: dict[str, Any]) -> None: + self.video_paths = metadata["video_paths"] + assert len(self.video_paths) == len(metadata["video_pts"]) + self.video_pts = metadata["video_pts"] + assert len(self.video_paths) == len(metadata["video_fps"]) + self.video_fps = metadata["video_fps"] + + @property + def metadata(self) -> dict[str, Any]: + _metadata = { + "video_paths": self.video_paths, + "video_pts": self.video_pts, + "video_fps": self.video_fps, + } + return _metadata + + def subset(self, indices: list[int]) -> "VideoClips": + video_paths = [self.video_paths[i] for i in indices] + video_pts = [self.video_pts[i] for i in indices] + video_fps = [self.video_fps[i] for i in indices] + metadata = { + "video_paths": video_paths, + "video_pts": video_pts, + "video_fps": video_fps, + } + return type(self)( + video_paths, + clip_length_in_frames=self.num_frames, + frames_between_clips=self.step, + frame_rate=self.frame_rate, + _precomputed_metadata=metadata, + num_workers=self.num_workers, + _video_width=self._video_width, + _video_height=self._video_height, + _video_min_dimension=self._video_min_dimension, + _video_max_dimension=self._video_max_dimension, + _audio_samples=self._audio_samples, + _audio_channels=self._audio_channels, + output_format=self.output_format, + ) + + @staticmethod + def compute_clips_for_video( + video_pts: torch.Tensor, num_frames: int, step: int, fps: Optional[float], frame_rate: Optional[float] = None + ) -> tuple[torch.Tensor, Union[list[slice], torch.Tensor]]: + if fps is None: + # if for some reason the video doesn't have fps (because doesn't have a video stream) + # set the fps to 1. The value doesn't matter, because video_pts is empty anyway + fps = 1 + if frame_rate is None: + frame_rate = fps + total_frames = len(video_pts) * frame_rate / fps + _idxs = VideoClips._resample_video_idx(int(math.floor(total_frames)), fps, frame_rate) + video_pts = video_pts[_idxs] + clips = unfold(video_pts, num_frames, step) + if not clips.numel(): + warnings.warn( + "There aren't enough frames in the current video to get a clip for the given clip length and " + "frames between clips. The video (and potentially others) will be skipped." + ) + idxs: Union[list[slice], torch.Tensor] + if isinstance(_idxs, slice): + idxs = [_idxs] * len(clips) + else: + idxs = unfold(_idxs, num_frames, step) + return clips, idxs + + def compute_clips(self, num_frames: int, step: int, frame_rate: Optional[float] = None) -> None: + """ + Compute all consecutive sequences of clips from video_pts. + Always returns clips of size `num_frames`, meaning that the + last few frames in a video can potentially be dropped. + + Args: + num_frames (int): number of frames for the clip + step (int): distance between two clips + frame_rate (int, optional): The frame rate + """ + self.num_frames = num_frames + self.step = step + self.frame_rate = frame_rate + self.clips = [] + self.resampling_idxs = [] + for video_pts, fps in zip(self.video_pts, self.video_fps): + clips, idxs = self.compute_clips_for_video(video_pts, num_frames, step, fps, frame_rate) + self.clips.append(clips) + self.resampling_idxs.append(idxs) + clip_lengths = torch.as_tensor([len(v) for v in self.clips]) + self.cumulative_sizes = clip_lengths.cumsum(0).tolist() + + def __len__(self) -> int: + return self.num_clips() + + def num_videos(self) -> int: + return len(self.video_paths) + + def num_clips(self) -> int: + """ + Number of subclips that are available in the video list. + """ + return self.cumulative_sizes[-1] + + def get_clip_location(self, idx: int) -> tuple[int, int]: + """ + Converts a flattened representation of the indices into a video_idx, clip_idx + representation. + """ + video_idx = bisect.bisect_right(self.cumulative_sizes, idx) + if video_idx == 0: + clip_idx = idx + else: + clip_idx = idx - self.cumulative_sizes[video_idx - 1] + return video_idx, clip_idx + + @staticmethod + def _resample_video_idx(num_frames: int, original_fps: float, new_fps: float) -> Union[slice, torch.Tensor]: + step = original_fps / new_fps + if step.is_integer(): + # optimization: if step is integer, don't need to perform + # advanced indexing + step = int(step) + return slice(None, None, step) + idxs = torch.arange(num_frames, dtype=torch.float32) * step + idxs = idxs.floor().to(torch.int64) + return idxs + + def get_clip(self, idx: int) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any], int]: + """ + Gets a subclip from a list of videos. + + Args: + idx (int): index of the subclip. Must be between 0 and num_clips(). + + Returns: + video (Tensor) + audio (Tensor) + info (Dict) + video_idx (int): index of the video in `video_paths` + """ + if idx >= self.num_clips(): + raise IndexError(f"Index {idx} out of range ({self.num_clips()} number of clips)") + video_idx, clip_idx = self.get_clip_location(idx) + video_path = self.video_paths[video_idx] + clip_pts = self.clips[video_idx][clip_idx] + + from torchvision import get_video_backend + + backend = get_video_backend() + + if backend == "pyav": + # check for invalid options + if self._video_width != 0: + raise ValueError("pyav backend doesn't support _video_width != 0") + if self._video_height != 0: + raise ValueError("pyav backend doesn't support _video_height != 0") + if self._video_min_dimension != 0: + raise ValueError("pyav backend doesn't support _video_min_dimension != 0") + if self._video_max_dimension != 0: + raise ValueError("pyav backend doesn't support _video_max_dimension != 0") + if self._audio_samples != 0: + raise ValueError("pyav backend doesn't support _audio_samples != 0") + + if backend == "pyav": + start_pts = clip_pts[0].item() + end_pts = clip_pts[-1].item() + video, audio, info = read_video(video_path, start_pts, end_pts) + else: + _info = _probe_video_from_file(video_path) + video_fps = _info.video_fps + audio_fps = None + + video_start_pts = cast(int, clip_pts[0].item()) + video_end_pts = cast(int, clip_pts[-1].item()) + + audio_start_pts, audio_end_pts = 0, -1 + audio_timebase = Fraction(0, 1) + video_timebase = Fraction(_info.video_timebase.numerator, _info.video_timebase.denominator) + if _info.has_audio: + audio_timebase = Fraction(_info.audio_timebase.numerator, _info.audio_timebase.denominator) + audio_start_pts = pts_convert(video_start_pts, video_timebase, audio_timebase, math.floor) + audio_end_pts = pts_convert(video_end_pts, video_timebase, audio_timebase, math.ceil) + audio_fps = _info.audio_sample_rate + video, audio, _ = _read_video_from_file( + video_path, + video_width=self._video_width, + video_height=self._video_height, + video_min_dimension=self._video_min_dimension, + video_max_dimension=self._video_max_dimension, + video_pts_range=(video_start_pts, video_end_pts), + video_timebase=video_timebase, + audio_samples=self._audio_samples, + audio_channels=self._audio_channels, + audio_pts_range=(audio_start_pts, audio_end_pts), + audio_timebase=audio_timebase, + ) + + info = {"video_fps": video_fps} + if audio_fps is not None: + info["audio_fps"] = audio_fps + + if self.frame_rate is not None: + resampling_idx = self.resampling_idxs[video_idx][clip_idx] + if isinstance(resampling_idx, torch.Tensor): + resampling_idx = resampling_idx - resampling_idx[0] + video = video[resampling_idx] + info["video_fps"] = self.frame_rate + assert len(video) == self.num_frames, f"{video.shape} x {self.num_frames}" + + if self.output_format == "TCHW": + # [T,H,W,C] --> [T,C,H,W] + video = video.permute(0, 3, 1, 2) + + return video, audio, info, video_idx + + def __getstate__(self) -> dict[str, Any]: + video_pts_sizes = [len(v) for v in self.video_pts] + # To be back-compatible, we convert data to dtype torch.long as needed + # because for empty list, in legacy implementation, torch.as_tensor will + # use torch.float as default dtype. This happens when decoding fails and + # no pts is returned in the list. + video_pts = [x.to(torch.int64) for x in self.video_pts] + # video_pts can be an empty list if no frames have been decoded + if video_pts: + video_pts = torch.cat(video_pts) # type: ignore[assignment] + # avoid bug in https://github.com/pytorch/pytorch/issues/32351 + # TODO: Revert it once the bug is fixed. + video_pts = video_pts.numpy() # type: ignore[attr-defined] + + # make a copy of the fields of self + d = self.__dict__.copy() + d["video_pts_sizes"] = video_pts_sizes + d["video_pts"] = video_pts + # delete the following attributes to reduce the size of dictionary. They + # will be re-computed in "__setstate__()" + del d["clips"] + del d["resampling_idxs"] + del d["cumulative_sizes"] + + # for backwards-compatibility + d["_version"] = 2 + return d + + def __setstate__(self, d: dict[str, Any]) -> None: + # for backwards-compatibility + if "_version" not in d: + self.__dict__ = d + return + + video_pts = torch.as_tensor(d["video_pts"], dtype=torch.int64) + video_pts = torch.split(video_pts, d["video_pts_sizes"], dim=0) + # don't need this info anymore + del d["video_pts_sizes"] + + d["video_pts"] = video_pts + self.__dict__ = d + # recompute attributes "clips", "resampling_idxs" and other derivative ones + self.compute_clips(self.num_frames, self.step, self.frame_rate) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/vision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..c43f7814c6c4462489b18348dd95078eb0e05c0a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/vision.py @@ -0,0 +1,111 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import torch.utils.data as data + +from ..utils import _log_api_usage_once + + +class VisionDataset(data.Dataset): + """ + Base Class For making datasets which are compatible with torchvision. + It is necessary to override the ``__getitem__`` and ``__len__`` method. + + Args: + root (string, optional): Root directory of dataset. Only used for `__repr__`. + transforms (callable, optional): A function/transforms that takes in + an image and a label and returns the transformed versions of both. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + + .. note:: + + :attr:`transforms` and the combination of :attr:`transform` and :attr:`target_transform` are mutually exclusive. + """ + + _repr_indent = 4 + + def __init__( + self, + root: Union[str, Path] = None, # type: ignore[assignment] + transforms: Optional[Callable] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + _log_api_usage_once(self) + if isinstance(root, str): + root = os.path.expanduser(root) + self.root = root + + has_transforms = transforms is not None + has_separate_transform = transform is not None or target_transform is not None + if has_transforms and has_separate_transform: + raise ValueError("Only transforms or transform/target_transform can be passed as argument") + + # for backwards-compatibility + self.transform = transform + self.target_transform = target_transform + + if has_separate_transform: + transforms = StandardTransform(transform, target_transform) + self.transforms = transforms + + def __getitem__(self, index: int) -> Any: + """ + Args: + index (int): Index + + Returns: + (Any): Sample and meta data, optionally transformed by the respective transforms. + """ + raise NotImplementedError + + def __len__(self) -> int: + raise NotImplementedError + + def __repr__(self) -> str: + head = "Dataset " + self.__class__.__name__ + body = [f"Number of datapoints: {self.__len__()}"] + if self.root is not None: + body.append(f"Root location: {self.root}") + body += self.extra_repr().splitlines() + if hasattr(self, "transforms") and self.transforms is not None: + body += [repr(self.transforms)] + lines = [head] + [" " * self._repr_indent + line for line in body] + return "\n".join(lines) + + def _format_transform_repr(self, transform: Callable, head: str) -> list[str]: + lines = transform.__repr__().splitlines() + return [f"{head}{lines[0]}"] + ["{}{}".format(" " * len(head), line) for line in lines[1:]] + + def extra_repr(self) -> str: + return "" + + +class StandardTransform: + def __init__(self, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None) -> None: + self.transform = transform + self.target_transform = target_transform + + def __call__(self, input: Any, target: Any) -> tuple[Any, Any]: + if self.transform is not None: + input = self.transform(input) + if self.target_transform is not None: + target = self.target_transform(target) + return input, target + + def _format_transform_repr(self, transform: Callable, head: str) -> list[str]: + lines = transform.__repr__().splitlines() + return [f"{head}{lines[0]}"] + ["{}{}".format(" " * len(head), line) for line in lines[1:]] + + def __repr__(self) -> str: + body = [self.__class__.__name__] + if self.transform is not None: + body += self._format_transform_repr(self.transform, "Transform: ") + if self.target_transform is not None: + body += self._format_transform_repr(self.target_transform, "Target transform: ") + + return "\n".join(body) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/voc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/voc.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3e502d84e4153bc57a7f2a431a20ecd35348e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/voc.py @@ -0,0 +1,224 @@ +import collections +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union +from xml.etree.ElementTree import Element as ET_Element + +try: + from defusedxml.ElementTree import parse as ET_parse +except ImportError: + from xml.etree.ElementTree import parse as ET_parse + +from PIL import Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + +DATASET_YEAR_DICT = { + "2012": { + "url": "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar", + "filename": "VOCtrainval_11-May-2012.tar", + "md5": "6cd6e144f989b92b3379bac3b3de84fd", + "base_dir": os.path.join("VOCdevkit", "VOC2012"), + }, + "2011": { + "url": "http://host.robots.ox.ac.uk/pascal/VOC/voc2011/VOCtrainval_25-May-2011.tar", + "filename": "VOCtrainval_25-May-2011.tar", + "md5": "6c3384ef61512963050cb5d687e5bf1e", + "base_dir": os.path.join("TrainVal", "VOCdevkit", "VOC2011"), + }, + "2010": { + "url": "http://host.robots.ox.ac.uk/pascal/VOC/voc2010/VOCtrainval_03-May-2010.tar", + "filename": "VOCtrainval_03-May-2010.tar", + "md5": "da459979d0c395079b5c75ee67908abb", + "base_dir": os.path.join("VOCdevkit", "VOC2010"), + }, + "2009": { + "url": "http://host.robots.ox.ac.uk/pascal/VOC/voc2009/VOCtrainval_11-May-2009.tar", + "filename": "VOCtrainval_11-May-2009.tar", + "md5": "a3e00b113cfcfebf17e343f59da3caa1", + "base_dir": os.path.join("VOCdevkit", "VOC2009"), + }, + "2008": { + "url": "http://host.robots.ox.ac.uk/pascal/VOC/voc2008/VOCtrainval_14-Jul-2008.tar", + "filename": "VOCtrainval_11-May-2012.tar", + "md5": "2629fa636546599198acfcfbfcf1904a", + "base_dir": os.path.join("VOCdevkit", "VOC2008"), + }, + "2007": { + "url": "http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar", + "filename": "VOCtrainval_06-Nov-2007.tar", + "md5": "c52e279531787c972589f7e41ab4ae64", + "base_dir": os.path.join("VOCdevkit", "VOC2007"), + }, + "2007-test": { + "url": "http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar", + "filename": "VOCtest_06-Nov-2007.tar", + "md5": "b6e924de25625d8de591ea690078ad9f", + "base_dir": os.path.join("VOCdevkit", "VOC2007"), + }, +} + + +class _VOCBase(VisionDataset): + _SPLITS_DIR: str + _TARGET_DIR: str + _TARGET_FILE_EXT: str + + def __init__( + self, + root: Union[str, Path], + year: str = "2012", + image_set: str = "train", + download: bool = False, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + ): + super().__init__(root, transforms, transform, target_transform) + + self.year = verify_str_arg(year, "year", valid_values=[str(yr) for yr in range(2007, 2013)]) + + valid_image_sets = ["train", "trainval", "val"] + if year == "2007": + valid_image_sets.append("test") + self.image_set = verify_str_arg(image_set, "image_set", valid_image_sets) + + key = "2007-test" if year == "2007" and image_set == "test" else year + dataset_year_dict = DATASET_YEAR_DICT[key] + + self.url = dataset_year_dict["url"] + self.filename = dataset_year_dict["filename"] + self.md5 = dataset_year_dict["md5"] + + base_dir = dataset_year_dict["base_dir"] + voc_root = os.path.join(self.root, base_dir) + + if download: + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.md5) + + if not os.path.isdir(voc_root): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + splits_dir = os.path.join(voc_root, "ImageSets", self._SPLITS_DIR) + split_f = os.path.join(splits_dir, image_set.rstrip("\n") + ".txt") + with open(os.path.join(split_f)) as f: + file_names = [x.strip() for x in f.readlines()] + + image_dir = os.path.join(voc_root, "JPEGImages") + self.images = [os.path.join(image_dir, x + ".jpg") for x in file_names] + + target_dir = os.path.join(voc_root, self._TARGET_DIR) + self.targets = [os.path.join(target_dir, x + self._TARGET_FILE_EXT) for x in file_names] + + assert len(self.images) == len(self.targets) + + def __len__(self) -> int: + return len(self.images) + + +class VOCSegmentation(_VOCBase): + """`Pascal VOC `_ Segmentation Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the VOC Dataset. + year (string, optional): The dataset year, supports years ``"2007"`` to ``"2012"``. + image_set (string, optional): Select the image_set to use, ``"train"``, ``"trainval"`` or ``"val"``. If + ``year=="2007"``, can also be ``"test"``. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + """ + + _SPLITS_DIR = "Segmentation" + _TARGET_DIR = "SegmentationClass" + _TARGET_FILE_EXT = ".png" + + @property + def masks(self) -> list[str]: + return self.targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is the image segmentation. + """ + img = Image.open(self.images[index]).convert("RGB") + target = Image.open(self.masks[index]) + + if self.transforms is not None: + img, target = self.transforms(img, target) + + return img, target + + +class VOCDetection(_VOCBase): + """`Pascal VOC `_ Detection Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the VOC Dataset. + year (string, optional): The dataset year, supports years ``"2007"`` to ``"2012"``. + image_set (string, optional): Select the image_set to use, ``"train"``, ``"trainval"`` or ``"val"``. If + ``year=="2007"``, can also be ``"test"``. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + (default: alphabetic indexing of VOC's 20 classes). + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, required): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + """ + + _SPLITS_DIR = "Main" + _TARGET_DIR = "Annotations" + _TARGET_FILE_EXT = ".xml" + + @property + def annotations(self) -> list[str]: + return self.targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is a dictionary of the XML tree. + """ + img = Image.open(self.images[index]).convert("RGB") + target = self.parse_voc_xml(ET_parse(self.annotations[index]).getroot()) + + if self.transforms is not None: + img, target = self.transforms(img, target) + + return img, target + + @staticmethod + def parse_voc_xml(node: ET_Element) -> dict[str, Any]: + voc_dict: dict[str, Any] = {} + children = list(node) + if children: + def_dic: dict[str, Any] = collections.defaultdict(list) + for dc in map(VOCDetection.parse_voc_xml, children): + for ind, v in dc.items(): + def_dic[ind].append(v) + if node.tag == "annotation": + def_dic["object"] = [def_dic["object"]] + voc_dict = {node.tag: {ind: v[0] if len(v) == 1 else v for ind, v in def_dic.items()}} + if node.text: + text = node.text.strip() + if not children: + voc_dict[node.tag] = text + return voc_dict diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/widerface.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/widerface.py new file mode 100644 index 0000000000000000000000000000000000000000..31ab28ebdba2660ba5ec0a16b19361ad30a8a692 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/datasets/widerface.py @@ -0,0 +1,196 @@ +import os +from os.path import abspath, expanduser +from pathlib import Path + +from typing import Any, Callable, Optional, Union + +import torch +from PIL import Image + +from .utils import download_and_extract_archive, download_file_from_google_drive, extract_archive, verify_str_arg +from .vision import VisionDataset + + +class WIDERFace(VisionDataset): + """`WIDERFace `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images and annotations are downloaded to. + Expects the following folder structure if download=False: + + .. code:: + + + └── widerface + ├── wider_face_split ('wider_face_split.zip' if compressed) + ├── WIDER_train ('WIDER_train.zip' if compressed) + ├── WIDER_val ('WIDER_val.zip' if compressed) + └── WIDER_test ('WIDER_test.zip' if compressed) + split (string): The dataset split to use. One of {``train``, ``val``, ``test``}. + Defaults to ``train``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + + """ + + BASE_FOLDER = "widerface" + FILE_LIST = [ + # File ID MD5 Hash Filename + ("15hGDLhsx8bLgLcIRD5DhYt5iBxnjNF1M", "3fedf70df600953d25982bcd13d91ba2", "WIDER_train.zip"), + ("1GUCogbp16PMGa39thoMMeWxp7Rp5oM8Q", "dfa7d7e790efa35df3788964cf0bbaea", "WIDER_val.zip"), + ("1HIfDbVEWKmsYKJZm4lchTBDLW5N7dY5T", "e5d8f4248ed24c334bbd12f49c29dd40", "WIDER_test.zip"), + ] + ANNOTATIONS_FILE = ( + "http://shuoyang1213.me/WIDERFACE/support/bbx_annotation/wider_face_split.zip", + "0e3767bcf0e326556d407bf5bff5d27c", + "wider_face_split.zip", + ) + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__( + root=os.path.join(root, self.BASE_FOLDER), transform=transform, target_transform=target_transform + ) + # check arguments + self.split = verify_str_arg(split, "split", ("train", "val", "test")) + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download and prepare it") + + self.img_info: list[dict[str, Union[str, dict[str, torch.Tensor]]]] = [] + if self.split in ("train", "val"): + self.parse_train_val_annotations_file() + else: + self.parse_test_annotations_file() + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is a dict of annotations for all faces in the image. + target=None for the test split. + """ + + # stay consistent with other datasets and return a PIL Image + img = Image.open(self.img_info[index]["img_path"]) # type: ignore[arg-type] + + if self.transform is not None: + img = self.transform(img) + + target = None if self.split == "test" else self.img_info[index]["annotations"] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.img_info) + + def extra_repr(self) -> str: + lines = ["Split: {split}"] + return "\n".join(lines).format(**self.__dict__) + + def parse_train_val_annotations_file(self) -> None: + filename = "wider_face_train_bbx_gt.txt" if self.split == "train" else "wider_face_val_bbx_gt.txt" + filepath = os.path.join(self.root, "wider_face_split", filename) + + with open(filepath) as f: + lines = f.readlines() + file_name_line, num_boxes_line, box_annotation_line = True, False, False + num_boxes, box_counter = 0, 0 + labels = [] + for line in lines: + line = line.rstrip() + if file_name_line: + img_path = os.path.join(self.root, "WIDER_" + self.split, "images", line) + img_path = abspath(expanduser(img_path)) + file_name_line = False + num_boxes_line = True + elif num_boxes_line: + num_boxes = int(line) + num_boxes_line = False + box_annotation_line = True + elif box_annotation_line: + box_counter += 1 + line_split = line.split(" ") + line_values = [int(x) for x in line_split] + labels.append(line_values) + if box_counter >= num_boxes: + box_annotation_line = False + file_name_line = True + labels_tensor = torch.tensor(labels) + self.img_info.append( + { + "img_path": img_path, + "annotations": { + "bbox": labels_tensor[:, 0:4].clone(), # x, y, width, height + "blur": labels_tensor[:, 4].clone(), + "expression": labels_tensor[:, 5].clone(), + "illumination": labels_tensor[:, 6].clone(), + "occlusion": labels_tensor[:, 7].clone(), + "pose": labels_tensor[:, 8].clone(), + "invalid": labels_tensor[:, 9].clone(), + }, + } + ) + box_counter = 0 + labels.clear() + else: + raise RuntimeError(f"Error parsing annotation file {filepath}") + + def parse_test_annotations_file(self) -> None: + filepath = os.path.join(self.root, "wider_face_split", "wider_face_test_filelist.txt") + filepath = abspath(expanduser(filepath)) + with open(filepath) as f: + lines = f.readlines() + for line in lines: + line = line.rstrip() + img_path = os.path.join(self.root, "WIDER_test", "images", line) + img_path = abspath(expanduser(img_path)) + self.img_info.append({"img_path": img_path}) + + def _check_integrity(self) -> bool: + # Allow original archive to be deleted (zip). Only need the extracted images + all_files = self.FILE_LIST.copy() + all_files.append(self.ANNOTATIONS_FILE) + for _, md5, filename in all_files: + file, ext = os.path.splitext(filename) + extracted_dir = os.path.join(self.root, file) + if not os.path.exists(extracted_dir): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + + # download and extract image data + for file_id, md5, filename in self.FILE_LIST: + download_file_from_google_drive(file_id, self.root, filename, md5) + filepath = os.path.join(self.root, filename) + extract_archive(filepath) + + # download and extract annotation files + download_and_extract_archive( + url=self.ANNOTATIONS_FILE[0], download_root=self.root, md5=self.ANNOTATIONS_FILE[1] + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/extension.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/extension.py new file mode 100644 index 0000000000000000000000000000000000000000..67801056e88b44d40bc2d382d62c389bf4ef039e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/extension.py @@ -0,0 +1,92 @@ +import os +import sys + +import torch + +from ._internally_replaced_utils import _get_extension_path + + +_HAS_OPS = False + + +def _has_ops(): + return False + + +try: + # On Windows Python-3.8.x has `os.add_dll_directory` call, + # which is called to configure dll search path. + # To find cuda related dlls we need to make sure the + # conda environment/bin path is configured Please take a look: + # https://stackoverflow.com/questions/59330863/cant-import-dll-module-in-python + # Please note: if some path can't be added using add_dll_directory we simply ignore this path + if os.name == "nt" and sys.version_info < (3, 9): + env_path = os.environ["PATH"] + path_arr = env_path.split(";") + for path in path_arr: + if os.path.exists(path): + try: + os.add_dll_directory(path) # type: ignore[attr-defined] + except Exception: + pass + + lib_path = _get_extension_path("_C") + torch.ops.load_library(lib_path) + _HAS_OPS = True + + def _has_ops(): # noqa: F811 + return True + +except (ImportError, OSError): + pass + + +def _assert_has_ops(): + if not _has_ops(): + raise RuntimeError( + "Couldn't load custom C++ ops. This can happen if your PyTorch and " + "torchvision versions are incompatible, or if you had errors while compiling " + "torchvision from source. For further information on the compatible versions, check " + "https://github.com/pytorch/vision#installation for the compatibility matrix. " + "Please check your PyTorch version with torch.__version__ and your torchvision " + "version with torchvision.__version__ and verify if they are compatible, and if not " + "please reinstall torchvision so that it matches your PyTorch install." + ) + + +def _check_cuda_version(): + """ + Make sure that CUDA versions match between the pytorch install and torchvision install + """ + if not _HAS_OPS: + return -1 + from torch.version import cuda as torch_version_cuda + + _version = torch.ops.torchvision._cuda_version() + if _version != -1 and torch_version_cuda is not None: + tv_version = str(_version) + if int(tv_version) < 10000: + tv_major = int(tv_version[0]) + tv_minor = int(tv_version[2]) + else: + tv_major = int(tv_version[0:2]) + tv_minor = int(tv_version[3]) + t_version = torch_version_cuda.split(".") + t_major = int(t_version[0]) + t_minor = int(t_version[1]) + if t_major != tv_major: + raise RuntimeError( + "Detected that PyTorch and torchvision were compiled with different CUDA major versions. " + f"PyTorch has CUDA Version={t_major}.{t_minor} and torchvision has " + f"CUDA Version={tv_major}.{tv_minor}. " + "Please reinstall the torchvision that matches your PyTorch install." + ) + return _version + + +def _load_library(lib_name): + lib_path = _get_extension_path(lib_name) + torch.ops.load_library(lib_path) + + +_check_cuda_version() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03bd5d23cb2cf8e3acb67b7567e3ad9ef8061874 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/__init__.py @@ -0,0 +1,73 @@ +try: + from ._load_gpu_decoder import _HAS_GPU_VIDEO_DECODER +except ModuleNotFoundError: + _HAS_GPU_VIDEO_DECODER = False + +from ._video_opt import ( + _HAS_CPU_VIDEO_DECODER, + _HAS_VIDEO_OPT, + _probe_video_from_file, + _probe_video_from_memory, + _read_video_from_file, + _read_video_from_memory, + _read_video_timestamps_from_file, + _read_video_timestamps_from_memory, + Timebase, + VideoMetaData, +) +from .image import ( + decode_avif, + decode_gif, + decode_heic, + decode_image, + decode_jpeg, + decode_png, + decode_webp, + encode_jpeg, + encode_png, + ImageReadMode, + read_file, + read_image, + write_file, + write_jpeg, + write_png, +) +from .video import read_video, read_video_timestamps, write_video +from .video_reader import VideoReader + + +__all__ = [ + "write_video", + "read_video", + "read_video_timestamps", + "_read_video_from_file", + "_read_video_timestamps_from_file", + "_probe_video_from_file", + "_read_video_from_memory", + "_read_video_timestamps_from_memory", + "_probe_video_from_memory", + "_HAS_CPU_VIDEO_DECODER", + "_HAS_VIDEO_OPT", + "_HAS_GPU_VIDEO_DECODER", + "_read_video_clip_from_memory", + "_read_video_meta_data", + "VideoMetaData", + "Timebase", + "ImageReadMode", + "decode_image", + "decode_jpeg", + "decode_png", + "decode_avif", + "decode_heic", + "decode_webp", + "decode_gif", + "encode_jpeg", + "encode_png", + "read_file", + "read_image", + "write_file", + "write_jpeg", + "write_png", + "Video", + "VideoReader", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_load_gpu_decoder.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_load_gpu_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..cfd40c545d8201b67290e27bf74ce115774dace1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_load_gpu_decoder.py @@ -0,0 +1,8 @@ +from ..extension import _load_library + + +try: + _load_library("gpu_decoder") + _HAS_GPU_VIDEO_DECODER = True +except (ImportError, OSError): + _HAS_GPU_VIDEO_DECODER = False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_video_deprecation_warning.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_video_deprecation_warning.py new file mode 100644 index 0000000000000000000000000000000000000000..6e18dc0916d9012a1dc7c5968a4f75c41c0fbd31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_video_deprecation_warning.py @@ -0,0 +1,16 @@ +import warnings + +import torch + + +def _raise_video_deprecation_warning(): + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + warnings.warn( + "The video decoding and encoding capabilities of torchvision " + "are deprecated from version 0.22 and will be removed in version 0.24. " + "We recommend that you migrate to TorchCodec, where we'll consolidate " + "the future decoding/encoding capabilities of PyTorch: " + "https://github.com/pytorch/torchcodec", + UserWarning, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_video_opt.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_video_opt.py new file mode 100644 index 0000000000000000000000000000000000000000..5dbf035886fc4465f3c8c634100d572d6c9f019d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/_video_opt.py @@ -0,0 +1,521 @@ +import math +import warnings +from fractions import Fraction +from typing import Optional, Union + +import torch + +from ..extension import _load_library +from ._video_deprecation_warning import _raise_video_deprecation_warning + + +try: + _load_library("video_reader") + _HAS_CPU_VIDEO_DECODER = True +except (ImportError, OSError): + _HAS_CPU_VIDEO_DECODER = False + +_HAS_VIDEO_OPT = _HAS_CPU_VIDEO_DECODER # For BC +default_timebase = Fraction(0, 1) + + +# simple class for torch scripting +# the complex Fraction class from fractions module is not scriptable +class Timebase: + __annotations__ = {"numerator": int, "denominator": int} + __slots__ = ["numerator", "denominator"] + + def __init__( + self, + numerator: int, + denominator: int, + ) -> None: + self.numerator = numerator + self.denominator = denominator + + +class VideoMetaData: + __annotations__ = { + "has_video": bool, + "video_timebase": Timebase, + "video_duration": float, + "video_fps": float, + "has_audio": bool, + "audio_timebase": Timebase, + "audio_duration": float, + "audio_sample_rate": float, + } + __slots__ = [ + "has_video", + "video_timebase", + "video_duration", + "video_fps", + "has_audio", + "audio_timebase", + "audio_duration", + "audio_sample_rate", + ] + + def __init__(self) -> None: + self.has_video = False + self.video_timebase = Timebase(0, 1) + self.video_duration = 0.0 + self.video_fps = 0.0 + self.has_audio = False + self.audio_timebase = Timebase(0, 1) + self.audio_duration = 0.0 + self.audio_sample_rate = 0.0 + + +def _validate_pts(pts_range: tuple[int, int]) -> None: + + if pts_range[0] > pts_range[1] > 0: + raise ValueError( + f"Start pts should not be smaller than end pts, got start pts: {pts_range[0]} and end pts: {pts_range[1]}" + ) + + +def _fill_info( + vtimebase: torch.Tensor, + vfps: torch.Tensor, + vduration: torch.Tensor, + atimebase: torch.Tensor, + asample_rate: torch.Tensor, + aduration: torch.Tensor, +) -> VideoMetaData: + """ + Build update VideoMetaData struct with info about the video + """ + meta = VideoMetaData() + if vtimebase.numel() > 0: + meta.video_timebase = Timebase(int(vtimebase[0].item()), int(vtimebase[1].item())) + timebase = vtimebase[0].item() / float(vtimebase[1].item()) + if vduration.numel() > 0: + meta.has_video = True + meta.video_duration = float(vduration.item()) * timebase + if vfps.numel() > 0: + meta.video_fps = float(vfps.item()) + if atimebase.numel() > 0: + meta.audio_timebase = Timebase(int(atimebase[0].item()), int(atimebase[1].item())) + timebase = atimebase[0].item() / float(atimebase[1].item()) + if aduration.numel() > 0: + meta.has_audio = True + meta.audio_duration = float(aduration.item()) * timebase + if asample_rate.numel() > 0: + meta.audio_sample_rate = float(asample_rate.item()) + + return meta + + +def _align_audio_frames( + aframes: torch.Tensor, aframe_pts: torch.Tensor, audio_pts_range: tuple[int, int] +) -> torch.Tensor: + start, end = aframe_pts[0], aframe_pts[-1] + num_samples = aframes.size(0) + step_per_aframe = float(end - start + 1) / float(num_samples) + s_idx = 0 + e_idx = num_samples + if start < audio_pts_range[0]: + s_idx = int((audio_pts_range[0] - start) / step_per_aframe) + if audio_pts_range[1] != -1 and end > audio_pts_range[1]: + e_idx = int((audio_pts_range[1] - end) / step_per_aframe) + return aframes[s_idx:e_idx, :] + + +def _read_video_from_file( + filename: str, + seek_frame_margin: float = 0.25, + read_video_stream: bool = True, + video_width: int = 0, + video_height: int = 0, + video_min_dimension: int = 0, + video_max_dimension: int = 0, + video_pts_range: tuple[int, int] = (0, -1), + video_timebase: Fraction = default_timebase, + read_audio_stream: bool = True, + audio_samples: int = 0, + audio_channels: int = 0, + audio_pts_range: tuple[int, int] = (0, -1), + audio_timebase: Fraction = default_timebase, +) -> tuple[torch.Tensor, torch.Tensor, VideoMetaData]: + """ + Reads a video from a file, returning both the video frames and the audio frames + + Args: + filename (str): path to the video file + seek_frame_margin (double, optional): seeking frame in the stream is imprecise. Thus, + when video_start_pts is specified, we seek the pts earlier by seek_frame_margin seconds + read_video_stream (int, optional): whether read video stream. If yes, set to 1. Otherwise, 0 + video_width/video_height/video_min_dimension/video_max_dimension (int): together decide + the size of decoded frames: + + - When video_width = 0, video_height = 0, video_min_dimension = 0, + and video_max_dimension = 0, keep the original frame resolution + - When video_width = 0, video_height = 0, video_min_dimension != 0, + and video_max_dimension = 0, keep the aspect ratio and resize the + frame so that shorter edge size is video_min_dimension + - When video_width = 0, video_height = 0, video_min_dimension = 0, + and video_max_dimension != 0, keep the aspect ratio and resize + the frame so that longer edge size is video_max_dimension + - When video_width = 0, video_height = 0, video_min_dimension != 0, + and video_max_dimension != 0, resize the frame so that shorter + edge size is video_min_dimension, and longer edge size is + video_max_dimension. The aspect ratio may not be preserved + - When video_width = 0, video_height != 0, video_min_dimension = 0, + and video_max_dimension = 0, keep the aspect ratio and resize + the frame so that frame video_height is $video_height + - When video_width != 0, video_height == 0, video_min_dimension = 0, + and video_max_dimension = 0, keep the aspect ratio and resize + the frame so that frame video_width is $video_width + - When video_width != 0, video_height != 0, video_min_dimension = 0, + and video_max_dimension = 0, resize the frame so that frame + video_width and video_height are set to $video_width and + $video_height, respectively + video_pts_range (list(int), optional): the start and end presentation timestamp of video stream + video_timebase (Fraction, optional): a Fraction rational number which denotes timebase in video stream + read_audio_stream (int, optional): whether read audio stream. If yes, set to 1. Otherwise, 0 + audio_samples (int, optional): audio sampling rate + audio_channels (int optional): audio channels + audio_pts_range (list(int), optional): the start and end presentation timestamp of audio stream + audio_timebase (Fraction, optional): a Fraction rational number which denotes time base in audio stream + + Returns + vframes (Tensor[T, H, W, C]): the `T` video frames + aframes (Tensor[L, K]): the audio frames, where `L` is the number of points and + `K` is the number of audio_channels + info (Dict): metadata for the video and audio. Can contain the fields video_fps (float) + and audio_fps (int) + """ + _raise_video_deprecation_warning() + _validate_pts(video_pts_range) + _validate_pts(audio_pts_range) + + result = torch.ops.video_reader.read_video_from_file( + filename, + seek_frame_margin, + 0, # getPtsOnly + read_video_stream, + video_width, + video_height, + video_min_dimension, + video_max_dimension, + video_pts_range[0], + video_pts_range[1], + video_timebase.numerator, + video_timebase.denominator, + read_audio_stream, + audio_samples, + audio_channels, + audio_pts_range[0], + audio_pts_range[1], + audio_timebase.numerator, + audio_timebase.denominator, + ) + vframes, _vframe_pts, vtimebase, vfps, vduration, aframes, aframe_pts, atimebase, asample_rate, aduration = result + info = _fill_info(vtimebase, vfps, vduration, atimebase, asample_rate, aduration) + if aframes.numel() > 0: + # when audio stream is found + aframes = _align_audio_frames(aframes, aframe_pts, audio_pts_range) + return vframes, aframes, info + + +def _read_video_timestamps_from_file(filename: str) -> tuple[list[int], list[int], VideoMetaData]: + """ + Decode all video- and audio frames in the video. Only pts + (presentation timestamp) is returned. The actual frame pixel data is not + copied. Thus, it is much faster than read_video(...) + """ + result = torch.ops.video_reader.read_video_from_file( + filename, + 0, # seek_frame_margin + 1, # getPtsOnly + 1, # read_video_stream + 0, # video_width + 0, # video_height + 0, # video_min_dimension + 0, # video_max_dimension + 0, # video_start_pts + -1, # video_end_pts + 0, # video_timebase_num + 1, # video_timebase_den + 1, # read_audio_stream + 0, # audio_samples + 0, # audio_channels + 0, # audio_start_pts + -1, # audio_end_pts + 0, # audio_timebase_num + 1, # audio_timebase_den + ) + _vframes, vframe_pts, vtimebase, vfps, vduration, _aframes, aframe_pts, atimebase, asample_rate, aduration = result + info = _fill_info(vtimebase, vfps, vduration, atimebase, asample_rate, aduration) + + vframe_pts = vframe_pts.numpy().tolist() + aframe_pts = aframe_pts.numpy().tolist() + return vframe_pts, aframe_pts, info + + +def _probe_video_from_file(filename: str) -> VideoMetaData: + """ + Probe a video file and return VideoMetaData with info about the video + """ + _raise_video_deprecation_warning() + result = torch.ops.video_reader.probe_video_from_file(filename) + vtimebase, vfps, vduration, atimebase, asample_rate, aduration = result + info = _fill_info(vtimebase, vfps, vduration, atimebase, asample_rate, aduration) + return info + + +def _read_video_from_memory( + video_data: torch.Tensor, + seek_frame_margin: float = 0.25, + read_video_stream: int = 1, + video_width: int = 0, + video_height: int = 0, + video_min_dimension: int = 0, + video_max_dimension: int = 0, + video_pts_range: tuple[int, int] = (0, -1), + video_timebase_numerator: int = 0, + video_timebase_denominator: int = 1, + read_audio_stream: int = 1, + audio_samples: int = 0, + audio_channels: int = 0, + audio_pts_range: tuple[int, int] = (0, -1), + audio_timebase_numerator: int = 0, + audio_timebase_denominator: int = 1, +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Reads a video from memory, returning both the video frames as the audio frames + This function is torchscriptable. + + Args: + video_data (data type could be 1) torch.Tensor, dtype=torch.int8 or 2) python bytes): + compressed video content stored in either 1) torch.Tensor 2) python bytes + seek_frame_margin (double, optional): seeking frame in the stream is imprecise. + Thus, when video_start_pts is specified, we seek the pts earlier by seek_frame_margin seconds + read_video_stream (int, optional): whether read video stream. If yes, set to 1. Otherwise, 0 + video_width/video_height/video_min_dimension/video_max_dimension (int): together decide + the size of decoded frames: + + - When video_width = 0, video_height = 0, video_min_dimension = 0, + and video_max_dimension = 0, keep the original frame resolution + - When video_width = 0, video_height = 0, video_min_dimension != 0, + and video_max_dimension = 0, keep the aspect ratio and resize the + frame so that shorter edge size is video_min_dimension + - When video_width = 0, video_height = 0, video_min_dimension = 0, + and video_max_dimension != 0, keep the aspect ratio and resize + the frame so that longer edge size is video_max_dimension + - When video_width = 0, video_height = 0, video_min_dimension != 0, + and video_max_dimension != 0, resize the frame so that shorter + edge size is video_min_dimension, and longer edge size is + video_max_dimension. The aspect ratio may not be preserved + - When video_width = 0, video_height != 0, video_min_dimension = 0, + and video_max_dimension = 0, keep the aspect ratio and resize + the frame so that frame video_height is $video_height + - When video_width != 0, video_height == 0, video_min_dimension = 0, + and video_max_dimension = 0, keep the aspect ratio and resize + the frame so that frame video_width is $video_width + - When video_width != 0, video_height != 0, video_min_dimension = 0, + and video_max_dimension = 0, resize the frame so that frame + video_width and video_height are set to $video_width and + $video_height, respectively + video_pts_range (list(int), optional): the start and end presentation timestamp of video stream + video_timebase_numerator / video_timebase_denominator (float, optional): a rational + number which denotes timebase in video stream + read_audio_stream (int, optional): whether read audio stream. If yes, set to 1. Otherwise, 0 + audio_samples (int, optional): audio sampling rate + audio_channels (int optional): audio audio_channels + audio_pts_range (list(int), optional): the start and end presentation timestamp of audio stream + audio_timebase_numerator / audio_timebase_denominator (float, optional): + a rational number which denotes time base in audio stream + + Returns: + vframes (Tensor[T, H, W, C]): the `T` video frames + aframes (Tensor[L, K]): the audio frames, where `L` is the number of points and + `K` is the number of channels + """ + + _raise_video_deprecation_warning() + _validate_pts(video_pts_range) + _validate_pts(audio_pts_range) + + if not isinstance(video_data, torch.Tensor): + with warnings.catch_warnings(): + # Ignore the warning because we actually don't modify the buffer in this function + warnings.filterwarnings("ignore", message="The given buffer is not writable") + video_data = torch.frombuffer(video_data, dtype=torch.uint8) + + result = torch.ops.video_reader.read_video_from_memory( + video_data, + seek_frame_margin, + 0, # getPtsOnly + read_video_stream, + video_width, + video_height, + video_min_dimension, + video_max_dimension, + video_pts_range[0], + video_pts_range[1], + video_timebase_numerator, + video_timebase_denominator, + read_audio_stream, + audio_samples, + audio_channels, + audio_pts_range[0], + audio_pts_range[1], + audio_timebase_numerator, + audio_timebase_denominator, + ) + + vframes, _vframe_pts, vtimebase, vfps, vduration, aframes, aframe_pts, atimebase, asample_rate, aduration = result + + if aframes.numel() > 0: + # when audio stream is found + aframes = _align_audio_frames(aframes, aframe_pts, audio_pts_range) + + return vframes, aframes + + +def _read_video_timestamps_from_memory( + video_data: torch.Tensor, +) -> tuple[list[int], list[int], VideoMetaData]: + """ + Decode all frames in the video. Only pts (presentation timestamp) is returned. + The actual frame pixel data is not copied. Thus, read_video_timestamps(...) + is much faster than read_video(...) + """ + if not isinstance(video_data, torch.Tensor): + with warnings.catch_warnings(): + # Ignore the warning because we actually don't modify the buffer in this function + warnings.filterwarnings("ignore", message="The given buffer is not writable") + video_data = torch.frombuffer(video_data, dtype=torch.uint8) + result = torch.ops.video_reader.read_video_from_memory( + video_data, + 0, # seek_frame_margin + 1, # getPtsOnly + 1, # read_video_stream + 0, # video_width + 0, # video_height + 0, # video_min_dimension + 0, # video_max_dimension + 0, # video_start_pts + -1, # video_end_pts + 0, # video_timebase_num + 1, # video_timebase_den + 1, # read_audio_stream + 0, # audio_samples + 0, # audio_channels + 0, # audio_start_pts + -1, # audio_end_pts + 0, # audio_timebase_num + 1, # audio_timebase_den + ) + _raise_video_deprecation_warning() + _vframes, vframe_pts, vtimebase, vfps, vduration, _aframes, aframe_pts, atimebase, asample_rate, aduration = result + info = _fill_info(vtimebase, vfps, vduration, atimebase, asample_rate, aduration) + + vframe_pts = vframe_pts.numpy().tolist() + aframe_pts = aframe_pts.numpy().tolist() + return vframe_pts, aframe_pts, info + + +def _probe_video_from_memory( + video_data: torch.Tensor, +) -> VideoMetaData: + """ + Probe a video in memory and return VideoMetaData with info about the video + This function is torchscriptable + """ + _raise_video_deprecation_warning() + if not isinstance(video_data, torch.Tensor): + with warnings.catch_warnings(): + # Ignore the warning because we actually don't modify the buffer in this function + warnings.filterwarnings("ignore", message="The given buffer is not writable") + video_data = torch.frombuffer(video_data, dtype=torch.uint8) + result = torch.ops.video_reader.probe_video_from_memory(video_data) + vtimebase, vfps, vduration, atimebase, asample_rate, aduration = result + info = _fill_info(vtimebase, vfps, vduration, atimebase, asample_rate, aduration) + return info + + +def _read_video( + filename: str, + start_pts: Union[float, Fraction] = 0, + end_pts: Optional[Union[float, Fraction]] = None, + pts_unit: str = "pts", +) -> tuple[torch.Tensor, torch.Tensor, dict[str, float]]: + _raise_video_deprecation_warning() + if end_pts is None: + end_pts = float("inf") + + if pts_unit == "pts": + warnings.warn( + "The pts_unit 'pts' gives wrong results and will be removed in a " + + "follow-up version. Please use pts_unit 'sec'." + ) + + info = _probe_video_from_file(filename) + + has_video = info.has_video + has_audio = info.has_audio + + def get_pts(time_base): + start_offset = start_pts + end_offset = end_pts + if pts_unit == "sec": + start_offset = int(math.floor(start_pts * (1 / time_base))) + if end_offset != float("inf"): + end_offset = int(math.ceil(end_pts * (1 / time_base))) + if end_offset == float("inf"): + end_offset = -1 + return start_offset, end_offset + + video_pts_range = (0, -1) + video_timebase = default_timebase + if has_video: + video_timebase = Fraction(info.video_timebase.numerator, info.video_timebase.denominator) + video_pts_range = get_pts(video_timebase) + + audio_pts_range = (0, -1) + audio_timebase = default_timebase + if has_audio: + audio_timebase = Fraction(info.audio_timebase.numerator, info.audio_timebase.denominator) + audio_pts_range = get_pts(audio_timebase) + + vframes, aframes, info = _read_video_from_file( + filename, + read_video_stream=True, + video_pts_range=video_pts_range, + video_timebase=video_timebase, + read_audio_stream=True, + audio_pts_range=audio_pts_range, + audio_timebase=audio_timebase, + ) + _info = {} + if has_video: + _info["video_fps"] = info.video_fps + if has_audio: + _info["audio_fps"] = info.audio_sample_rate + + return vframes, aframes, _info + + +def _read_video_timestamps( + filename: str, pts_unit: str = "pts" +) -> tuple[Union[list[int], list[Fraction]], Optional[float]]: + _raise_video_deprecation_warning() + if pts_unit == "pts": + warnings.warn( + "The pts_unit 'pts' gives wrong results and will be removed in a " + + "follow-up version. Please use pts_unit 'sec'." + ) + + pts: Union[list[int], list[Fraction]] + pts, _, info = _read_video_timestamps_from_file(filename) + + if pts_unit == "sec": + video_time_base = Fraction(info.video_timebase.numerator, info.video_timebase.denominator) + pts = [x * video_time_base for x in pts] + + video_fps = info.video_fps if info.has_video else None + + return pts, video_fps diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/image.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/image.py new file mode 100644 index 0000000000000000000000000000000000000000..c88e58ca4cac5f39124ab257875ee3665858e720 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/image.py @@ -0,0 +1,511 @@ +from enum import Enum +from typing import Union +from warnings import warn + +import torch + +from ..extension import _load_library +from ..utils import _log_api_usage_once + + +try: + _load_library("image") +except (ImportError, OSError) as e: + warn( + f"Failed to load image Python extension: '{e}'" + f"If you don't plan on using image functionality from `torchvision.io`, you can ignore this warning. " + f"Otherwise, there might be something wrong with your environment. " + f"Did you have `libjpeg` or `libpng` installed before building `torchvision` from source?" + ) + + +class ImageReadMode(Enum): + """Allow automatic conversion to RGB, RGBA, etc while decoding. + + .. note:: + + You don't need to use this struct, you can just pass strings to all + ``mode`` parameters, e.g. ``mode="RGB"``. + + The different available modes are the following. + + - UNCHANGED: loads the image as-is + - RGB: converts to RGB + - RGBA: converts to RGB with transparency (also aliased as RGB_ALPHA) + - GRAY: converts to grayscale + - GRAY_ALPHA: converts to grayscale with transparency + + .. note:: + + Some decoders won't support all possible values, e.g. GRAY and + GRAY_ALPHA are only supported for PNG and JPEG images. + """ + + UNCHANGED = 0 + GRAY = 1 + GRAY_ALPHA = 2 + RGB = 3 + RGB_ALPHA = 4 + RGBA = RGB_ALPHA # Alias for convenience + + +def read_file(path: str) -> torch.Tensor: + """ + Return the bytes contents of a file as a uint8 1D Tensor. + + Args: + path (str or ``pathlib.Path``): the path to the file to be read + + Returns: + data (Tensor) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(read_file) + data = torch.ops.image.read_file(str(path)) + return data + + +def write_file(filename: str, data: torch.Tensor) -> None: + """ + Write the content of an uint8 1D tensor to a file. + + Args: + filename (str or ``pathlib.Path``): the path to the file to be written + data (Tensor): the contents to be written to the output file + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(write_file) + torch.ops.image.write_file(str(filename), data) + + +def decode_png( + input: torch.Tensor, + mode: ImageReadMode = ImageReadMode.UNCHANGED, + apply_exif_orientation: bool = False, +) -> torch.Tensor: + """ + Decodes a PNG image into a 3 dimensional RGB or grayscale Tensor. + + The values of the output tensor are in uint8 in [0, 255] for most cases. If + the image is a 16-bit png, then the output tensor is uint16 in [0, 65535] + (supported from torchvision ``0.21``). Since uint16 support is limited in + pytorch, we recommend calling + :func:`torchvision.transforms.v2.functional.to_dtype()` with ``scale=True`` + after this function to convert the decoded image into a uint8 or float + tensor. + + Args: + input (Tensor[1]): a one dimensional uint8 tensor containing + the raw bytes of the PNG image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + apply_exif_orientation (bool): apply EXIF orientation transformation to the output tensor. + Default: False. + + Returns: + output (Tensor[image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_png) + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + output = torch.ops.image.decode_png(input, mode.value, apply_exif_orientation) + return output + + +def encode_png(input: torch.Tensor, compression_level: int = 6) -> torch.Tensor: + """ + Takes an input tensor in CHW layout and returns a buffer with the contents + of its corresponding PNG file. + + Args: + input (Tensor[channels, image_height, image_width]): int8 image tensor of + ``c`` channels, where ``c`` must 3 or 1. + compression_level (int): Compression factor for the resulting file, it must be a number + between 0 and 9. Default: 6 + + Returns: + Tensor[1]: A one dimensional int8 tensor that contains the raw bytes of the + PNG file. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(encode_png) + output = torch.ops.image.encode_png(input, compression_level) + return output + + +def write_png(input: torch.Tensor, filename: str, compression_level: int = 6): + """ + Takes an input tensor in CHW layout (or HW in the case of grayscale images) + and saves it in a PNG file. + + Args: + input (Tensor[channels, image_height, image_width]): int8 image tensor of + ``c`` channels, where ``c`` must be 1 or 3. + filename (str or ``pathlib.Path``): Path to save the image. + compression_level (int): Compression factor for the resulting file, it must be a number + between 0 and 9. Default: 6 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(write_png) + output = encode_png(input, compression_level) + write_file(filename, output) + + +def decode_jpeg( + input: Union[torch.Tensor, list[torch.Tensor]], + mode: ImageReadMode = ImageReadMode.UNCHANGED, + device: Union[str, torch.device] = "cpu", + apply_exif_orientation: bool = False, +) -> Union[torch.Tensor, list[torch.Tensor]]: + """Decode JPEG image(s) into 3D RGB or grayscale Tensor(s), on CPU or CUDA. + + The values of the output tensor are uint8 between 0 and 255. + + .. note:: + When using a CUDA device, passing a list of tensors is more efficient than repeated individual calls to ``decode_jpeg``. + When using CPU the performance is equivalent. + The CUDA version of this function has explicitly been designed with thread-safety in mind. + This function does not return partial results in case of an error. + + Args: + input (Tensor[1] or list[Tensor[1]]): a (list of) one dimensional uint8 tensor(s) containing + the raw bytes of the JPEG image. The tensor(s) must be on CPU, + regardless of the ``device`` parameter. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + device (str or torch.device): The device on which the decoded image will + be stored. If a cuda device is specified, the image will be decoded + with `nvjpeg `_. This is only + supported for CUDA version >= 10.1 + + .. betastatus:: device parameter + + .. warning:: + There is a memory leak in the nvjpeg library for CUDA versions < 11.6. + Make sure to rely on CUDA 11.6 or above before using ``device="cuda"``. + apply_exif_orientation (bool): apply EXIF orientation transformation to the output tensor. + Default: False. Only implemented for JPEG format on CPU. + + Returns: + output (Tensor[image_channels, image_height, image_width] or list[Tensor[image_channels, image_height, image_width]]): + The values of the output tensor(s) are uint8 between 0 and 255. + ``output.device`` will be set to the specified ``device`` + + + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_jpeg) + if isinstance(device, str): + device = torch.device(device) + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + + if isinstance(input, list): + if len(input) == 0: + raise ValueError("Input list must contain at least one element") + if not all(isinstance(t, torch.Tensor) for t in input): + raise ValueError("All elements of the input list must be tensors.") + if not all(t.device.type == "cpu" for t in input): + raise ValueError("Input list must contain tensors on CPU.") + if device.type == "cuda": + return torch.ops.image.decode_jpegs_cuda(input, mode.value, device) + else: + return [torch.ops.image.decode_jpeg(img, mode.value, apply_exif_orientation) for img in input] + + else: # input is tensor + if input.device.type != "cpu": + raise ValueError("Input tensor must be a CPU tensor") + if device.type == "cuda": + return torch.ops.image.decode_jpegs_cuda([input], mode.value, device)[0] + else: + return torch.ops.image.decode_jpeg(input, mode.value, apply_exif_orientation) + + +def encode_jpeg( + input: Union[torch.Tensor, list[torch.Tensor]], quality: int = 75 +) -> Union[torch.Tensor, list[torch.Tensor]]: + """Encode RGB tensor(s) into raw encoded jpeg bytes, on CPU or CUDA. + + .. note:: + Passing a list of CUDA tensors is more efficient than repeated individual calls to ``encode_jpeg``. + For CPU tensors the performance is equivalent. + + Args: + input (Tensor[channels, image_height, image_width] or List[Tensor[channels, image_height, image_width]]): + (list of) uint8 image tensor(s) of ``c`` channels, where ``c`` must be 1 or 3 + quality (int): Quality of the resulting JPEG file(s). Must be a number between + 1 and 100. Default: 75 + + Returns: + output (Tensor[1] or list[Tensor[1]]): A (list of) one dimensional uint8 tensor(s) that contain the raw bytes of the JPEG file. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(encode_jpeg) + if quality < 1 or quality > 100: + raise ValueError("Image quality should be a positive number between 1 and 100") + if isinstance(input, list): + if not input: + raise ValueError("encode_jpeg requires at least one input tensor when a list is passed") + if input[0].device.type == "cuda": + return torch.ops.image.encode_jpegs_cuda(input, quality) + else: + return [torch.ops.image.encode_jpeg(image, quality) for image in input] + else: # single input tensor + if input.device.type == "cuda": + return torch.ops.image.encode_jpegs_cuda([input], quality)[0] + else: + return torch.ops.image.encode_jpeg(input, quality) + + +def write_jpeg(input: torch.Tensor, filename: str, quality: int = 75): + """ + Takes an input tensor in CHW layout and saves it in a JPEG file. + + Args: + input (Tensor[channels, image_height, image_width]): int8 image tensor of ``c`` + channels, where ``c`` must be 1 or 3. + filename (str or ``pathlib.Path``): Path to save the image. + quality (int): Quality of the resulting JPEG file, it must be a number + between 1 and 100. Default: 75 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(write_jpeg) + output = encode_jpeg(input, quality) + assert isinstance(output, torch.Tensor) # Needed for torchscript + write_file(filename, output) + + +def decode_image( + input: Union[torch.Tensor, str], + mode: ImageReadMode = ImageReadMode.UNCHANGED, + apply_exif_orientation: bool = False, +) -> torch.Tensor: + """Decode an image into a uint8 tensor, from a path or from raw encoded bytes. + + Currently supported image formats are jpeg, png, gif and webp. + + The values of the output tensor are in uint8 in [0, 255] for most cases. + + If the image is a 16-bit png, then the output tensor is uint16 in [0, 65535] + (supported from torchvision ``0.21``). Since uint16 support is limited in + pytorch, we recommend calling + :func:`torchvision.transforms.v2.functional.to_dtype()` with ``scale=True`` + after this function to convert the decoded image into a uint8 or float + tensor. + + .. note:: + + ``decode_image()`` doesn't work yet on AVIF or HEIC images. For these + formats, directly call :func:`~torchvision.io.decode_avif` or + :func:`~torchvision.io.decode_heic`. + + Args: + input (Tensor or str or ``pathlib.Path``): The image to decode. If a + tensor is passed, it must be one dimensional uint8 tensor containing + the raw bytes of the image. Otherwise, this must be a path to the image file. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + apply_exif_orientation (bool): apply EXIF orientation transformation to the output tensor. + Only applies to JPEG and PNG images. Default: False. + + Returns: + output (Tensor[image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_image) + if not isinstance(input, torch.Tensor): + input = read_file(str(input)) + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + output = torch.ops.image.decode_image(input, mode.value, apply_exif_orientation) + return output + + +def read_image( + path: str, + mode: ImageReadMode = ImageReadMode.UNCHANGED, + apply_exif_orientation: bool = False, +) -> torch.Tensor: + """[OBSOLETE] Use :func:`~torchvision.io.decode_image` instead.""" + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(read_image) + data = read_file(path) + return decode_image(data, mode, apply_exif_orientation=apply_exif_orientation) + + +def decode_gif(input: torch.Tensor) -> torch.Tensor: + """ + Decode a GIF image into a 3 or 4 dimensional RGB Tensor. + + The values of the output tensor are uint8 between 0 and 255. + The output tensor has shape ``(C, H, W)`` if there is only one image in the + GIF, and ``(N, C, H, W)`` if there are ``N`` images. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the GIF image. + + Returns: + output (Tensor[image_channels, image_height, image_width] or Tensor[num_images, image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_gif) + return torch.ops.image.decode_gif(input) + + +def decode_webp( + input: torch.Tensor, + mode: ImageReadMode = ImageReadMode.UNCHANGED, +) -> torch.Tensor: + """ + Decode a WEBP image into a 3 dimensional RGB[A] Tensor. + + The values of the output tensor are uint8 between 0 and 255. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the WEBP image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + + Returns: + Decoded image (Tensor[image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_webp) + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + return torch.ops.image.decode_webp(input, mode.value) + + +# TODO_AVIF_HEIC: Better support for torchscript. Scripting decode_avif of +# decode_heic currently fails, mainly because of the logic +# _load_extra_decoders_once() (using global variables, try/except statements, +# etc.). +# The ops (torch.ops.extra_decoders_ns.decode_*) are otherwise torchscript-able, +# and users who need torchscript can always just wrap those. + +# TODO_AVIF_HEIC: decode_image() should work for those. The key technical issue +# we have here is that the format detection logic of decode_image() is +# implemented in torchvision, and torchvision has zero knowledge of +# torchvision-extra-decoders, so we cannot call the AVIF/HEIC C++ decoders +# (those in torchvision-extra-decoders) from there. +# A trivial check that could be done within torchvision would be to check the +# file extension, if a path was passed. We could also just implement the +# AVIF/HEIC detection logic in Python as a fallback, if the file detection +# didn't find any format. In any case: properly determining whether a file is +# HEIC is far from trivial, and relying on libmagic would probably be best + + +_EXTRA_DECODERS_ALREADY_LOADED = False + + +def _load_extra_decoders_once(): + global _EXTRA_DECODERS_ALREADY_LOADED + if _EXTRA_DECODERS_ALREADY_LOADED: + return + + try: + import torchvision_extra_decoders + + # torchvision-extra-decoders only supports linux for now. BUT, users on + # e.g. MacOS can still install it: they will get the pure-python + # 0.0.0.dev version: + # https://pypi.org/project/torchvision-extra-decoders/0.0.0.dev0, which + # is a dummy version that was created to reserve the namespace on PyPI. + # We have to check that expose_extra_decoders() exists for those users, + # so we can properly error on non-Linux archs. + assert hasattr(torchvision_extra_decoders, "expose_extra_decoders") + except (AssertionError, ImportError) as e: + raise RuntimeError( + "In order to enable the AVIF and HEIC decoding capabilities of " + "torchvision, you need to `pip install torchvision-extra-decoders`. " + "Just install the package, you don't need to update your code. " + "This is only supported on Linux, and this feature is still in BETA stage. " + "Please let us know of any issue: https://github.com/pytorch/vision/issues/new/choose. " + "Note that `torchvision-extra-decoders` is released under the LGPL license. " + ) from e + + # This will expose torch.ops.extra_decoders_ns.decode_avif and torch.ops.extra_decoders_ns.decode_heic + torchvision_extra_decoders.expose_extra_decoders() + + _EXTRA_DECODERS_ALREADY_LOADED = True + + +def decode_avif(input: torch.Tensor, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor: + """Decode an AVIF image into a 3 dimensional RGB[A] Tensor. + + .. warning:: + In order to enable the AVIF decoding capabilities of torchvision, you + first need to run ``pip install torchvision-extra-decoders``. Just + install the package, you don't need to update your code. This is only + supported on Linux, and this feature is still in BETA stage. Please let + us know of any issue: + https://github.com/pytorch/vision/issues/new/choose. Note that + `torchvision-extra-decoders + `_ is + released under the LGPL license. + + The values of the output tensor are in uint8 in [0, 255] for most images. If + the image has a bit-depth of more than 8, then the output tensor is uint16 + in [0, 65535]. Since uint16 support is limited in pytorch, we recommend + calling :func:`torchvision.transforms.v2.functional.to_dtype()` with + ``scale=True`` after this function to convert the decoded image into a uint8 + or float tensor. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the AVIF image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + + Returns: + Decoded image (Tensor[image_channels, image_height, image_width]) + """ + _load_extra_decoders_once() + if input.dtype != torch.uint8: + raise RuntimeError(f"Input tensor must have uint8 data type, got {input.dtype}") + return torch.ops.extra_decoders_ns.decode_avif(input, mode.value) + + +def decode_heic(input: torch.Tensor, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor: + """Decode an HEIC image into a 3 dimensional RGB[A] Tensor. + + .. warning:: + In order to enable the HEIC decoding capabilities of torchvision, you + first need to run ``pip install torchvision-extra-decoders``. Just + install the package, you don't need to update your code. This is only + supported on Linux, and this feature is still in BETA stage. Please let + us know of any issue: + https://github.com/pytorch/vision/issues/new/choose. Note that + `torchvision-extra-decoders + `_ is + released under the LGPL license. + + The values of the output tensor are in uint8 in [0, 255] for most images. If + the image has a bit-depth of more than 8, then the output tensor is uint16 + in [0, 65535]. Since uint16 support is limited in pytorch, we recommend + calling :func:`torchvision.transforms.v2.functional.to_dtype()` with + ``scale=True`` after this function to convert the decoded image into a uint8 + or float tensor. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the HEIC image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + + Returns: + Decoded image (Tensor[image_channels, image_height, image_width]) + """ + _load_extra_decoders_once() + if input.dtype != torch.uint8: + raise RuntimeError(f"Input tensor must have uint8 data type, got {input.dtype}") + return torch.ops.extra_decoders_ns.decode_heic(input, mode.value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/video.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/video.py new file mode 100644 index 0000000000000000000000000000000000000000..14edcf50aaaa5e7d242657ffdc2e3bebf105b8fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/video.py @@ -0,0 +1,468 @@ +import gc +import math +import os +import re +import warnings +from fractions import Fraction +from typing import Any, Optional, Union + +import numpy as np +import torch + +from ..utils import _log_api_usage_once +from . import _video_opt +from ._video_deprecation_warning import _raise_video_deprecation_warning + +try: + import av + + av.logging.set_level(av.logging.ERROR) + if not hasattr(av.video.frame.VideoFrame, "pict_type"): + av = ImportError( + """\ +Your version of PyAV is too old for the necessary video operations in torchvision. +If you are on Python 3.5, you will have to build from source (the conda-forge +packages are not up-to-date). See +https://github.com/mikeboers/PyAV#installation for instructions on how to +install PyAV on your system. +""" + ) + try: + FFmpegError = av.FFmpegError # from av 14 https://github.com/PyAV-Org/PyAV/blob/main/CHANGELOG.rst + except AttributeError: + FFmpegError = av.AVError +except ImportError: + av = ImportError( + """\ +PyAV is not installed, and is necessary for the video operations in torchvision. +See https://github.com/mikeboers/PyAV#installation for instructions on how to +install PyAV on your system. +""" + ) + + +def _check_av_available() -> None: + if isinstance(av, Exception): + raise av + + +def _av_available() -> bool: + return not isinstance(av, Exception) + + +# PyAV has some reference cycles +_CALLED_TIMES = 0 +_GC_COLLECTION_INTERVAL = 10 + + +def write_video( + filename: str, + video_array: torch.Tensor, + fps: float, + video_codec: str = "libx264", + options: Optional[dict[str, Any]] = None, + audio_array: Optional[torch.Tensor] = None, + audio_fps: Optional[float] = None, + audio_codec: Optional[str] = None, + audio_options: Optional[dict[str, Any]] = None, +) -> None: + """ + [DEPRECATED] Writes a 4d tensor in [T, H, W, C] format in a video file. + + .. warning:: + + DEPRECATED: All the video decoding and encoding capabilities of torchvision + are deprecated from version 0.22 and will be removed in version 0.24. We + recommend that you migrate to + `TorchCodec `__, where we'll + consolidate the future decoding/encoding capabilities of PyTorch + + This function relies on PyAV (therefore, ultimately FFmpeg) to encode + videos, you can get more fine-grained control by referring to the other + options at your disposal within `the FFMpeg wiki + `_. + + Args: + filename (str): path where the video will be saved + video_array (Tensor[T, H, W, C]): tensor containing the individual frames, + as a uint8 tensor in [T, H, W, C] format + fps (Number): video frames per second + video_codec (str): the name of the video codec, i.e. "libx264", "h264", etc. + options (Dict): dictionary containing options to be passed into the PyAV video stream. + The list of options is codec-dependent and can all + be found from `the FFMpeg wiki `_. + audio_array (Tensor[C, N]): tensor containing the audio, where C is the number of channels + and N is the number of samples + audio_fps (Number): audio sample rate, typically 44100 or 48000 + audio_codec (str): the name of the audio codec, i.e. "mp3", "aac", etc. + audio_options (Dict): dictionary containing options to be passed into the PyAV audio stream. + The list of options is codec-dependent and can all + be found from `the FFMpeg wiki `_. + + Examples:: + >>> # Creating libx264 video with CRF 17, for visually lossless footage: + >>> + >>> from torchvision.io import write_video + >>> # 1000 frames of 100x100, 3-channel image. + >>> vid = torch.randn(1000, 100, 100, 3, dtype = torch.uint8) + >>> write_video("video.mp4", options = {"crf": "17"}) + + """ + _raise_video_deprecation_warning() + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(write_video) + _check_av_available() + video_array = torch.as_tensor(video_array, dtype=torch.uint8).numpy(force=True) + + # PyAV does not support floating point numbers with decimal point + # and will throw OverflowException in case this is not the case + if isinstance(fps, float): + fps = int(np.round(fps)) + + with av.open(filename, mode="w") as container: + stream = container.add_stream(video_codec, rate=fps) + stream.width = video_array.shape[2] + stream.height = video_array.shape[1] + stream.pix_fmt = "yuv420p" if video_codec != "libx264rgb" else "rgb24" + stream.options = options or {} + + if audio_array is not None: + audio_format_dtypes = { + "dbl": " 1 else "mono" + audio_sample_fmt = container.streams.audio[0].format.name + + format_dtype = np.dtype(audio_format_dtypes[audio_sample_fmt]) + audio_array = torch.as_tensor(audio_array).numpy(force=True).astype(format_dtype) + + frame = av.AudioFrame.from_ndarray(audio_array, format=audio_sample_fmt, layout=audio_layout) + + frame.sample_rate = audio_fps + + for packet in a_stream.encode(frame): + container.mux(packet) + + for packet in a_stream.encode(): + container.mux(packet) + + for img in video_array: + frame = av.VideoFrame.from_ndarray(img, format="rgb24") + try: + frame.pict_type = "NONE" + except TypeError: + from av.video.frame import PictureType # noqa + + frame.pict_type = PictureType.NONE + + for packet in stream.encode(frame): + container.mux(packet) + + # Flush stream + for packet in stream.encode(): + container.mux(packet) + + +def _read_from_stream( + container: "av.container.Container", + start_offset: float, + end_offset: float, + pts_unit: str, + stream: "av.stream.Stream", + stream_name: dict[str, Optional[Union[int, tuple[int, ...], list[int]]]], +) -> list["av.frame.Frame"]: + global _CALLED_TIMES, _GC_COLLECTION_INTERVAL + _CALLED_TIMES += 1 + if _CALLED_TIMES % _GC_COLLECTION_INTERVAL == _GC_COLLECTION_INTERVAL - 1: + gc.collect() + + if pts_unit == "sec": + # TODO: we should change all of this from ground up to simply take + # sec and convert to MS in C++ + start_offset = int(math.floor(start_offset * (1 / stream.time_base))) + if end_offset != float("inf"): + end_offset = int(math.ceil(end_offset * (1 / stream.time_base))) + else: + warnings.warn("The pts_unit 'pts' gives wrong results. Please use pts_unit 'sec'.") + + frames = {} + should_buffer = True + max_buffer_size = 5 + if stream.type == "video": + # DivX-style packed B-frames can have out-of-order pts (2 frames in a single pkt) + # so need to buffer some extra frames to sort everything + # properly + extradata = stream.codec_context.extradata + # overly complicated way of finding if `divx_packed` is set, following + # https://github.com/FFmpeg/FFmpeg/commit/d5a21172283572af587b3d939eba0091484d3263 + if extradata and b"DivX" in extradata: + # can't use regex directly because of some weird characters sometimes... + pos = extradata.find(b"DivX") + d = extradata[pos:] + o = re.search(rb"DivX(\d+)Build(\d+)(\w)", d) + if o is None: + o = re.search(rb"DivX(\d+)b(\d+)(\w)", d) + if o is not None: + should_buffer = o.group(3) == b"p" + seek_offset = start_offset + # some files don't seek to the right location, so better be safe here + seek_offset = max(seek_offset - 1, 0) + if should_buffer: + # FIXME this is kind of a hack, but we will jump to the previous keyframe + # so this will be safe + seek_offset = max(seek_offset - max_buffer_size, 0) + try: + # TODO check if stream needs to always be the video stream here or not + container.seek(seek_offset, any_frame=False, backward=True, stream=stream) + except FFmpegError: + # TODO add some warnings in this case + # print("Corrupted file?", container.name) + return [] + buffer_count = 0 + try: + for _idx, frame in enumerate(container.decode(**stream_name)): + frames[frame.pts] = frame + if frame.pts >= end_offset: + if should_buffer and buffer_count < max_buffer_size: + buffer_count += 1 + continue + break + except FFmpegError: + # TODO add a warning + pass + # ensure that the results are sorted wrt the pts + result = [frames[i] for i in sorted(frames) if start_offset <= frames[i].pts <= end_offset] + if len(frames) > 0 and start_offset > 0 and start_offset not in frames: + # if there is no frame that exactly matches the pts of start_offset + # add the last frame smaller than start_offset, to guarantee that + # we will have all the necessary data. This is most useful for audio + preceding_frames = [i for i in frames if i < start_offset] + if len(preceding_frames) > 0: + first_frame_pts = max(preceding_frames) + result.insert(0, frames[first_frame_pts]) + return result + + +def _align_audio_frames( + aframes: torch.Tensor, audio_frames: list["av.frame.Frame"], ref_start: int, ref_end: float +) -> torch.Tensor: + start, end = audio_frames[0].pts, audio_frames[-1].pts + total_aframes = aframes.shape[1] + step_per_aframe = (end - start + 1) / total_aframes + s_idx = 0 + e_idx = total_aframes + if start < ref_start: + s_idx = int((ref_start - start) / step_per_aframe) + if end > ref_end: + e_idx = int((ref_end - end) / step_per_aframe) + return aframes[:, s_idx:e_idx] + + +def read_video( + filename: str, + start_pts: Union[float, Fraction] = 0, + end_pts: Optional[Union[float, Fraction]] = None, + pts_unit: str = "pts", + output_format: str = "THWC", +) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]: + """[DEPRECATED] Reads a video from a file, returning both the video frames and the audio frames + + .. warning:: + + DEPRECATED: All the video decoding and encoding capabilities of torchvision + are deprecated from version 0.22 and will be removed in version 0.24. We + recommend that you migrate to + `TorchCodec `__, where we'll + consolidate the future decoding/encoding capabilities of PyTorch + + Args: + filename (str): path to the video file. If using the pyav backend, this can be whatever ``av.open`` accepts. + start_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional): + The start presentation time of the video + end_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional): + The end presentation time + pts_unit (str, optional): unit in which start_pts and end_pts values will be interpreted, + either 'pts' or 'sec'. Defaults to 'pts'. + output_format (str, optional): The format of the output video tensors. Can be either "THWC" (default) or "TCHW". + + Returns: + vframes (Tensor[T, H, W, C] or Tensor[T, C, H, W]): the `T` video frames + aframes (Tensor[K, L]): the audio frames, where `K` is the number of channels and `L` is the number of points + info (Dict): metadata for the video and audio. Can contain the fields video_fps (float) and audio_fps (int) + """ + _raise_video_deprecation_warning() + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(read_video) + + output_format = output_format.upper() + if output_format not in ("THWC", "TCHW"): + raise ValueError(f"output_format should be either 'THWC' or 'TCHW', got {output_format}.") + + from torchvision import get_video_backend + + if get_video_backend() != "pyav": + if not os.path.exists(filename): + raise RuntimeError(f"File not found: {filename}") + vframes, aframes, info = _video_opt._read_video(filename, start_pts, end_pts, pts_unit) + else: + _check_av_available() + + if end_pts is None: + end_pts = float("inf") + + if end_pts < start_pts: + raise ValueError( + f"end_pts should be larger than start_pts, got start_pts={start_pts} and end_pts={end_pts}" + ) + + info = {} + video_frames = [] + audio_frames = [] + audio_timebase = _video_opt.default_timebase + + try: + with av.open(filename, metadata_errors="ignore") as container: + if container.streams.audio: + audio_timebase = container.streams.audio[0].time_base + if container.streams.video: + video_frames = _read_from_stream( + container, + start_pts, + end_pts, + pts_unit, + container.streams.video[0], + {"video": 0}, + ) + video_fps = container.streams.video[0].average_rate + # guard against potentially corrupted files + if video_fps is not None: + info["video_fps"] = float(video_fps) + + if container.streams.audio: + audio_frames = _read_from_stream( + container, + start_pts, + end_pts, + pts_unit, + container.streams.audio[0], + {"audio": 0}, + ) + info["audio_fps"] = container.streams.audio[0].rate + + except FFmpegError: + # TODO raise a warning? + pass + + vframes_list = [frame.to_rgb().to_ndarray() for frame in video_frames] + aframes_list = [frame.to_ndarray() for frame in audio_frames] + + if vframes_list: + vframes = torch.as_tensor(np.stack(vframes_list)) + else: + vframes = torch.empty((0, 1, 1, 3), dtype=torch.uint8) + + if aframes_list: + aframes = np.concatenate(aframes_list, 1) + aframes = torch.as_tensor(aframes) + if pts_unit == "sec": + start_pts = int(math.floor(start_pts * (1 / audio_timebase))) + if end_pts != float("inf"): + end_pts = int(math.ceil(end_pts * (1 / audio_timebase))) + aframes = _align_audio_frames(aframes, audio_frames, start_pts, end_pts) + else: + aframes = torch.empty((1, 0), dtype=torch.float32) + + if output_format == "TCHW": + # [T,H,W,C] --> [T,C,H,W] + vframes = vframes.permute(0, 3, 1, 2) + + return vframes, aframes, info + + +def _can_read_timestamps_from_packets(container: "av.container.Container") -> bool: + extradata = container.streams[0].codec_context.extradata + if extradata is None: + return False + if b"Lavc" in extradata: + return True + return False + + +def _decode_video_timestamps(container: "av.container.Container") -> list[int]: + if _can_read_timestamps_from_packets(container): + # fast path + return [x.pts for x in container.demux(video=0) if x.pts is not None] + else: + return [x.pts for x in container.decode(video=0) if x.pts is not None] + + +def read_video_timestamps(filename: str, pts_unit: str = "pts") -> tuple[list[int], Optional[float]]: + """[DEPREACTED] List the video frames timestamps. + + .. warning:: + + DEPRECATED: All the video decoding and encoding capabilities of torchvision + are deprecated from version 0.22 and will be removed in version 0.24. We + recommend that you migrate to + `TorchCodec `__, where we'll + consolidate the future decoding/encoding capabilities of PyTorch + + Note that the function decodes the whole video frame-by-frame. + + Args: + filename (str): path to the video file + pts_unit (str, optional): unit in which timestamp values will be returned + either 'pts' or 'sec'. Defaults to 'pts'. + + Returns: + pts (List[int] if pts_unit = 'pts', List[Fraction] if pts_unit = 'sec'): + presentation timestamps for each one of the frames in the video. + video_fps (float, optional): the frame rate for the video + + """ + _raise_video_deprecation_warning() + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(read_video_timestamps) + from torchvision import get_video_backend + + if get_video_backend() != "pyav": + return _video_opt._read_video_timestamps(filename, pts_unit) + + _check_av_available() + + video_fps = None + pts = [] + + try: + with av.open(filename, metadata_errors="ignore") as container: + if container.streams.video: + video_stream = container.streams.video[0] + video_time_base = video_stream.time_base + try: + pts = _decode_video_timestamps(container) + except FFmpegError: + warnings.warn(f"Failed decoding frames for file {filename}") + video_fps = float(video_stream.average_rate) + except FFmpegError as e: + msg = f"Failed to open container for {filename}; Caught error: {e}" + warnings.warn(msg, RuntimeWarning) + + pts.sort() + + if pts_unit == "sec": + pts = [x * video_time_base for x in pts] + + return pts, video_fps diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/video_reader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/video_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..efc58c4790557a7b15478d5fd9d8feacfbf489c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/io/video_reader.py @@ -0,0 +1,296 @@ +import io +import warnings +from collections.abc import Iterator + +from typing import Any + +import torch + +from ..utils import _log_api_usage_once +from ._video_deprecation_warning import _raise_video_deprecation_warning + +from ._video_opt import _HAS_CPU_VIDEO_DECODER + +if _HAS_CPU_VIDEO_DECODER: + + def _has_video_opt() -> bool: + return True + +else: + + def _has_video_opt() -> bool: + return False + + +try: + import av + + av.logging.set_level(av.logging.ERROR) + if not hasattr(av.video.frame.VideoFrame, "pict_type"): + av = ImportError( + """\ +Your version of PyAV is too old for the necessary video operations in torchvision. +If you are on Python 3.5, you will have to build from source (the conda-forge +packages are not up-to-date). See +https://github.com/mikeboers/PyAV#installation for instructions on how to +install PyAV on your system. +""" + ) +except ImportError: + av = ImportError( + """\ +PyAV is not installed, and is necessary for the video operations in torchvision. +See https://github.com/mikeboers/PyAV#installation for instructions on how to +install PyAV on your system. +""" + ) + + +class VideoReader: + """[DEPRECATED] Fine-grained video-reading API. + Supports frame-by-frame reading of various streams from a single video + container. Much like previous video_reader API it supports the following + backends: video_reader, pyav, and cuda. + Backends can be set via `torchvision.set_video_backend` function. + + .. warning:: + + DEPRECATED: All the video decoding and encoding capabilities of torchvision + are deprecated from version 0.22 and will be removed in version 0.24. We + recommend that you migrate to + `TorchCodec `__, where we'll + consolidate the future decoding/encoding capabilities of PyTorch + + .. betastatus:: VideoReader class + + Example: + The following examples creates a :mod:`VideoReader` object, seeks into 2s + point, and returns a single frame:: + + import torchvision + video_path = "path_to_a_test_video" + reader = torchvision.io.VideoReader(video_path, "video") + reader.seek(2.0) + frame = next(reader) + + :mod:`VideoReader` implements the iterable API, which makes it suitable to + using it in conjunction with :mod:`itertools` for more advanced reading. + As such, we can use a :mod:`VideoReader` instance inside for loops:: + + reader.seek(2) + for frame in reader: + frames.append(frame['data']) + # additionally, `seek` implements a fluent API, so we can do + for frame in reader.seek(2): + frames.append(frame['data']) + + With :mod:`itertools`, we can read all frames between 2 and 5 seconds with the + following code:: + + for frame in itertools.takewhile(lambda x: x['pts'] <= 5, reader.seek(2)): + frames.append(frame['data']) + + and similarly, reading 10 frames after the 2s timestamp can be achieved + as follows:: + + for frame in itertools.islice(reader.seek(2), 10): + frames.append(frame['data']) + + .. note:: + + Each stream descriptor consists of two parts: stream type (e.g. 'video') and + a unique stream id (which are determined by the video encoding). + In this way, if the video container contains multiple + streams of the same type, users can access the one they want. + If only stream type is passed, the decoder auto-detects first stream of that type. + + Args: + src (string, bytes object, or tensor): The media source. + If string-type, it must be a file path supported by FFMPEG. + If bytes, should be an in-memory representation of a file supported by FFMPEG. + If Tensor, it is interpreted internally as byte buffer. + It must be one-dimensional, of type ``torch.uint8``. + + stream (string, optional): descriptor of the required stream, followed by the stream id, + in the format ``{stream_type}:{stream_id}``. Defaults to ``"video:0"``. + Currently available options include ``['video', 'audio']`` + + num_threads (int, optional): number of threads used by the codec to decode video. + Default value (0) enables multithreading with codec-dependent heuristic. The performance + will depend on the version of FFMPEG codecs supported. + """ + + def __init__( + self, + src: str, + stream: str = "video", + num_threads: int = 0, + ) -> None: + _raise_video_deprecation_warning() + _log_api_usage_once(self) + from .. import get_video_backend + + self.backend = get_video_backend() + if isinstance(src, str): + if not src: + raise ValueError("src cannot be empty") + elif isinstance(src, bytes): + if self.backend in ["cuda"]: + raise RuntimeError( + "VideoReader cannot be initialized from bytes object when using cuda or pyav backend." + ) + elif self.backend == "pyav": + src = io.BytesIO(src) + else: + with warnings.catch_warnings(): + # Ignore the warning because we actually don't modify the buffer in this function + warnings.filterwarnings("ignore", message="The given buffer is not writable") + src = torch.frombuffer(src, dtype=torch.uint8) + elif isinstance(src, torch.Tensor): + if self.backend in ["cuda", "pyav"]: + raise RuntimeError( + "VideoReader cannot be initialized from Tensor object when using cuda or pyav backend." + ) + else: + raise ValueError(f"src must be either string, Tensor or bytes object. Got {type(src)}") + + if self.backend == "cuda": + device = torch.device("cuda") + self._c = torch.classes.torchvision.GPUDecoder(src, device) + + elif self.backend == "video_reader": + if isinstance(src, str): + self._c = torch.classes.torchvision.Video(src, stream, num_threads) + elif isinstance(src, torch.Tensor): + self._c = torch.classes.torchvision.Video("", "", 0) + self._c.init_from_memory(src, stream, num_threads) + + elif self.backend == "pyav": + self.container = av.open(src, metadata_errors="ignore") + # TODO: load metadata + stream_type = stream.split(":")[0] + stream_id = 0 if len(stream.split(":")) == 1 else int(stream.split(":")[1]) + self.pyav_stream = {stream_type: stream_id} + self._c = self.container.decode(**self.pyav_stream) + + # TODO: add extradata exception + + else: + raise RuntimeError(f"Unknown video backend: {self.backend}") + + def __next__(self) -> dict[str, Any]: + """Decodes and returns the next frame of the current stream. + Frames are encoded as a dict with mandatory + data and pts fields, where data is a tensor, and pts is a + presentation timestamp of the frame expressed in seconds + as a float. + + Returns: + (dict): a dictionary and containing decoded frame (``data``) + and corresponding timestamp (``pts``) in seconds + + """ + if self.backend == "cuda": + frame = self._c.next() + if frame.numel() == 0: + raise StopIteration + return {"data": frame, "pts": None} + elif self.backend == "video_reader": + frame, pts = self._c.next() + else: + try: + frame = next(self._c) + pts = float(frame.pts * frame.time_base) + if "video" in self.pyav_stream: + frame = torch.as_tensor(frame.to_rgb().to_ndarray()).permute(2, 0, 1) + elif "audio" in self.pyav_stream: + frame = torch.as_tensor(frame.to_ndarray()).permute(1, 0) + else: + frame = None + except av.error.EOFError: + raise StopIteration + + if frame.numel() == 0: + raise StopIteration + + return {"data": frame, "pts": pts} + + def __iter__(self) -> Iterator[dict[str, Any]]: + return self + + def seek(self, time_s: float, keyframes_only: bool = False) -> "VideoReader": + """Seek within current stream. + + Args: + time_s (float): seek time in seconds + keyframes_only (bool): allow to seek only to keyframes + + .. note:: + Current implementation is the so-called precise seek. This + means following seek, call to :mod:`next()` will return the + frame with the exact timestamp if it exists or + the first frame with timestamp larger than ``time_s``. + """ + if self.backend in ["cuda", "video_reader"]: + self._c.seek(time_s, keyframes_only) + else: + # handle special case as pyav doesn't catch it + if time_s < 0: + time_s = 0 + temp_str = self.container.streams.get(**self.pyav_stream)[0] + offset = int(round(time_s / temp_str.time_base)) + if not keyframes_only: + warnings.warn("Accurate seek is not implemented for pyav backend") + self.container.seek(offset, backward=True, any_frame=False, stream=temp_str) + self._c = self.container.decode(**self.pyav_stream) + return self + + def get_metadata(self) -> dict[str, Any]: + """Returns video metadata + + Returns: + (dict): dictionary containing duration and frame rate for every stream + """ + if self.backend == "pyav": + metadata = {} # type: Dict[str, Any] + for stream in self.container.streams: + if stream.type not in metadata: + if stream.type == "video": + rate_n = "fps" + else: + rate_n = "framerate" + metadata[stream.type] = {rate_n: [], "duration": []} + + rate = getattr(stream, "average_rate", None) or stream.sample_rate + + metadata[stream.type]["duration"].append(float(stream.duration * stream.time_base)) + metadata[stream.type][rate_n].append(float(rate)) + return metadata + return self._c.get_metadata() + + def set_current_stream(self, stream: str) -> bool: + """Set current stream. + Explicitly define the stream we are operating on. + + Args: + stream (string): descriptor of the required stream. Defaults to ``"video:0"`` + Currently available stream types include ``['video', 'audio']``. + Each descriptor consists of two parts: stream type (e.g. 'video') and + a unique stream id (which are determined by video encoding). + In this way, if the video container contains multiple + streams of the same type, users can access the one they want. + If only stream type is passed, the decoder auto-detects first stream + of that type and returns it. + + Returns: + (bool): True on success, False otherwise + """ + if self.backend == "cuda": + warnings.warn("GPU decoding only works with video stream.") + if self.backend == "pyav": + stream_type = stream.split(":")[0] + stream_id = 0 if len(stream.split(":")) == 1 else int(stream.split(":")[1]) + self.pyav_stream = {stream_type: stream_id} + self._c = self.container.decode(**self.pyav_stream) + return True + return self._c.set_current_stream(stream) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea0a1f7178b6ca03776d58c17411a8ff483f8b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/__init__.py @@ -0,0 +1,23 @@ +from .alexnet import * +from .convnext import * +from .densenet import * +from .efficientnet import * +from .googlenet import * +from .inception import * +from .mnasnet import * +from .mobilenet import * +from .regnet import * +from .resnet import * +from .shufflenetv2 import * +from .squeezenet import * +from .vgg import * +from .vision_transformer import * +from .swin_transformer import * +from .maxvit import * +from . import detection, optical_flow, quantization, segmentation, video + +# The Weights and WeightsEnum are developer-facing utils that we make public for +# downstream libs like torchgeo https://github.com/pytorch/vision/issues/7094 +# TODO: we could / should document them publicly, but it's not clear where, as +# they're not intended for end users. +from ._api import get_model, get_model_builder, get_model_weights, get_weight, list_models, Weights, WeightsEnum diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_api.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..358e6f431591c30edcfe4d5ebc6dee8a5a44b130 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_api.py @@ -0,0 +1,277 @@ +import fnmatch +import importlib +import inspect +import sys +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from enum import Enum +from functools import partial +from inspect import signature +from types import ModuleType +from typing import Any, Callable, get_args, Optional, TypeVar, Union + +from torch import nn + +from .._internally_replaced_utils import load_state_dict_from_url + + +__all__ = ["WeightsEnum", "Weights", "get_model", "get_model_builder", "get_model_weights", "get_weight", "list_models"] + + +@dataclass +class Weights: + """ + This class is used to group important attributes associated with the pre-trained weights. + + Args: + url (str): The location where we find the weights. + transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms) + needed to use the model. The reason we attach a constructor method rather than an already constructed + object is because the specific object might have memory and thus we want to delay initialization until + needed. + meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be + informative attributes (for example the number of parameters/flops, recipe link/methods used in training + etc), configuration parameters (for example the `num_classes`) needed to construct the model or important + meta-data (for example the `classes` of a classification model) needed to use the model. + """ + + url: str + transforms: Callable + meta: dict[str, Any] + + def __eq__(self, other: Any) -> bool: + # We need this custom implementation for correct deep-copy and deserialization behavior. + # TL;DR: After the definition of an enum, creating a new instance, i.e. by deep-copying or deserializing it, + # involves an equality check against the defined members. Unfortunately, the `transforms` attribute is often + # defined with `functools.partial` and `fn = partial(...); assert deepcopy(fn) != fn`. Without custom handling + # for it, the check against the defined members would fail and effectively prevent the weights from being + # deep-copied or deserialized. + # See https://github.com/pytorch/vision/pull/7107 for details. + if not isinstance(other, Weights): + return NotImplemented + + if self.url != other.url: + return False + + if self.meta != other.meta: + return False + + if isinstance(self.transforms, partial) and isinstance(other.transforms, partial): + return ( + self.transforms.func == other.transforms.func + and self.transforms.args == other.transforms.args + and self.transforms.keywords == other.transforms.keywords + ) + else: + return self.transforms == other.transforms + + +class WeightsEnum(Enum): + """ + This class is the parent class of all model weights. Each model building method receives an optional `weights` + parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type + `Weights`. + + Args: + value (Weights): The data class entry with the weight information. + """ + + @classmethod + def verify(cls, obj: Any) -> Any: + if obj is not None: + if type(obj) is str: + obj = cls[obj.replace(cls.__name__ + ".", "")] + elif not isinstance(obj, cls): + raise TypeError( + f"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}." + ) + return obj + + def get_state_dict(self, *args: Any, **kwargs: Any) -> Mapping[str, Any]: + return load_state_dict_from_url(self.url, *args, **kwargs) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}.{self._name_}" + + @property + def url(self): + return self.value.url + + @property + def transforms(self): + return self.value.transforms + + @property + def meta(self): + return self.value.meta + + +def get_weight(name: str) -> WeightsEnum: + """ + Gets the weights enum value by its full name. Example: "ResNet50_Weights.IMAGENET1K_V1" + + Args: + name (str): The name of the weight enum entry. + + Returns: + WeightsEnum: The requested weight enum. + """ + try: + enum_name, value_name = name.split(".") + except ValueError: + raise ValueError(f"Invalid weight name provided: '{name}'.") + + base_module_name = ".".join(sys.modules[__name__].__name__.split(".")[:-1]) + base_module = importlib.import_module(base_module_name) + model_modules = [base_module] + [ + x[1] + for x in inspect.getmembers(base_module, inspect.ismodule) + if x[1].__file__.endswith("__init__.py") # type: ignore[union-attr] + ] + + weights_enum = None + for m in model_modules: + potential_class = m.__dict__.get(enum_name, None) + if potential_class is not None and issubclass(potential_class, WeightsEnum): + weights_enum = potential_class + break + + if weights_enum is None: + raise ValueError(f"The weight enum '{enum_name}' for the specific method couldn't be retrieved.") + + return weights_enum[value_name] + + +def get_model_weights(name: Union[Callable, str]) -> type[WeightsEnum]: + """ + Returns the weights enum class associated to the given model. + + Args: + name (callable or str): The model builder function or the name under which it is registered. + + Returns: + weights_enum (WeightsEnum): The weights enum class associated with the model. + """ + model = get_model_builder(name) if isinstance(name, str) else name + return _get_enum_from_fn(model) + + +def _get_enum_from_fn(fn: Callable) -> type[WeightsEnum]: + """ + Internal method that gets the weight enum of a specific model builder method. + + Args: + fn (Callable): The builder method used to create the model. + Returns: + WeightsEnum: The requested weight enum. + """ + sig = signature(fn) + if "weights" not in sig.parameters: + raise ValueError("The method is missing the 'weights' argument.") + + ann = sig.parameters["weights"].annotation + weights_enum = None + if isinstance(ann, type) and issubclass(ann, WeightsEnum): + weights_enum = ann + else: + # handle cases like Union[Optional, T] + for t in get_args(ann): # type: ignore[union-attr] + if isinstance(t, type) and issubclass(t, WeightsEnum): + weights_enum = t + break + + if weights_enum is None: + raise ValueError( + "The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct." + ) + + return weights_enum + + +M = TypeVar("M", bound=nn.Module) + +BUILTIN_MODELS = {} + + +def register_model(name: Optional[str] = None) -> Callable[[Callable[..., M]], Callable[..., M]]: + def wrapper(fn: Callable[..., M]) -> Callable[..., M]: + key = name if name is not None else fn.__name__ + if key in BUILTIN_MODELS: + raise ValueError(f"An entry is already registered under the name '{key}'.") + BUILTIN_MODELS[key] = fn + return fn + + return wrapper + + +def list_models( + module: Optional[ModuleType] = None, + include: Union[Iterable[str], str, None] = None, + exclude: Union[Iterable[str], str, None] = None, +) -> list[str]: + """ + Returns a list with the names of registered models. + + Args: + module (ModuleType, optional): The module from which we want to extract the available models. + include (str or Iterable[str], optional): Filter(s) for including the models from the set of all models. + Filters are passed to `fnmatch `__ to match Unix shell-style + wildcards. In case of many filters, the results is the union of individual filters. + exclude (str or Iterable[str], optional): Filter(s) applied after include_filters to remove models. + Filter are passed to `fnmatch `__ to match Unix shell-style + wildcards. In case of many filters, the results is removal of all the models that match any individual filter. + + Returns: + models (list): A list with the names of available models. + """ + all_models = { + k for k, v in BUILTIN_MODELS.items() if module is None or v.__module__.rsplit(".", 1)[0] == module.__name__ + } + if include: + models: set[str] = set() + if isinstance(include, str): + include = [include] + for include_filter in include: + models = models | set(fnmatch.filter(all_models, include_filter)) + else: + models = all_models + + if exclude: + if isinstance(exclude, str): + exclude = [exclude] + for exclude_filter in exclude: + models = models - set(fnmatch.filter(all_models, exclude_filter)) + return sorted(models) + + +def get_model_builder(name: str) -> Callable[..., nn.Module]: + """ + Gets the model name and returns the model builder method. + + Args: + name (str): The name under which the model is registered. + + Returns: + fn (Callable): The model builder method. + """ + name = name.lower() + try: + fn = BUILTIN_MODELS[name] + except KeyError: + raise ValueError(f"Unknown model {name}") + return fn + + +def get_model(name: str, **config: Any) -> nn.Module: + """ + Gets the model name and configuration and returns an instantiated model. + + Args: + name (str): The name under which the model is registered. + **config (Any): parameters passed to the model builder method. + + Returns: + model (nn.Module): The initialized model. + """ + fn = get_model_builder(name) + return fn(**config) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_meta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..e66f411c287e0f456448315ba4fd0bfcce281d2b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_meta.py @@ -0,0 +1,1554 @@ +""" +This file is part of the private API. Please do not refer to any variables defined here directly as they will be +removed on future versions without warning. +""" + +# This will eventually be replaced with a call at torchvision.datasets.info("imagenet").categories +_IMAGENET_CATEGORIES = [ + "tench", + "goldfish", + "great white shark", + "tiger shark", + "hammerhead", + "electric ray", + "stingray", + "cock", + "hen", + "ostrich", + "brambling", + "goldfinch", + "house finch", + "junco", + "indigo bunting", + "robin", + "bulbul", + "jay", + "magpie", + "chickadee", + "water ouzel", + "kite", + "bald eagle", + "vulture", + "great grey owl", + "European fire salamander", + "common newt", + "eft", + "spotted salamander", + "axolotl", + "bullfrog", + "tree frog", + "tailed frog", + "loggerhead", + "leatherback turtle", + "mud turtle", + "terrapin", + "box turtle", + "banded gecko", + "common iguana", + "American chameleon", + "whiptail", + "agama", + "frilled lizard", + "alligator lizard", + "Gila monster", + "green lizard", + "African chameleon", + "Komodo dragon", + "African crocodile", + "American alligator", + "triceratops", + "thunder snake", + "ringneck snake", + "hognose snake", + "green snake", + "king snake", + "garter snake", + "water snake", + "vine snake", + "night snake", + "boa constrictor", + "rock python", + "Indian cobra", + "green mamba", + "sea snake", + "horned viper", + "diamondback", + "sidewinder", + "trilobite", + "harvestman", + "scorpion", + "black and gold garden spider", + "barn spider", + "garden spider", + "black widow", + "tarantula", + "wolf spider", + "tick", + "centipede", + "black grouse", + "ptarmigan", + "ruffed grouse", + "prairie chicken", + "peacock", + "quail", + "partridge", + "African grey", + "macaw", + "sulphur-crested cockatoo", + "lorikeet", + "coucal", + "bee eater", + "hornbill", + "hummingbird", + "jacamar", + "toucan", + "drake", + "red-breasted merganser", + "goose", + "black swan", + "tusker", + "echidna", + "platypus", + "wallaby", + "koala", + "wombat", + "jellyfish", + "sea anemone", + "brain coral", + "flatworm", + "nematode", + "conch", + "snail", + "slug", + "sea slug", + "chiton", + "chambered nautilus", + "Dungeness crab", + "rock crab", + "fiddler crab", + "king crab", + "American lobster", + "spiny lobster", + "crayfish", + "hermit crab", + "isopod", + "white stork", + "black stork", + "spoonbill", + "flamingo", + "little blue heron", + "American egret", + "bittern", + "crane bird", + "limpkin", + "European gallinule", + "American coot", + "bustard", + "ruddy turnstone", + "red-backed sandpiper", + "redshank", + "dowitcher", + "oystercatcher", + "pelican", + "king penguin", + "albatross", + "grey whale", + "killer whale", + "dugong", + "sea lion", + "Chihuahua", + "Japanese spaniel", + "Maltese dog", + "Pekinese", + "Shih-Tzu", + "Blenheim spaniel", + "papillon", + "toy terrier", + "Rhodesian ridgeback", + "Afghan hound", + "basset", + "beagle", + "bloodhound", + "bluetick", + "black-and-tan coonhound", + "Walker hound", + "English foxhound", + "redbone", + "borzoi", + "Irish wolfhound", + "Italian greyhound", + "whippet", + "Ibizan hound", + "Norwegian elkhound", + "otterhound", + "Saluki", + "Scottish deerhound", + "Weimaraner", + "Staffordshire bullterrier", + "American Staffordshire terrier", + "Bedlington terrier", + "Border terrier", + "Kerry blue terrier", + "Irish terrier", + "Norfolk terrier", + "Norwich terrier", + "Yorkshire terrier", + "wire-haired fox terrier", + "Lakeland terrier", + "Sealyham terrier", + "Airedale", + "cairn", + "Australian terrier", + "Dandie Dinmont", + "Boston bull", + "miniature schnauzer", + "giant schnauzer", + "standard schnauzer", + "Scotch terrier", + "Tibetan terrier", + "silky terrier", + "soft-coated wheaten terrier", + "West Highland white terrier", + "Lhasa", + "flat-coated retriever", + "curly-coated retriever", + "golden retriever", + "Labrador retriever", + "Chesapeake Bay retriever", + "German short-haired pointer", + "vizsla", + "English setter", + "Irish setter", + "Gordon setter", + "Brittany spaniel", + "clumber", + "English springer", + "Welsh springer spaniel", + "cocker spaniel", + "Sussex spaniel", + "Irish water spaniel", + "kuvasz", + "schipperke", + "groenendael", + "malinois", + "briard", + "kelpie", + "komondor", + "Old English sheepdog", + "Shetland sheepdog", + "collie", + "Border collie", + "Bouvier des Flandres", + "Rottweiler", + "German shepherd", + "Doberman", + "miniature pinscher", + "Greater Swiss Mountain dog", + "Bernese mountain dog", + "Appenzeller", + "EntleBucher", + "boxer", + "bull mastiff", + "Tibetan mastiff", + "French bulldog", + "Great Dane", + "Saint Bernard", + "Eskimo dog", + "malamute", + "Siberian husky", + "dalmatian", + "affenpinscher", + "basenji", + "pug", + "Leonberg", + "Newfoundland", + "Great Pyrenees", + "Samoyed", + "Pomeranian", + "chow", + "keeshond", + "Brabancon griffon", + "Pembroke", + "Cardigan", + "toy poodle", + "miniature poodle", + "standard poodle", + "Mexican hairless", + "timber wolf", + "white wolf", + "red wolf", + "coyote", + "dingo", + "dhole", + "African hunting dog", + "hyena", + "red fox", + "kit fox", + "Arctic fox", + "grey fox", + "tabby", + "tiger cat", + "Persian cat", + "Siamese cat", + "Egyptian cat", + "cougar", + "lynx", + "leopard", + "snow leopard", + "jaguar", + "lion", + "tiger", + "cheetah", + "brown bear", + "American black bear", + "ice bear", + "sloth bear", + "mongoose", + "meerkat", + "tiger beetle", + "ladybug", + "ground beetle", + "long-horned beetle", + "leaf beetle", + "dung beetle", + "rhinoceros beetle", + "weevil", + "fly", + "bee", + "ant", + "grasshopper", + "cricket", + "walking stick", + "cockroach", + "mantis", + "cicada", + "leafhopper", + "lacewing", + "dragonfly", + "damselfly", + "admiral", + "ringlet", + "monarch", + "cabbage butterfly", + "sulphur butterfly", + "lycaenid", + "starfish", + "sea urchin", + "sea cucumber", + "wood rabbit", + "hare", + "Angora", + "hamster", + "porcupine", + "fox squirrel", + "marmot", + "beaver", + "guinea pig", + "sorrel", + "zebra", + "hog", + "wild boar", + "warthog", + "hippopotamus", + "ox", + "water buffalo", + "bison", + "ram", + "bighorn", + "ibex", + "hartebeest", + "impala", + "gazelle", + "Arabian camel", + "llama", + "weasel", + "mink", + "polecat", + "black-footed ferret", + "otter", + "skunk", + "badger", + "armadillo", + "three-toed sloth", + "orangutan", + "gorilla", + "chimpanzee", + "gibbon", + "siamang", + "guenon", + "patas", + "baboon", + "macaque", + "langur", + "colobus", + "proboscis monkey", + "marmoset", + "capuchin", + "howler monkey", + "titi", + "spider monkey", + "squirrel monkey", + "Madagascar cat", + "indri", + "Indian elephant", + "African elephant", + "lesser panda", + "giant panda", + "barracouta", + "eel", + "coho", + "rock beauty", + "anemone fish", + "sturgeon", + "gar", + "lionfish", + "puffer", + "abacus", + "abaya", + "academic gown", + "accordion", + "acoustic guitar", + "aircraft carrier", + "airliner", + "airship", + "altar", + "ambulance", + "amphibian", + "analog clock", + "apiary", + "apron", + "ashcan", + "assault rifle", + "backpack", + "bakery", + "balance beam", + "balloon", + "ballpoint", + "Band Aid", + "banjo", + "bannister", + "barbell", + "barber chair", + "barbershop", + "barn", + "barometer", + "barrel", + "barrow", + "baseball", + "basketball", + "bassinet", + "bassoon", + "bathing cap", + "bath towel", + "bathtub", + "beach wagon", + "beacon", + "beaker", + "bearskin", + "beer bottle", + "beer glass", + "bell cote", + "bib", + "bicycle-built-for-two", + "bikini", + "binder", + "binoculars", + "birdhouse", + "boathouse", + "bobsled", + "bolo tie", + "bonnet", + "bookcase", + "bookshop", + "bottlecap", + "bow", + "bow tie", + "brass", + "brassiere", + "breakwater", + "breastplate", + "broom", + "bucket", + "buckle", + "bulletproof vest", + "bullet train", + "butcher shop", + "cab", + "caldron", + "candle", + "cannon", + "canoe", + "can opener", + "cardigan", + "car mirror", + "carousel", + "carpenter's kit", + "carton", + "car wheel", + "cash machine", + "cassette", + "cassette player", + "castle", + "catamaran", + "CD player", + "cello", + "cellular telephone", + "chain", + "chainlink fence", + "chain mail", + "chain saw", + "chest", + "chiffonier", + "chime", + "china cabinet", + "Christmas stocking", + "church", + "cinema", + "cleaver", + "cliff dwelling", + "cloak", + "clog", + "cocktail shaker", + "coffee mug", + "coffeepot", + "coil", + "combination lock", + "computer keyboard", + "confectionery", + "container ship", + "convertible", + "corkscrew", + "cornet", + "cowboy boot", + "cowboy hat", + "cradle", + "crane", + "crash helmet", + "crate", + "crib", + "Crock Pot", + "croquet ball", + "crutch", + "cuirass", + "dam", + "desk", + "desktop computer", + "dial telephone", + "diaper", + "digital clock", + "digital watch", + "dining table", + "dishrag", + "dishwasher", + "disk brake", + "dock", + "dogsled", + "dome", + "doormat", + "drilling platform", + "drum", + "drumstick", + "dumbbell", + "Dutch oven", + "electric fan", + "electric guitar", + "electric locomotive", + "entertainment center", + "envelope", + "espresso maker", + "face powder", + "feather boa", + "file", + "fireboat", + "fire engine", + "fire screen", + "flagpole", + "flute", + "folding chair", + "football helmet", + "forklift", + "fountain", + "fountain pen", + "four-poster", + "freight car", + "French horn", + "frying pan", + "fur coat", + "garbage truck", + "gasmask", + "gas pump", + "goblet", + "go-kart", + "golf ball", + "golfcart", + "gondola", + "gong", + "gown", + "grand piano", + "greenhouse", + "grille", + "grocery store", + "guillotine", + "hair slide", + "hair spray", + "half track", + "hammer", + "hamper", + "hand blower", + "hand-held computer", + "handkerchief", + "hard disc", + "harmonica", + "harp", + "harvester", + "hatchet", + "holster", + "home theater", + "honeycomb", + "hook", + "hoopskirt", + "horizontal bar", + "horse cart", + "hourglass", + "iPod", + "iron", + "jack-o'-lantern", + "jean", + "jeep", + "jersey", + "jigsaw puzzle", + "jinrikisha", + "joystick", + "kimono", + "knee pad", + "knot", + "lab coat", + "ladle", + "lampshade", + "laptop", + "lawn mower", + "lens cap", + "letter opener", + "library", + "lifeboat", + "lighter", + "limousine", + "liner", + "lipstick", + "Loafer", + "lotion", + "loudspeaker", + "loupe", + "lumbermill", + "magnetic compass", + "mailbag", + "mailbox", + "maillot", + "maillot tank suit", + "manhole cover", + "maraca", + "marimba", + "mask", + "matchstick", + "maypole", + "maze", + "measuring cup", + "medicine chest", + "megalith", + "microphone", + "microwave", + "military uniform", + "milk can", + "minibus", + "miniskirt", + "minivan", + "missile", + "mitten", + "mixing bowl", + "mobile home", + "Model T", + "modem", + "monastery", + "monitor", + "moped", + "mortar", + "mortarboard", + "mosque", + "mosquito net", + "motor scooter", + "mountain bike", + "mountain tent", + "mouse", + "mousetrap", + "moving van", + "muzzle", + "nail", + "neck brace", + "necklace", + "nipple", + "notebook", + "obelisk", + "oboe", + "ocarina", + "odometer", + "oil filter", + "organ", + "oscilloscope", + "overskirt", + "oxcart", + "oxygen mask", + "packet", + "paddle", + "paddlewheel", + "padlock", + "paintbrush", + "pajama", + "palace", + "panpipe", + "paper towel", + "parachute", + "parallel bars", + "park bench", + "parking meter", + "passenger car", + "patio", + "pay-phone", + "pedestal", + "pencil box", + "pencil sharpener", + "perfume", + "Petri dish", + "photocopier", + "pick", + "pickelhaube", + "picket fence", + "pickup", + "pier", + "piggy bank", + "pill bottle", + "pillow", + "ping-pong ball", + "pinwheel", + "pirate", + "pitcher", + "plane", + "planetarium", + "plastic bag", + "plate rack", + "plow", + "plunger", + "Polaroid camera", + "pole", + "police van", + "poncho", + "pool table", + "pop bottle", + "pot", + "potter's wheel", + "power drill", + "prayer rug", + "printer", + "prison", + "projectile", + "projector", + "puck", + "punching bag", + "purse", + "quill", + "quilt", + "racer", + "racket", + "radiator", + "radio", + "radio telescope", + "rain barrel", + "recreational vehicle", + "reel", + "reflex camera", + "refrigerator", + "remote control", + "restaurant", + "revolver", + "rifle", + "rocking chair", + "rotisserie", + "rubber eraser", + "rugby ball", + "rule", + "running shoe", + "safe", + "safety pin", + "saltshaker", + "sandal", + "sarong", + "sax", + "scabbard", + "scale", + "school bus", + "schooner", + "scoreboard", + "screen", + "screw", + "screwdriver", + "seat belt", + "sewing machine", + "shield", + "shoe shop", + "shoji", + "shopping basket", + "shopping cart", + "shovel", + "shower cap", + "shower curtain", + "ski", + "ski mask", + "sleeping bag", + "slide rule", + "sliding door", + "slot", + "snorkel", + "snowmobile", + "snowplow", + "soap dispenser", + "soccer ball", + "sock", + "solar dish", + "sombrero", + "soup bowl", + "space bar", + "space heater", + "space shuttle", + "spatula", + "speedboat", + "spider web", + "spindle", + "sports car", + "spotlight", + "stage", + "steam locomotive", + "steel arch bridge", + "steel drum", + "stethoscope", + "stole", + "stone wall", + "stopwatch", + "stove", + "strainer", + "streetcar", + "stretcher", + "studio couch", + "stupa", + "submarine", + "suit", + "sundial", + "sunglass", + "sunglasses", + "sunscreen", + "suspension bridge", + "swab", + "sweatshirt", + "swimming trunks", + "swing", + "switch", + "syringe", + "table lamp", + "tank", + "tape player", + "teapot", + "teddy", + "television", + "tennis ball", + "thatch", + "theater curtain", + "thimble", + "thresher", + "throne", + "tile roof", + "toaster", + "tobacco shop", + "toilet seat", + "torch", + "totem pole", + "tow truck", + "toyshop", + "tractor", + "trailer truck", + "tray", + "trench coat", + "tricycle", + "trimaran", + "tripod", + "triumphal arch", + "trolleybus", + "trombone", + "tub", + "turnstile", + "typewriter keyboard", + "umbrella", + "unicycle", + "upright", + "vacuum", + "vase", + "vault", + "velvet", + "vending machine", + "vestment", + "viaduct", + "violin", + "volleyball", + "waffle iron", + "wall clock", + "wallet", + "wardrobe", + "warplane", + "washbasin", + "washer", + "water bottle", + "water jug", + "water tower", + "whiskey jug", + "whistle", + "wig", + "window screen", + "window shade", + "Windsor tie", + "wine bottle", + "wing", + "wok", + "wooden spoon", + "wool", + "worm fence", + "wreck", + "yawl", + "yurt", + "web site", + "comic book", + "crossword puzzle", + "street sign", + "traffic light", + "book jacket", + "menu", + "plate", + "guacamole", + "consomme", + "hot pot", + "trifle", + "ice cream", + "ice lolly", + "French loaf", + "bagel", + "pretzel", + "cheeseburger", + "hotdog", + "mashed potato", + "head cabbage", + "broccoli", + "cauliflower", + "zucchini", + "spaghetti squash", + "acorn squash", + "butternut squash", + "cucumber", + "artichoke", + "bell pepper", + "cardoon", + "mushroom", + "Granny Smith", + "strawberry", + "orange", + "lemon", + "fig", + "pineapple", + "banana", + "jackfruit", + "custard apple", + "pomegranate", + "hay", + "carbonara", + "chocolate sauce", + "dough", + "meat loaf", + "pizza", + "potpie", + "burrito", + "red wine", + "espresso", + "cup", + "eggnog", + "alp", + "bubble", + "cliff", + "coral reef", + "geyser", + "lakeside", + "promontory", + "sandbar", + "seashore", + "valley", + "volcano", + "ballplayer", + "groom", + "scuba diver", + "rapeseed", + "daisy", + "yellow lady's slipper", + "corn", + "acorn", + "hip", + "buckeye", + "coral fungus", + "agaric", + "gyromitra", + "stinkhorn", + "earthstar", + "hen-of-the-woods", + "bolete", + "ear", + "toilet tissue", +] + +# To be replaced with torchvision.datasets.info("coco").categories +_COCO_CATEGORIES = [ + "__background__", + "person", + "bicycle", + "car", + "motorcycle", + "airplane", + "bus", + "train", + "truck", + "boat", + "traffic light", + "fire hydrant", + "N/A", + "stop sign", + "parking meter", + "bench", + "bird", + "cat", + "dog", + "horse", + "sheep", + "cow", + "elephant", + "bear", + "zebra", + "giraffe", + "N/A", + "backpack", + "umbrella", + "N/A", + "N/A", + "handbag", + "tie", + "suitcase", + "frisbee", + "skis", + "snowboard", + "sports ball", + "kite", + "baseball bat", + "baseball glove", + "skateboard", + "surfboard", + "tennis racket", + "bottle", + "N/A", + "wine glass", + "cup", + "fork", + "knife", + "spoon", + "bowl", + "banana", + "apple", + "sandwich", + "orange", + "broccoli", + "carrot", + "hot dog", + "pizza", + "donut", + "cake", + "chair", + "couch", + "potted plant", + "bed", + "N/A", + "dining table", + "N/A", + "N/A", + "toilet", + "N/A", + "tv", + "laptop", + "mouse", + "remote", + "keyboard", + "cell phone", + "microwave", + "oven", + "toaster", + "sink", + "refrigerator", + "N/A", + "book", + "clock", + "vase", + "scissors", + "teddy bear", + "hair drier", + "toothbrush", +] + +# To be replaced with torchvision.datasets.info("coco_kp") +_COCO_PERSON_CATEGORIES = ["no person", "person"] +_COCO_PERSON_KEYPOINT_NAMES = [ + "nose", + "left_eye", + "right_eye", + "left_ear", + "right_ear", + "left_shoulder", + "right_shoulder", + "left_elbow", + "right_elbow", + "left_wrist", + "right_wrist", + "left_hip", + "right_hip", + "left_knee", + "right_knee", + "left_ankle", + "right_ankle", +] + +# To be replaced with torchvision.datasets.info("voc").categories +_VOC_CATEGORIES = [ + "__background__", + "aeroplane", + "bicycle", + "bird", + "boat", + "bottle", + "bus", + "car", + "cat", + "chair", + "cow", + "diningtable", + "dog", + "horse", + "motorbike", + "person", + "pottedplant", + "sheep", + "sofa", + "train", + "tvmonitor", +] + +# To be replaced with torchvision.datasets.info("kinetics400").categories +_KINETICS400_CATEGORIES = [ + "abseiling", + "air drumming", + "answering questions", + "applauding", + "applying cream", + "archery", + "arm wrestling", + "arranging flowers", + "assembling computer", + "auctioning", + "baby waking up", + "baking cookies", + "balloon blowing", + "bandaging", + "barbequing", + "bartending", + "beatboxing", + "bee keeping", + "belly dancing", + "bench pressing", + "bending back", + "bending metal", + "biking through snow", + "blasting sand", + "blowing glass", + "blowing leaves", + "blowing nose", + "blowing out candles", + "bobsledding", + "bookbinding", + "bouncing on trampoline", + "bowling", + "braiding hair", + "breading or breadcrumbing", + "breakdancing", + "brush painting", + "brushing hair", + "brushing teeth", + "building cabinet", + "building shed", + "bungee jumping", + "busking", + "canoeing or kayaking", + "capoeira", + "carrying baby", + "cartwheeling", + "carving pumpkin", + "catching fish", + "catching or throwing baseball", + "catching or throwing frisbee", + "catching or throwing softball", + "celebrating", + "changing oil", + "changing wheel", + "checking tires", + "cheerleading", + "chopping wood", + "clapping", + "clay pottery making", + "clean and jerk", + "cleaning floor", + "cleaning gutters", + "cleaning pool", + "cleaning shoes", + "cleaning toilet", + "cleaning windows", + "climbing a rope", + "climbing ladder", + "climbing tree", + "contact juggling", + "cooking chicken", + "cooking egg", + "cooking on campfire", + "cooking sausages", + "counting money", + "country line dancing", + "cracking neck", + "crawling baby", + "crossing river", + "crying", + "curling hair", + "cutting nails", + "cutting pineapple", + "cutting watermelon", + "dancing ballet", + "dancing charleston", + "dancing gangnam style", + "dancing macarena", + "deadlifting", + "decorating the christmas tree", + "digging", + "dining", + "disc golfing", + "diving cliff", + "dodgeball", + "doing aerobics", + "doing laundry", + "doing nails", + "drawing", + "dribbling basketball", + "drinking", + "drinking beer", + "drinking shots", + "driving car", + "driving tractor", + "drop kicking", + "drumming fingers", + "dunking basketball", + "dying hair", + "eating burger", + "eating cake", + "eating carrots", + "eating chips", + "eating doughnuts", + "eating hotdog", + "eating ice cream", + "eating spaghetti", + "eating watermelon", + "egg hunting", + "exercising arm", + "exercising with an exercise ball", + "extinguishing fire", + "faceplanting", + "feeding birds", + "feeding fish", + "feeding goats", + "filling eyebrows", + "finger snapping", + "fixing hair", + "flipping pancake", + "flying kite", + "folding clothes", + "folding napkins", + "folding paper", + "front raises", + "frying vegetables", + "garbage collecting", + "gargling", + "getting a haircut", + "getting a tattoo", + "giving or receiving award", + "golf chipping", + "golf driving", + "golf putting", + "grinding meat", + "grooming dog", + "grooming horse", + "gymnastics tumbling", + "hammer throw", + "headbanging", + "headbutting", + "high jump", + "high kick", + "hitting baseball", + "hockey stop", + "holding snake", + "hopscotch", + "hoverboarding", + "hugging", + "hula hooping", + "hurdling", + "hurling (sport)", + "ice climbing", + "ice fishing", + "ice skating", + "ironing", + "javelin throw", + "jetskiing", + "jogging", + "juggling balls", + "juggling fire", + "juggling soccer ball", + "jumping into pool", + "jumpstyle dancing", + "kicking field goal", + "kicking soccer ball", + "kissing", + "kitesurfing", + "knitting", + "krumping", + "laughing", + "laying bricks", + "long jump", + "lunge", + "making a cake", + "making a sandwich", + "making bed", + "making jewelry", + "making pizza", + "making snowman", + "making sushi", + "making tea", + "marching", + "massaging back", + "massaging feet", + "massaging legs", + "massaging person's head", + "milking cow", + "mopping floor", + "motorcycling", + "moving furniture", + "mowing lawn", + "news anchoring", + "opening bottle", + "opening present", + "paragliding", + "parasailing", + "parkour", + "passing American football (in game)", + "passing American football (not in game)", + "peeling apples", + "peeling potatoes", + "petting animal (not cat)", + "petting cat", + "picking fruit", + "planting trees", + "plastering", + "playing accordion", + "playing badminton", + "playing bagpipes", + "playing basketball", + "playing bass guitar", + "playing cards", + "playing cello", + "playing chess", + "playing clarinet", + "playing controller", + "playing cricket", + "playing cymbals", + "playing didgeridoo", + "playing drums", + "playing flute", + "playing guitar", + "playing harmonica", + "playing harp", + "playing ice hockey", + "playing keyboard", + "playing kickball", + "playing monopoly", + "playing organ", + "playing paintball", + "playing piano", + "playing poker", + "playing recorder", + "playing saxophone", + "playing squash or racquetball", + "playing tennis", + "playing trombone", + "playing trumpet", + "playing ukulele", + "playing violin", + "playing volleyball", + "playing xylophone", + "pole vault", + "presenting weather forecast", + "pull ups", + "pumping fist", + "pumping gas", + "punching bag", + "punching person (boxing)", + "push up", + "pushing car", + "pushing cart", + "pushing wheelchair", + "reading book", + "reading newspaper", + "recording music", + "riding a bike", + "riding camel", + "riding elephant", + "riding mechanical bull", + "riding mountain bike", + "riding mule", + "riding or walking with horse", + "riding scooter", + "riding unicycle", + "ripping paper", + "robot dancing", + "rock climbing", + "rock scissors paper", + "roller skating", + "running on treadmill", + "sailing", + "salsa dancing", + "sanding floor", + "scrambling eggs", + "scuba diving", + "setting table", + "shaking hands", + "shaking head", + "sharpening knives", + "sharpening pencil", + "shaving head", + "shaving legs", + "shearing sheep", + "shining shoes", + "shooting basketball", + "shooting goal (soccer)", + "shot put", + "shoveling snow", + "shredding paper", + "shuffling cards", + "side kick", + "sign language interpreting", + "singing", + "situp", + "skateboarding", + "ski jumping", + "skiing (not slalom or crosscountry)", + "skiing crosscountry", + "skiing slalom", + "skipping rope", + "skydiving", + "slacklining", + "slapping", + "sled dog racing", + "smoking", + "smoking hookah", + "snatch weight lifting", + "sneezing", + "sniffing", + "snorkeling", + "snowboarding", + "snowkiting", + "snowmobiling", + "somersaulting", + "spinning poi", + "spray painting", + "spraying", + "springboard diving", + "squat", + "sticking tongue out", + "stomping grapes", + "stretching arm", + "stretching leg", + "strumming guitar", + "surfing crowd", + "surfing water", + "sweeping floor", + "swimming backstroke", + "swimming breast stroke", + "swimming butterfly stroke", + "swing dancing", + "swinging legs", + "swinging on something", + "sword fighting", + "tai chi", + "taking a shower", + "tango dancing", + "tap dancing", + "tapping guitar", + "tapping pen", + "tasting beer", + "tasting food", + "testifying", + "texting", + "throwing axe", + "throwing ball", + "throwing discus", + "tickling", + "tobogganing", + "tossing coin", + "tossing salad", + "training dog", + "trapezing", + "trimming or shaving beard", + "trimming trees", + "triple jump", + "tying bow tie", + "tying knot (not on a tie)", + "tying tie", + "unboxing", + "unloading truck", + "using computer", + "using remote controller (not gaming)", + "using segway", + "vault", + "waiting in line", + "walking the dog", + "washing dishes", + "washing feet", + "washing hair", + "washing hands", + "water skiing", + "water sliding", + "watering plants", + "waxing back", + "waxing chest", + "waxing eyebrows", + "waxing legs", + "weaving basket", + "welding", + "whistling", + "windsurfing", + "wrapping present", + "wrestling", + "writing", + "yawning", + "yoga", + "zumba", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..61b9a069f98f1b2114c72a5e16d12ab88b9f2400 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/_utils.py @@ -0,0 +1,256 @@ +import functools +import inspect +import warnings +from collections import OrderedDict +from typing import Any, Callable, Optional, TypeVar, Union + +from torch import nn + +from .._utils import sequence_to_str +from ._api import WeightsEnum + + +class IntermediateLayerGetter(nn.ModuleDict): + """ + Module wrapper that returns intermediate layers from a model + + It has a strong assumption that the modules have been registered + into the model in the same order as they are used. + This means that one should **not** reuse the same nn.Module + twice in the forward if you want this to work. + + Additionally, it is only able to query submodules that are directly + assigned to the model. So if `model` is passed, `model.feature1` can + be returned, but not `model.feature1.layer2`. + + Args: + model (nn.Module): model on which we will extract the features + return_layers (Dict[name, new_name]): a dict containing the names + of the modules for which the activations will be returned as + the key of the dict, and the value of the dict is the name + of the returned activation (which the user can specify). + + Examples:: + + >>> m = torchvision.models.resnet18(weights=ResNet18_Weights.DEFAULT) + >>> # extract layer1 and layer3, giving as names `feat1` and feat2` + >>> new_m = torchvision.models._utils.IntermediateLayerGetter(m, + >>> {'layer1': 'feat1', 'layer3': 'feat2'}) + >>> out = new_m(torch.rand(1, 3, 224, 224)) + >>> print([(k, v.shape) for k, v in out.items()]) + >>> [('feat1', torch.Size([1, 64, 56, 56])), + >>> ('feat2', torch.Size([1, 256, 14, 14]))] + """ + + _version = 2 + __annotations__ = { + "return_layers": dict[str, str], + } + + def __init__(self, model: nn.Module, return_layers: dict[str, str]) -> None: + if not set(return_layers).issubset([name for name, _ in model.named_children()]): + raise ValueError("return_layers are not present in model") + orig_return_layers = return_layers + return_layers = {str(k): str(v) for k, v in return_layers.items()} + layers = OrderedDict() + for name, module in model.named_children(): + layers[name] = module + if name in return_layers: + del return_layers[name] + if not return_layers: + break + + super().__init__(layers) + self.return_layers = orig_return_layers + + def forward(self, x): + out = OrderedDict() + for name, module in self.items(): + x = module(x) + if name in self.return_layers: + out_name = self.return_layers[name] + out[out_name] = x + return out + + +def _make_divisible(v: float, divisor: int, min_value: Optional[int] = None) -> int: + """ + This function is taken from the original tf repo. + It ensures that all layers have a channel number that is divisible by 8 + It can be seen here: + https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py + """ + if min_value is None: + min_value = divisor + new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) + # Make sure that round down does not go down by more than 10%. + if new_v < 0.9 * v: + new_v += divisor + return new_v + + +D = TypeVar("D") + + +def kwonly_to_pos_or_kw(fn: Callable[..., D]) -> Callable[..., D]: + """Decorates a function that uses keyword only parameters to also allow them being passed as positionals. + + For example, consider the use case of changing the signature of ``old_fn`` into the one from ``new_fn``: + + .. code:: + + def old_fn(foo, bar, baz=None): + ... + + def new_fn(foo, *, bar, baz=None): + ... + + Calling ``old_fn("foo", "bar, "baz")`` was valid, but the same call is no longer valid with ``new_fn``. To keep BC + and at the same time warn the user of the deprecation, this decorator can be used: + + .. code:: + + @kwonly_to_pos_or_kw + def new_fn(foo, *, bar, baz=None): + ... + + new_fn("foo", "bar, "baz") + """ + params = inspect.signature(fn).parameters + + try: + keyword_only_start_idx = next( + idx for idx, param in enumerate(params.values()) if param.kind == param.KEYWORD_ONLY + ) + except StopIteration: + raise TypeError(f"Found no keyword-only parameter on function '{fn.__name__}'") from None + + keyword_only_params = tuple(inspect.signature(fn).parameters)[keyword_only_start_idx:] + + @functools.wraps(fn) + def wrapper(*args: Any, **kwargs: Any) -> D: + args, keyword_only_args = args[:keyword_only_start_idx], args[keyword_only_start_idx:] + if keyword_only_args: + keyword_only_kwargs = dict(zip(keyword_only_params, keyword_only_args)) + warnings.warn( + f"Using {sequence_to_str(tuple(keyword_only_kwargs.keys()), separate_last='and ')} as positional " + f"parameter(s) is deprecated since 0.13 and may be removed in the future. Please use keyword parameter(s) " + f"instead." + ) + kwargs.update(keyword_only_kwargs) + + return fn(*args, **kwargs) + + return wrapper + + +W = TypeVar("W", bound=WeightsEnum) +M = TypeVar("M", bound=nn.Module) +V = TypeVar("V") + + +def handle_legacy_interface(**weights: tuple[str, Union[Optional[W], Callable[[dict[str, Any]], Optional[W]]]]): + """Decorates a model builder with the new interface to make it compatible with the old. + + In particular this handles two things: + + 1. Allows positional parameters again, but emits a deprecation warning in case they are used. See + :func:`torchvision.prototype.utils._internal.kwonly_to_pos_or_kw` for details. + 2. Handles the default value change from ``pretrained=False`` to ``weights=None`` and ``pretrained=True`` to + ``weights=Weights`` and emits a deprecation warning with instructions for the new interface. + + Args: + **weights (Tuple[str, Union[Optional[W], Callable[[Dict[str, Any]], Optional[W]]]]): Deprecated parameter + name and default value for the legacy ``pretrained=True``. The default value can be a callable in which + case it will be called with a dictionary of the keyword arguments. The only key that is guaranteed to be in + the dictionary is the deprecated parameter name passed as first element in the tuple. All other parameters + should be accessed with :meth:`~dict.get`. + """ + + def outer_wrapper(builder: Callable[..., M]) -> Callable[..., M]: + @kwonly_to_pos_or_kw + @functools.wraps(builder) + def inner_wrapper(*args: Any, **kwargs: Any) -> M: + for weights_param, (pretrained_param, default) in weights.items(): # type: ignore[union-attr] + # If neither the weights nor the pretrained parameter as passed, or the weights argument already use + # the new style arguments, there is nothing to do. Note that we cannot use `None` as sentinel for the + # weight argument, since it is a valid value. + sentinel = object() + weights_arg = kwargs.get(weights_param, sentinel) + if ( + (weights_param not in kwargs and pretrained_param not in kwargs) + or isinstance(weights_arg, WeightsEnum) + or (isinstance(weights_arg, str) and weights_arg != "legacy") + or weights_arg is None + ): + continue + + # If the pretrained parameter was passed as positional argument, it is now mapped to + # `kwargs[weights_param]`. This happens because the @kwonly_to_pos_or_kw decorator uses the current + # signature to infer the names of positionally passed arguments and thus has no knowledge that there + # used to be a pretrained parameter. + pretrained_positional = weights_arg is not sentinel + if pretrained_positional: + # We put the pretrained argument under its legacy name in the keyword argument dictionary to have + # unified access to the value if the default value is a callable. + kwargs[pretrained_param] = pretrained_arg = kwargs.pop(weights_param) + else: + pretrained_arg = kwargs[pretrained_param] + + if pretrained_arg: + default_weights_arg = default(kwargs) if callable(default) else default + if not isinstance(default_weights_arg, WeightsEnum): + raise ValueError(f"No weights available for model {builder.__name__}") + else: + default_weights_arg = None + + if not pretrained_positional: + warnings.warn( + f"The parameter '{pretrained_param}' is deprecated since 0.13 and may be removed in the future, " + f"please use '{weights_param}' instead." + ) + + msg = ( + f"Arguments other than a weight enum or `None` for '{weights_param}' are deprecated since 0.13 and " + f"may be removed in the future. " + f"The current behavior is equivalent to passing `{weights_param}={default_weights_arg}`." + ) + if pretrained_arg: + msg = ( + f"{msg} You can also use `{weights_param}={type(default_weights_arg).__name__}.DEFAULT` " + f"to get the most up-to-date weights." + ) + warnings.warn(msg) + + del kwargs[pretrained_param] + kwargs[weights_param] = default_weights_arg + + return builder(*args, **kwargs) + + return inner_wrapper + + return outer_wrapper + + +def _ovewrite_named_param(kwargs: dict[str, Any], param: str, new_value: V) -> None: + if param in kwargs: + if kwargs[param] != new_value: + raise ValueError(f"The parameter '{param}' expected value {new_value} but got {kwargs[param]} instead.") + else: + kwargs[param] = new_value + + +def _ovewrite_value_param(param: str, actual: Optional[V], expected: V) -> V: + if actual is not None: + if actual != expected: + raise ValueError(f"The parameter '{param}' expected value {expected} but got {actual} instead.") + return expected + + +class _ModelURLs(dict): + def __getitem__(self, item): + warnings.warn( + "Accessing the model URLs via the internal dictionary of the module is deprecated since 0.13 and may " + "be removed in the future. Please access them via the appropriate Weights Enum instead." + ) + return super().__getitem__(item) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/alexnet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/alexnet.py new file mode 100644 index 0000000000000000000000000000000000000000..f85acbeb2148d2aa8f289808e61aa61e2d68e2f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/alexnet.py @@ -0,0 +1,119 @@ +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["AlexNet", "AlexNet_Weights", "alexnet"] + + +class AlexNet(nn.Module): + def __init__(self, num_classes: int = 1000, dropout: float = 0.5) -> None: + super().__init__() + _log_api_usage_once(self) + self.features = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + nn.Conv2d(64, 192, kernel_size=5, padding=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + nn.Conv2d(192, 384, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(384, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(256, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + ) + self.avgpool = nn.AdaptiveAvgPool2d((6, 6)) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), + nn.Linear(256 * 6 * 6, 4096), + nn.ReLU(inplace=True), + nn.Dropout(p=dropout), + nn.Linear(4096, 4096), + nn.ReLU(inplace=True), + nn.Linear(4096, num_classes), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.classifier(x) + return x + + +class AlexNet_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/alexnet-owt-7be5be79.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 61100840, + "min_size": (63, 63), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#alexnet-and-vgg", + "_metrics": { + "ImageNet-1K": { + "acc@1": 56.522, + "acc@5": 79.066, + } + }, + "_ops": 0.714, + "_file_size": 233.087, + "_docs": """ + These weights reproduce closely the results of the paper using a simplified training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", AlexNet_Weights.IMAGENET1K_V1)) +def alexnet(*, weights: Optional[AlexNet_Weights] = None, progress: bool = True, **kwargs: Any) -> AlexNet: + """AlexNet model architecture from `One weird trick for parallelizing convolutional neural networks `__. + + .. note:: + AlexNet was originally introduced in the `ImageNet Classification with + Deep Convolutional Neural Networks + `__ + paper. Our implementation is based instead on the "One weird trick" + paper above. + + Args: + weights (:class:`~torchvision.models.AlexNet_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.AlexNet_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.squeezenet.AlexNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.AlexNet_Weights + :members: + """ + + weights = AlexNet_Weights.verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = AlexNet(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/convnext.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/convnext.py new file mode 100644 index 0000000000000000000000000000000000000000..3264cb1fd0ce43ca40cad4e8f0ca46e9cf1703db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/convnext.py @@ -0,0 +1,415 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor +from torch.nn import functional as F + +from ..ops.misc import Conv2dNormActivation, Permute +from ..ops.stochastic_depth import StochasticDepth +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "ConvNeXt", + "ConvNeXt_Tiny_Weights", + "ConvNeXt_Small_Weights", + "ConvNeXt_Base_Weights", + "ConvNeXt_Large_Weights", + "convnext_tiny", + "convnext_small", + "convnext_base", + "convnext_large", +] + + +class LayerNorm2d(nn.LayerNorm): + def forward(self, x: Tensor) -> Tensor: + x = x.permute(0, 2, 3, 1) + x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + x = x.permute(0, 3, 1, 2) + return x + + +class CNBlock(nn.Module): + def __init__( + self, + dim, + layer_scale: float, + stochastic_depth_prob: float, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-6) + + self.block = nn.Sequential( + nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim, bias=True), + Permute([0, 2, 3, 1]), + norm_layer(dim), + nn.Linear(in_features=dim, out_features=4 * dim, bias=True), + nn.GELU(), + nn.Linear(in_features=4 * dim, out_features=dim, bias=True), + Permute([0, 3, 1, 2]), + ) + self.layer_scale = nn.Parameter(torch.ones(dim, 1, 1) * layer_scale) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + + def forward(self, input: Tensor) -> Tensor: + result = self.layer_scale * self.block(input) + result = self.stochastic_depth(result) + result += input + return result + + +class CNBlockConfig: + # Stores information listed at Section 3 of the ConvNeXt paper + def __init__( + self, + input_channels: int, + out_channels: Optional[int], + num_layers: int, + ) -> None: + self.input_channels = input_channels + self.out_channels = out_channels + self.num_layers = num_layers + + def __repr__(self) -> str: + s = self.__class__.__name__ + "(" + s += "input_channels={input_channels}" + s += ", out_channels={out_channels}" + s += ", num_layers={num_layers}" + s += ")" + return s.format(**self.__dict__) + + +class ConvNeXt(nn.Module): + def __init__( + self, + block_setting: list[CNBlockConfig], + stochastic_depth_prob: float = 0.0, + layer_scale: float = 1e-6, + num_classes: int = 1000, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + **kwargs: Any, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if not block_setting: + raise ValueError("The block_setting should not be empty") + elif not (isinstance(block_setting, Sequence) and all([isinstance(s, CNBlockConfig) for s in block_setting])): + raise TypeError("The block_setting should be List[CNBlockConfig]") + + if block is None: + block = CNBlock + + if norm_layer is None: + norm_layer = partial(LayerNorm2d, eps=1e-6) + + layers: list[nn.Module] = [] + + # Stem + firstconv_output_channels = block_setting[0].input_channels + layers.append( + Conv2dNormActivation( + 3, + firstconv_output_channels, + kernel_size=4, + stride=4, + padding=0, + norm_layer=norm_layer, + activation_layer=None, + bias=True, + ) + ) + + total_stage_blocks = sum(cnf.num_layers for cnf in block_setting) + stage_block_id = 0 + for cnf in block_setting: + # Bottlenecks + stage: list[nn.Module] = [] + for _ in range(cnf.num_layers): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * stage_block_id / (total_stage_blocks - 1.0) + stage.append(block(cnf.input_channels, layer_scale, sd_prob)) + stage_block_id += 1 + layers.append(nn.Sequential(*stage)) + if cnf.out_channels is not None: + # Downsampling + layers.append( + nn.Sequential( + norm_layer(cnf.input_channels), + nn.Conv2d(cnf.input_channels, cnf.out_channels, kernel_size=2, stride=2), + ) + ) + + self.features = nn.Sequential(*layers) + self.avgpool = nn.AdaptiveAvgPool2d(1) + + lastblock = block_setting[-1] + lastconv_output_channels = ( + lastblock.out_channels if lastblock.out_channels is not None else lastblock.input_channels + ) + self.classifier = nn.Sequential( + norm_layer(lastconv_output_channels), nn.Flatten(1), nn.Linear(lastconv_output_channels, num_classes) + ) + + for m in self.modules(): + if isinstance(m, (nn.Conv2d, nn.Linear)): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + x = self.features(x) + x = self.avgpool(x) + x = self.classifier(x) + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _convnext( + block_setting: list[CNBlockConfig], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> ConvNeXt: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = ConvNeXt(block_setting, stochastic_depth_prob=stochastic_depth_prob, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (32, 32), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#convnext", + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, +} + + +class ConvNeXt_Tiny_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_tiny-983f1562.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=236), + meta={ + **_COMMON_META, + "num_params": 28589128, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.520, + "acc@5": 96.146, + } + }, + "_ops": 4.456, + "_file_size": 109.119, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ConvNeXt_Small_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_small-0c510722.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=230), + meta={ + **_COMMON_META, + "num_params": 50223688, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.616, + "acc@5": 96.650, + } + }, + "_ops": 8.684, + "_file_size": 191.703, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ConvNeXt_Base_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_base-6075fbad.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 88591464, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.062, + "acc@5": 96.870, + } + }, + "_ops": 15.355, + "_file_size": 338.064, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ConvNeXt_Large_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_large-ea097f82.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 197767336, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.414, + "acc@5": 96.976, + } + }, + "_ops": 34.361, + "_file_size": 754.537, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Tiny_Weights.IMAGENET1K_V1)) +def convnext_tiny(*, weights: Optional[ConvNeXt_Tiny_Weights] = None, progress: bool = True, **kwargs: Any) -> ConvNeXt: + """ConvNeXt Tiny model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Tiny_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Tiny_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Tiny_Weights + :members: + """ + weights = ConvNeXt_Tiny_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(96, 192, 3), + CNBlockConfig(192, 384, 3), + CNBlockConfig(384, 768, 9), + CNBlockConfig(768, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.1) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Small_Weights.IMAGENET1K_V1)) +def convnext_small( + *, weights: Optional[ConvNeXt_Small_Weights] = None, progress: bool = True, **kwargs: Any +) -> ConvNeXt: + """ConvNeXt Small model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Small_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Small_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Small_Weights + :members: + """ + weights = ConvNeXt_Small_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(96, 192, 3), + CNBlockConfig(192, 384, 3), + CNBlockConfig(384, 768, 27), + CNBlockConfig(768, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.4) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Base_Weights.IMAGENET1K_V1)) +def convnext_base(*, weights: Optional[ConvNeXt_Base_Weights] = None, progress: bool = True, **kwargs: Any) -> ConvNeXt: + """ConvNeXt Base model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Base_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Base_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Base_Weights + :members: + """ + weights = ConvNeXt_Base_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(128, 256, 3), + CNBlockConfig(256, 512, 3), + CNBlockConfig(512, 1024, 27), + CNBlockConfig(1024, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.5) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Large_Weights.IMAGENET1K_V1)) +def convnext_large( + *, weights: Optional[ConvNeXt_Large_Weights] = None, progress: bool = True, **kwargs: Any +) -> ConvNeXt: + """ConvNeXt Large model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Large_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Large_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Large_Weights + :members: + """ + weights = ConvNeXt_Large_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(192, 384, 3), + CNBlockConfig(384, 768, 3), + CNBlockConfig(768, 1536, 27), + CNBlockConfig(1536, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.5) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/densenet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/densenet.py new file mode 100644 index 0000000000000000000000000000000000000000..06457f7b09e9d383327b0bc41304a412eb6b7839 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/densenet.py @@ -0,0 +1,448 @@ +import re +from collections import OrderedDict +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as cp +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + +__all__ = [ + "DenseNet", + "DenseNet121_Weights", + "DenseNet161_Weights", + "DenseNet169_Weights", + "DenseNet201_Weights", + "densenet121", + "densenet161", + "densenet169", + "densenet201", +] + + +class _DenseLayer(nn.Module): + def __init__( + self, num_input_features: int, growth_rate: int, bn_size: int, drop_rate: float, memory_efficient: bool = False + ) -> None: + super().__init__() + self.norm1 = nn.BatchNorm2d(num_input_features) + self.relu1 = nn.ReLU(inplace=True) + self.conv1 = nn.Conv2d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False) + + self.norm2 = nn.BatchNorm2d(bn_size * growth_rate) + self.relu2 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False) + + self.drop_rate = float(drop_rate) + self.memory_efficient = memory_efficient + + def bn_function(self, inputs: list[Tensor]) -> Tensor: + concated_features = torch.cat(inputs, 1) + bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features))) # noqa: T484 + return bottleneck_output + + # todo: rewrite when torchscript supports any + def any_requires_grad(self, input: list[Tensor]) -> bool: + for tensor in input: + if tensor.requires_grad: + return True + return False + + @torch.jit.unused # noqa: T484 + def call_checkpoint_bottleneck(self, input: list[Tensor]) -> Tensor: + def closure(*inputs): + return self.bn_function(inputs) + + return cp.checkpoint(closure, *input, use_reentrant=False) + + @torch.jit._overload_method # noqa: F811 + def forward(self, input: list[Tensor]) -> Tensor: # noqa: F811 + pass + + @torch.jit._overload_method # noqa: F811 + def forward(self, input: Tensor) -> Tensor: # noqa: F811 + pass + + # torchscript does not yet support *args, so we overload method + # allowing it to take either a List[Tensor] or single Tensor + def forward(self, input: Tensor) -> Tensor: # noqa: F811 + if isinstance(input, Tensor): + prev_features = [input] + else: + prev_features = input + + if self.memory_efficient and self.any_requires_grad(prev_features): + if torch.jit.is_scripting(): + raise Exception("Memory Efficient not supported in JIT") + + bottleneck_output = self.call_checkpoint_bottleneck(prev_features) + else: + bottleneck_output = self.bn_function(prev_features) + + new_features = self.conv2(self.relu2(self.norm2(bottleneck_output))) + if self.drop_rate > 0: + new_features = F.dropout(new_features, p=self.drop_rate, training=self.training) + return new_features + + +class _DenseBlock(nn.ModuleDict): + _version = 2 + + def __init__( + self, + num_layers: int, + num_input_features: int, + bn_size: int, + growth_rate: int, + drop_rate: float, + memory_efficient: bool = False, + ) -> None: + super().__init__() + for i in range(num_layers): + layer = _DenseLayer( + num_input_features + i * growth_rate, + growth_rate=growth_rate, + bn_size=bn_size, + drop_rate=drop_rate, + memory_efficient=memory_efficient, + ) + self.add_module("denselayer%d" % (i + 1), layer) + + def forward(self, init_features: Tensor) -> Tensor: + features = [init_features] + for name, layer in self.items(): + new_features = layer(features) + features.append(new_features) + return torch.cat(features, 1) + + +class _Transition(nn.Sequential): + def __init__(self, num_input_features: int, num_output_features: int) -> None: + super().__init__() + self.norm = nn.BatchNorm2d(num_input_features) + self.relu = nn.ReLU(inplace=True) + self.conv = nn.Conv2d(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False) + self.pool = nn.AvgPool2d(kernel_size=2, stride=2) + + +class DenseNet(nn.Module): + r"""Densenet-BC model class, based on + `"Densely Connected Convolutional Networks" `_. + + Args: + growth_rate (int) - how many filters to add each layer (`k` in paper) + block_config (list of 4 ints) - how many layers in each pooling block + num_init_features (int) - the number of filters to learn in the first convolution layer + bn_size (int) - multiplicative factor for number of bottle neck layers + (i.e. bn_size * k features in the bottleneck layer) + drop_rate (float) - dropout rate after each dense layer + num_classes (int) - number of classification classes + memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, + but slower. Default: *False*. See `"paper" `_. + """ + + def __init__( + self, + growth_rate: int = 32, + block_config: tuple[int, int, int, int] = (6, 12, 24, 16), + num_init_features: int = 64, + bn_size: int = 4, + drop_rate: float = 0, + num_classes: int = 1000, + memory_efficient: bool = False, + ) -> None: + + super().__init__() + _log_api_usage_once(self) + + # First convolution + self.features = nn.Sequential( + OrderedDict( + [ + ("conv0", nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)), + ("norm0", nn.BatchNorm2d(num_init_features)), + ("relu0", nn.ReLU(inplace=True)), + ("pool0", nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), + ] + ) + ) + + # Each denseblock + num_features = num_init_features + for i, num_layers in enumerate(block_config): + block = _DenseBlock( + num_layers=num_layers, + num_input_features=num_features, + bn_size=bn_size, + growth_rate=growth_rate, + drop_rate=drop_rate, + memory_efficient=memory_efficient, + ) + self.features.add_module("denseblock%d" % (i + 1), block) + num_features = num_features + num_layers * growth_rate + if i != len(block_config) - 1: + trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2) + self.features.add_module("transition%d" % (i + 1), trans) + num_features = num_features // 2 + + # Final batch norm + self.features.add_module("norm5", nn.BatchNorm2d(num_features)) + + # Linear layer + self.classifier = nn.Linear(num_features, num_classes) + + # Official init from torch repo. + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.constant_(m.bias, 0) + + def forward(self, x: Tensor) -> Tensor: + features = self.features(x) + out = F.relu(features, inplace=True) + out = F.adaptive_avg_pool2d(out, (1, 1)) + out = torch.flatten(out, 1) + out = self.classifier(out) + return out + + +def _load_state_dict(model: nn.Module, weights: WeightsEnum, progress: bool) -> None: + # '.'s are no longer allowed in module names, but previous _DenseLayer + # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'. + # They are also in the checkpoints in model_urls. This pattern is used + # to find such keys. + pattern = re.compile( + r"^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$" + ) + + state_dict = weights.get_state_dict(progress=progress, check_hash=True) + for key in list(state_dict.keys()): + res = pattern.match(key) + if res: + new_key = res.group(1) + res.group(2) + state_dict[new_key] = state_dict[key] + del state_dict[key] + model.load_state_dict(state_dict) + + +def _densenet( + growth_rate: int, + block_config: tuple[int, int, int, int], + num_init_features: int, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> DenseNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = DenseNet(growth_rate, block_config, num_init_features, **kwargs) + + if weights is not None: + _load_state_dict(model=model, weights=weights, progress=progress) + + return model + + +_COMMON_META = { + "min_size": (29, 29), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/pull/116", + "_docs": """These weights are ported from LuaTorch.""", +} + + +class DenseNet121_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet121-a639ec97.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 7978856, + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.434, + "acc@5": 91.972, + } + }, + "_ops": 2.834, + "_file_size": 30.845, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class DenseNet161_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet161-8d451a50.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 28681000, + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.138, + "acc@5": 93.560, + } + }, + "_ops": 7.728, + "_file_size": 110.369, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class DenseNet169_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet169-b2777c0a.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 14149480, + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.600, + "acc@5": 92.806, + } + }, + "_ops": 3.36, + "_file_size": 54.708, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class DenseNet201_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet201-c1103571.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 20013928, + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.896, + "acc@5": 93.370, + } + }, + "_ops": 4.291, + "_file_size": 77.373, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet121_Weights.IMAGENET1K_V1)) +def densenet121(*, weights: Optional[DenseNet121_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-121 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet121_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet121_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet121_Weights + :members: + """ + weights = DenseNet121_Weights.verify(weights) + + return _densenet(32, (6, 12, 24, 16), 64, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet161_Weights.IMAGENET1K_V1)) +def densenet161(*, weights: Optional[DenseNet161_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-161 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet161_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet161_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet161_Weights + :members: + """ + weights = DenseNet161_Weights.verify(weights) + + return _densenet(48, (6, 12, 36, 24), 96, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet169_Weights.IMAGENET1K_V1)) +def densenet169(*, weights: Optional[DenseNet169_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-169 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet169_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet169_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet169_Weights + :members: + """ + weights = DenseNet169_Weights.verify(weights) + + return _densenet(32, (6, 12, 32, 32), 64, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet201_Weights.IMAGENET1K_V1)) +def densenet201(*, weights: Optional[DenseNet201_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-201 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet201_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet201_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet201_Weights + :members: + """ + weights = DenseNet201_Weights.verify(weights) + + return _densenet(32, (6, 12, 48, 32), 64, weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4146651c737971cc5a883b6750f2ded3051bc8ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/__init__.py @@ -0,0 +1,7 @@ +from .faster_rcnn import * +from .fcos import * +from .keypoint_rcnn import * +from .mask_rcnn import * +from .retinanet import * +from .ssd import * +from .ssdlite import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..805c05a92ffb074c123540fcd36751d00a454dde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/_utils.py @@ -0,0 +1,539 @@ +import math +from collections import OrderedDict +from typing import Optional + +import torch +from torch import nn, Tensor +from torch.nn import functional as F +from torchvision.ops import complete_box_iou_loss, distance_box_iou_loss, FrozenBatchNorm2d, generalized_box_iou_loss + + +class BalancedPositiveNegativeSampler: + """ + This class samples batches, ensuring that they contain a fixed proportion of positives + """ + + def __init__(self, batch_size_per_image: int, positive_fraction: float) -> None: + """ + Args: + batch_size_per_image (int): number of elements to be selected per image + positive_fraction (float): percentage of positive elements per batch + """ + self.batch_size_per_image = batch_size_per_image + self.positive_fraction = positive_fraction + + def __call__(self, matched_idxs: list[Tensor]) -> tuple[list[Tensor], list[Tensor]]: + """ + Args: + matched_idxs: list of tensors containing -1, 0 or positive values. + Each tensor corresponds to a specific image. + -1 values are ignored, 0 are considered as negatives and > 0 as + positives. + + Returns: + pos_idx (list[tensor]) + neg_idx (list[tensor]) + + Returns two lists of binary masks for each image. + The first list contains the positive elements that were selected, + and the second list the negative example. + """ + pos_idx = [] + neg_idx = [] + for matched_idxs_per_image in matched_idxs: + positive = torch.where(matched_idxs_per_image >= 1)[0] + negative = torch.where(matched_idxs_per_image == 0)[0] + + num_pos = int(self.batch_size_per_image * self.positive_fraction) + # protect against not enough positive examples + num_pos = min(positive.numel(), num_pos) + num_neg = self.batch_size_per_image - num_pos + # protect against not enough negative examples + num_neg = min(negative.numel(), num_neg) + + # randomly select positive and negative examples + perm1 = torch.randperm(positive.numel(), device=positive.device)[:num_pos] + perm2 = torch.randperm(negative.numel(), device=negative.device)[:num_neg] + + pos_idx_per_image = positive[perm1] + neg_idx_per_image = negative[perm2] + + # create binary mask from indices + pos_idx_per_image_mask = torch.zeros_like(matched_idxs_per_image, dtype=torch.uint8) + neg_idx_per_image_mask = torch.zeros_like(matched_idxs_per_image, dtype=torch.uint8) + + pos_idx_per_image_mask[pos_idx_per_image] = 1 + neg_idx_per_image_mask[neg_idx_per_image] = 1 + + pos_idx.append(pos_idx_per_image_mask) + neg_idx.append(neg_idx_per_image_mask) + + return pos_idx, neg_idx + + +@torch.jit._script_if_tracing +def encode_boxes(reference_boxes: Tensor, proposals: Tensor, weights: Tensor) -> Tensor: + """ + Encode a set of proposals with respect to some + reference boxes + + Args: + reference_boxes (Tensor): reference boxes + proposals (Tensor): boxes to be encoded + weights (Tensor[4]): the weights for ``(x, y, w, h)`` + """ + + # perform some unpacking to make it JIT-fusion friendly + wx = weights[0] + wy = weights[1] + ww = weights[2] + wh = weights[3] + + proposals_x1 = proposals[:, 0].unsqueeze(1) + proposals_y1 = proposals[:, 1].unsqueeze(1) + proposals_x2 = proposals[:, 2].unsqueeze(1) + proposals_y2 = proposals[:, 3].unsqueeze(1) + + reference_boxes_x1 = reference_boxes[:, 0].unsqueeze(1) + reference_boxes_y1 = reference_boxes[:, 1].unsqueeze(1) + reference_boxes_x2 = reference_boxes[:, 2].unsqueeze(1) + reference_boxes_y2 = reference_boxes[:, 3].unsqueeze(1) + + # implementation starts here + ex_widths = proposals_x2 - proposals_x1 + ex_heights = proposals_y2 - proposals_y1 + ex_ctr_x = proposals_x1 + 0.5 * ex_widths + ex_ctr_y = proposals_y1 + 0.5 * ex_heights + + gt_widths = reference_boxes_x2 - reference_boxes_x1 + gt_heights = reference_boxes_y2 - reference_boxes_y1 + gt_ctr_x = reference_boxes_x1 + 0.5 * gt_widths + gt_ctr_y = reference_boxes_y1 + 0.5 * gt_heights + + targets_dx = wx * (gt_ctr_x - ex_ctr_x) / ex_widths + targets_dy = wy * (gt_ctr_y - ex_ctr_y) / ex_heights + targets_dw = ww * torch.log(gt_widths / ex_widths) + targets_dh = wh * torch.log(gt_heights / ex_heights) + + targets = torch.cat((targets_dx, targets_dy, targets_dw, targets_dh), dim=1) + return targets + + +class BoxCoder: + """ + This class encodes and decodes a set of bounding boxes into + the representation used for training the regressors. + """ + + def __init__( + self, weights: tuple[float, float, float, float], bbox_xform_clip: float = math.log(1000.0 / 16) + ) -> None: + """ + Args: + weights (4-element tuple) + bbox_xform_clip (float) + """ + self.weights = weights + self.bbox_xform_clip = bbox_xform_clip + + def encode(self, reference_boxes: list[Tensor], proposals: list[Tensor]) -> list[Tensor]: + boxes_per_image = [len(b) for b in reference_boxes] + reference_boxes = torch.cat(reference_boxes, dim=0) + proposals = torch.cat(proposals, dim=0) + targets = self.encode_single(reference_boxes, proposals) + return targets.split(boxes_per_image, 0) + + def encode_single(self, reference_boxes: Tensor, proposals: Tensor) -> Tensor: + """ + Encode a set of proposals with respect to some + reference boxes + + Args: + reference_boxes (Tensor): reference boxes + proposals (Tensor): boxes to be encoded + """ + dtype = reference_boxes.dtype + device = reference_boxes.device + weights = torch.as_tensor(self.weights, dtype=dtype, device=device) + targets = encode_boxes(reference_boxes, proposals, weights) + + return targets + + def decode(self, rel_codes: Tensor, boxes: list[Tensor]) -> Tensor: + torch._assert( + isinstance(boxes, (list, tuple)), + "This function expects boxes of type list or tuple.", + ) + torch._assert( + isinstance(rel_codes, torch.Tensor), + "This function expects rel_codes of type torch.Tensor.", + ) + boxes_per_image = [b.size(0) for b in boxes] + concat_boxes = torch.cat(boxes, dim=0) + box_sum = 0 + for val in boxes_per_image: + box_sum += val + if box_sum > 0: + rel_codes = rel_codes.reshape(box_sum, -1) + pred_boxes = self.decode_single(rel_codes, concat_boxes) + if box_sum > 0: + pred_boxes = pred_boxes.reshape(box_sum, -1, 4) + return pred_boxes + + def decode_single(self, rel_codes: Tensor, boxes: Tensor) -> Tensor: + """ + From a set of original boxes and encoded relative box offsets, + get the decoded boxes. + + Args: + rel_codes (Tensor): encoded boxes + boxes (Tensor): reference boxes. + """ + + boxes = boxes.to(rel_codes.dtype) + + widths = boxes[:, 2] - boxes[:, 0] + heights = boxes[:, 3] - boxes[:, 1] + ctr_x = boxes[:, 0] + 0.5 * widths + ctr_y = boxes[:, 1] + 0.5 * heights + + wx, wy, ww, wh = self.weights + dx = rel_codes[:, 0::4] / wx + dy = rel_codes[:, 1::4] / wy + dw = rel_codes[:, 2::4] / ww + dh = rel_codes[:, 3::4] / wh + + # Prevent sending too large values into torch.exp() + dw = torch.clamp(dw, max=self.bbox_xform_clip) + dh = torch.clamp(dh, max=self.bbox_xform_clip) + + pred_ctr_x = dx * widths[:, None] + ctr_x[:, None] + pred_ctr_y = dy * heights[:, None] + ctr_y[:, None] + pred_w = torch.exp(dw) * widths[:, None] + pred_h = torch.exp(dh) * heights[:, None] + + # Distance from center to box's corner. + c_to_c_h = torch.tensor(0.5, dtype=pred_ctr_y.dtype, device=pred_h.device) * pred_h + c_to_c_w = torch.tensor(0.5, dtype=pred_ctr_x.dtype, device=pred_w.device) * pred_w + + pred_boxes1 = pred_ctr_x - c_to_c_w + pred_boxes2 = pred_ctr_y - c_to_c_h + pred_boxes3 = pred_ctr_x + c_to_c_w + pred_boxes4 = pred_ctr_y + c_to_c_h + pred_boxes = torch.stack((pred_boxes1, pred_boxes2, pred_boxes3, pred_boxes4), dim=2).flatten(1) + return pred_boxes + + +class BoxLinearCoder: + """ + The linear box-to-box transform defined in FCOS. The transformation is parameterized + by the distance from the center of (square) src box to 4 edges of the target box. + """ + + def __init__(self, normalize_by_size: bool = True) -> None: + """ + Args: + normalize_by_size (bool): normalize deltas by the size of src (anchor) boxes. + """ + self.normalize_by_size = normalize_by_size + + def encode(self, reference_boxes: Tensor, proposals: Tensor) -> Tensor: + """ + Encode a set of proposals with respect to some reference boxes + + Args: + reference_boxes (Tensor): reference boxes + proposals (Tensor): boxes to be encoded + + Returns: + Tensor: the encoded relative box offsets that can be used to + decode the boxes. + + """ + + # get the center of reference_boxes + reference_boxes_ctr_x = 0.5 * (reference_boxes[..., 0] + reference_boxes[..., 2]) + reference_boxes_ctr_y = 0.5 * (reference_boxes[..., 1] + reference_boxes[..., 3]) + + # get box regression transformation deltas + target_l = reference_boxes_ctr_x - proposals[..., 0] + target_t = reference_boxes_ctr_y - proposals[..., 1] + target_r = proposals[..., 2] - reference_boxes_ctr_x + target_b = proposals[..., 3] - reference_boxes_ctr_y + + targets = torch.stack((target_l, target_t, target_r, target_b), dim=-1) + + if self.normalize_by_size: + reference_boxes_w = reference_boxes[..., 2] - reference_boxes[..., 0] + reference_boxes_h = reference_boxes[..., 3] - reference_boxes[..., 1] + reference_boxes_size = torch.stack( + (reference_boxes_w, reference_boxes_h, reference_boxes_w, reference_boxes_h), dim=-1 + ) + targets = targets / reference_boxes_size + return targets + + def decode(self, rel_codes: Tensor, boxes: Tensor) -> Tensor: + """ + From a set of original boxes and encoded relative box offsets, + get the decoded boxes. + + Args: + rel_codes (Tensor): encoded boxes + boxes (Tensor): reference boxes. + + Returns: + Tensor: the predicted boxes with the encoded relative box offsets. + + .. note:: + This method assumes that ``rel_codes`` and ``boxes`` have same size for 0th dimension. i.e. ``len(rel_codes) == len(boxes)``. + + """ + + boxes = boxes.to(dtype=rel_codes.dtype) + + ctr_x = 0.5 * (boxes[..., 0] + boxes[..., 2]) + ctr_y = 0.5 * (boxes[..., 1] + boxes[..., 3]) + + if self.normalize_by_size: + boxes_w = boxes[..., 2] - boxes[..., 0] + boxes_h = boxes[..., 3] - boxes[..., 1] + + list_box_size = torch.stack((boxes_w, boxes_h, boxes_w, boxes_h), dim=-1) + rel_codes = rel_codes * list_box_size + + pred_boxes1 = ctr_x - rel_codes[..., 0] + pred_boxes2 = ctr_y - rel_codes[..., 1] + pred_boxes3 = ctr_x + rel_codes[..., 2] + pred_boxes4 = ctr_y + rel_codes[..., 3] + + pred_boxes = torch.stack((pred_boxes1, pred_boxes2, pred_boxes3, pred_boxes4), dim=-1) + return pred_boxes + + +class Matcher: + """ + This class assigns to each predicted "element" (e.g., a box) a ground-truth + element. Each predicted element will have exactly zero or one matches; each + ground-truth element may be assigned to zero or more predicted elements. + + Matching is based on the MxN match_quality_matrix, that characterizes how well + each (ground-truth, predicted)-pair match. For example, if the elements are + boxes, the matrix may contain box IoU overlap values. + + The matcher returns a tensor of size N containing the index of the ground-truth + element m that matches to prediction n. If there is no match, a negative value + is returned. + """ + + BELOW_LOW_THRESHOLD = -1 + BETWEEN_THRESHOLDS = -2 + + __annotations__ = { + "BELOW_LOW_THRESHOLD": int, + "BETWEEN_THRESHOLDS": int, + } + + def __init__(self, high_threshold: float, low_threshold: float, allow_low_quality_matches: bool = False) -> None: + """ + Args: + high_threshold (float): quality values greater than or equal to + this value are candidate matches. + low_threshold (float): a lower quality threshold used to stratify + matches into three levels: + 1) matches >= high_threshold + 2) BETWEEN_THRESHOLDS matches in [low_threshold, high_threshold) + 3) BELOW_LOW_THRESHOLD matches in [0, low_threshold) + allow_low_quality_matches (bool): if True, produce additional matches + for predictions that have only low-quality match candidates. See + set_low_quality_matches_ for more details. + """ + self.BELOW_LOW_THRESHOLD = -1 + self.BETWEEN_THRESHOLDS = -2 + torch._assert(low_threshold <= high_threshold, "low_threshold should be <= high_threshold") + self.high_threshold = high_threshold + self.low_threshold = low_threshold + self.allow_low_quality_matches = allow_low_quality_matches + + def __call__(self, match_quality_matrix: Tensor) -> Tensor: + """ + Args: + match_quality_matrix (Tensor[float]): an MxN tensor, containing the + pairwise quality between M ground-truth elements and N predicted elements. + + Returns: + matches (Tensor[int64]): an N tensor where N[i] is a matched gt in + [0, M - 1] or a negative value indicating that prediction i could not + be matched. + """ + if match_quality_matrix.numel() == 0: + # empty targets or proposals not supported during training + if match_quality_matrix.shape[0] == 0: + raise ValueError("No ground-truth boxes available for one of the images during training") + else: + raise ValueError("No proposal boxes available for one of the images during training") + + # match_quality_matrix is M (gt) x N (predicted) + # Max over gt elements (dim 0) to find best gt candidate for each prediction + matched_vals, matches = match_quality_matrix.max(dim=0) + if self.allow_low_quality_matches: + all_matches = matches.clone() + else: + all_matches = None # type: ignore[assignment] + + # Assign candidate matches with low quality to negative (unassigned) values + below_low_threshold = matched_vals < self.low_threshold + between_thresholds = (matched_vals >= self.low_threshold) & (matched_vals < self.high_threshold) + matches[below_low_threshold] = self.BELOW_LOW_THRESHOLD + matches[between_thresholds] = self.BETWEEN_THRESHOLDS + + if self.allow_low_quality_matches: + if all_matches is None: + torch._assert(False, "all_matches should not be None") + else: + self.set_low_quality_matches_(matches, all_matches, match_quality_matrix) + + return matches + + def set_low_quality_matches_(self, matches: Tensor, all_matches: Tensor, match_quality_matrix: Tensor) -> None: + """ + Produce additional matches for predictions that have only low-quality matches. + Specifically, for each ground-truth find the set of predictions that have + maximum overlap with it (including ties); for each prediction in that set, if + it is unmatched, then match it to the ground-truth with which it has the highest + quality value. + """ + # For each gt, find the prediction with which it has the highest quality + highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1) + # Find the highest quality match available, even if it is low, including ties + gt_pred_pairs_of_highest_quality = torch.where(match_quality_matrix == highest_quality_foreach_gt[:, None]) + # Example gt_pred_pairs_of_highest_quality: + # (tensor([0, 1, 1, 2, 2, 3, 3, 4, 5, 5]), + # tensor([39796, 32055, 32070, 39190, 40255, 40390, 41455, 45470, 45325, 46390])) + # Each element in the first tensor is a gt index, and each element in second tensor is a prediction index + # Note how gt items 1, 2, 3, and 5 each have two ties + + pred_inds_to_update = gt_pred_pairs_of_highest_quality[1] + matches[pred_inds_to_update] = all_matches[pred_inds_to_update] + + +class SSDMatcher(Matcher): + def __init__(self, threshold: float) -> None: + super().__init__(threshold, threshold, allow_low_quality_matches=False) + + def __call__(self, match_quality_matrix: Tensor) -> Tensor: + matches = super().__call__(match_quality_matrix) + + # For each gt, find the prediction with which it has the highest quality + _, highest_quality_pred_foreach_gt = match_quality_matrix.max(dim=1) + matches[highest_quality_pred_foreach_gt] = torch.arange( + highest_quality_pred_foreach_gt.size(0), dtype=torch.int64, device=highest_quality_pred_foreach_gt.device + ) + + return matches + + +def overwrite_eps(model: nn.Module, eps: float) -> None: + """ + This method overwrites the default eps values of all the + FrozenBatchNorm2d layers of the model with the provided value. + This is necessary to address the BC-breaking change introduced + by the bug-fix at pytorch/vision#2933. The overwrite is applied + only when the pretrained weights are loaded to maintain compatibility + with previous versions. + + Args: + model (nn.Module): The model on which we perform the overwrite. + eps (float): The new value of eps. + """ + for module in model.modules(): + if isinstance(module, FrozenBatchNorm2d): + module.eps = eps + + +def retrieve_out_channels(model: nn.Module, size: tuple[int, int]) -> list[int]: + """ + This method retrieves the number of output channels of a specific model. + + Args: + model (nn.Module): The model for which we estimate the out_channels. + It should return a single Tensor or an OrderedDict[Tensor]. + size (Tuple[int, int]): The size (wxh) of the input. + + Returns: + out_channels (List[int]): A list of the output channels of the model. + """ + in_training = model.training + model.eval() + + with torch.no_grad(): + # Use dummy data to retrieve the feature map sizes to avoid hard-coding their values + device = next(model.parameters()).device + tmp_img = torch.zeros((1, 3, size[1], size[0]), device=device) + features = model(tmp_img) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + out_channels = [x.size(1) for x in features.values()] + + if in_training: + model.train() + + return out_channels + + +@torch.jit.unused +def _fake_cast_onnx(v: Tensor) -> int: + return v # type: ignore[return-value] + + +def _topk_min(input: Tensor, orig_kval: int, axis: int) -> int: + """ + ONNX spec requires the k-value to be less than or equal to the number of inputs along + provided dim. Certain models use the number of elements along a particular axis instead of K + if K exceeds the number of elements along that axis. Previously, python's min() function was + used to determine whether to use the provided k-value or the specified dim axis value. + + However, in cases where the model is being exported in tracing mode, python min() is + static causing the model to be traced incorrectly and eventually fail at the topk node. + In order to avoid this situation, in tracing mode, torch.min() is used instead. + + Args: + input (Tensor): The original input tensor. + orig_kval (int): The provided k-value. + axis(int): Axis along which we retrieve the input size. + + Returns: + min_kval (int): Appropriately selected k-value. + """ + if not torch.jit.is_tracing(): + return min(orig_kval, input.size(axis)) + axis_dim_val = torch._shape_as_tensor(input)[axis].unsqueeze(0) + min_kval = torch.min(torch.cat((torch.tensor([orig_kval], dtype=axis_dim_val.dtype), axis_dim_val), 0)) + return _fake_cast_onnx(min_kval) + + +def _box_loss( + type: str, + box_coder: BoxCoder, + anchors_per_image: Tensor, + matched_gt_boxes_per_image: Tensor, + bbox_regression_per_image: Tensor, + cnf: Optional[dict[str, float]] = None, +) -> Tensor: + torch._assert(type in ["l1", "smooth_l1", "ciou", "diou", "giou"], f"Unsupported loss: {type}") + + if type == "l1": + target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image) + return F.l1_loss(bbox_regression_per_image, target_regression, reduction="sum") + elif type == "smooth_l1": + target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image) + beta = cnf["beta"] if cnf is not None and "beta" in cnf else 1.0 + return F.smooth_l1_loss(bbox_regression_per_image, target_regression, reduction="sum", beta=beta) + else: + bbox_per_image = box_coder.decode_single(bbox_regression_per_image, anchors_per_image) + eps = cnf["eps"] if cnf is not None and "eps" in cnf else 1e-7 + if type == "ciou": + return complete_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps) + if type == "diou": + return distance_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps) + # otherwise giou + return generalized_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/anchor_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/anchor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..05aa7664beadfd60dc572831fa759eca10093fad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/anchor_utils.py @@ -0,0 +1,268 @@ +import math +from typing import Optional + +import torch +from torch import nn, Tensor + +from .image_list import ImageList + + +class AnchorGenerator(nn.Module): + """ + Module that generates anchors for a set of feature maps and + image sizes. + + The module support computing anchors at multiple sizes and aspect ratios + per feature map. This module assumes aspect ratio = height / width for + each anchor. + + sizes and aspect_ratios should have the same number of elements, and it should + correspond to the number of feature maps. + + sizes[i] and aspect_ratios[i] can have an arbitrary number of elements, + and AnchorGenerator will output a set of sizes[i] * aspect_ratios[i] anchors + per spatial location for feature map i. + + Args: + sizes (Tuple[Tuple[int]]): + aspect_ratios (Tuple[Tuple[float]]): + """ + + __annotations__ = { + "cell_anchors": list[torch.Tensor], + } + + def __init__( + self, + sizes=((128, 256, 512),), + aspect_ratios=((0.5, 1.0, 2.0),), + ): + super().__init__() + + if not isinstance(sizes[0], (list, tuple)): + # TODO change this + sizes = tuple((s,) for s in sizes) + if not isinstance(aspect_ratios[0], (list, tuple)): + aspect_ratios = (aspect_ratios,) * len(sizes) + + self.sizes = sizes + self.aspect_ratios = aspect_ratios + self.cell_anchors = [ + self.generate_anchors(size, aspect_ratio) for size, aspect_ratio in zip(sizes, aspect_ratios) + ] + + # TODO: https://github.com/pytorch/pytorch/issues/26792 + # For every (aspect_ratios, scales) combination, output a zero-centered anchor with those values. + # (scales, aspect_ratios) are usually an element of zip(self.scales, self.aspect_ratios) + # This method assumes aspect ratio = height / width for an anchor. + def generate_anchors( + self, + scales: list[int], + aspect_ratios: list[float], + dtype: torch.dtype = torch.float32, + device: torch.device = torch.device("cpu"), + ) -> Tensor: + scales = torch.as_tensor(scales, dtype=dtype, device=device) + aspect_ratios = torch.as_tensor(aspect_ratios, dtype=dtype, device=device) + h_ratios = torch.sqrt(aspect_ratios) + w_ratios = 1 / h_ratios + + ws = (w_ratios[:, None] * scales[None, :]).view(-1) + hs = (h_ratios[:, None] * scales[None, :]).view(-1) + + base_anchors = torch.stack([-ws, -hs, ws, hs], dim=1) / 2 + return base_anchors.round() + + def set_cell_anchors(self, dtype: torch.dtype, device: torch.device): + self.cell_anchors = [cell_anchor.to(dtype=dtype, device=device) for cell_anchor in self.cell_anchors] + + def num_anchors_per_location(self) -> list[int]: + return [len(s) * len(a) for s, a in zip(self.sizes, self.aspect_ratios)] + + # For every combination of (a, (g, s), i) in (self.cell_anchors, zip(grid_sizes, strides), 0:2), + # output g[i] anchors that are s[i] distance apart in direction i, with the same dimensions as a. + def grid_anchors(self, grid_sizes: list[list[int]], strides: list[list[Tensor]]) -> list[Tensor]: + anchors = [] + cell_anchors = self.cell_anchors + torch._assert(cell_anchors is not None, "cell_anchors should not be None") + torch._assert( + len(grid_sizes) == len(strides) == len(cell_anchors), + "Anchors should be Tuple[Tuple[int]] because each feature " + "map could potentially have different sizes and aspect ratios. " + "There needs to be a match between the number of " + "feature maps passed and the number of sizes / aspect ratios specified.", + ) + + for size, stride, base_anchors in zip(grid_sizes, strides, cell_anchors): + grid_height, grid_width = size + stride_height, stride_width = stride + device = base_anchors.device + + # For output anchor, compute [x_center, y_center, x_center, y_center] + shifts_x = torch.arange(0, grid_width, dtype=torch.int32, device=device) * stride_width + shifts_y = torch.arange(0, grid_height, dtype=torch.int32, device=device) * stride_height + shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x, indexing="ij") + shift_x = shift_x.reshape(-1) + shift_y = shift_y.reshape(-1) + shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1) + + # For every (base anchor, output anchor) pair, + # offset each zero-centered base anchor by the center of the output anchor. + anchors.append((shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4)) + + return anchors + + def forward(self, image_list: ImageList, feature_maps: list[Tensor]) -> list[Tensor]: + grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps] + image_size = image_list.tensors.shape[-2:] + dtype, device = feature_maps[0].dtype, feature_maps[0].device + strides = [ + [ + torch.empty((), dtype=torch.int64, device=device).fill_(image_size[0] // g[0]), + torch.empty((), dtype=torch.int64, device=device).fill_(image_size[1] // g[1]), + ] + for g in grid_sizes + ] + self.set_cell_anchors(dtype, device) + anchors_over_all_feature_maps = self.grid_anchors(grid_sizes, strides) + anchors: list[list[torch.Tensor]] = [] + for _ in range(len(image_list.image_sizes)): + anchors_in_image = [anchors_per_feature_map for anchors_per_feature_map in anchors_over_all_feature_maps] + anchors.append(anchors_in_image) + anchors = [torch.cat(anchors_per_image) for anchors_per_image in anchors] + return anchors + + +class DefaultBoxGenerator(nn.Module): + """ + This module generates the default boxes of SSD for a set of feature maps and image sizes. + + Args: + aspect_ratios (List[List[int]]): A list with all the aspect ratios used in each feature map. + min_ratio (float): The minimum scale :math:`\text{s}_{\text{min}}` of the default boxes used in the estimation + of the scales of each feature map. It is used only if the ``scales`` parameter is not provided. + max_ratio (float): The maximum scale :math:`\text{s}_{\text{max}}` of the default boxes used in the estimation + of the scales of each feature map. It is used only if the ``scales`` parameter is not provided. + scales (List[float]], optional): The scales of the default boxes. If not provided it will be estimated using + the ``min_ratio`` and ``max_ratio`` parameters. + steps (List[int]], optional): It's a hyper-parameter that affects the tiling of default boxes. If not provided + it will be estimated from the data. + clip (bool): Whether the standardized values of default boxes should be clipped between 0 and 1. The clipping + is applied while the boxes are encoded in format ``(cx, cy, w, h)``. + """ + + def __init__( + self, + aspect_ratios: list[list[int]], + min_ratio: float = 0.15, + max_ratio: float = 0.9, + scales: Optional[list[float]] = None, + steps: Optional[list[int]] = None, + clip: bool = True, + ): + super().__init__() + if steps is not None and len(aspect_ratios) != len(steps): + raise ValueError("aspect_ratios and steps should have the same length") + self.aspect_ratios = aspect_ratios + self.steps = steps + self.clip = clip + num_outputs = len(aspect_ratios) + + # Estimation of default boxes scales + if scales is None: + if num_outputs > 1: + range_ratio = max_ratio - min_ratio + self.scales = [min_ratio + range_ratio * k / (num_outputs - 1.0) for k in range(num_outputs)] + self.scales.append(1.0) + else: + self.scales = [min_ratio, max_ratio] + else: + self.scales = scales + + self._wh_pairs = self._generate_wh_pairs(num_outputs) + + def _generate_wh_pairs( + self, num_outputs: int, dtype: torch.dtype = torch.float32, device: torch.device = torch.device("cpu") + ) -> list[Tensor]: + _wh_pairs: list[Tensor] = [] + for k in range(num_outputs): + # Adding the 2 default width-height pairs for aspect ratio 1 and scale s'k + s_k = self.scales[k] + s_prime_k = math.sqrt(self.scales[k] * self.scales[k + 1]) + wh_pairs = [[s_k, s_k], [s_prime_k, s_prime_k]] + + # Adding 2 pairs for each aspect ratio of the feature map k + for ar in self.aspect_ratios[k]: + sq_ar = math.sqrt(ar) + w = self.scales[k] * sq_ar + h = self.scales[k] / sq_ar + wh_pairs.extend([[w, h], [h, w]]) + + _wh_pairs.append(torch.as_tensor(wh_pairs, dtype=dtype, device=device)) + return _wh_pairs + + def num_anchors_per_location(self) -> list[int]: + # Estimate num of anchors based on aspect ratios: 2 default boxes + 2 * ratios of feaure map. + return [2 + 2 * len(r) for r in self.aspect_ratios] + + # Default Boxes calculation based on page 6 of SSD paper + def _grid_default_boxes( + self, grid_sizes: list[list[int]], image_size: list[int], dtype: torch.dtype = torch.float32 + ) -> Tensor: + default_boxes = [] + for k, f_k in enumerate(grid_sizes): + # Now add the default boxes for each width-height pair + if self.steps is not None: + x_f_k = image_size[1] / self.steps[k] + y_f_k = image_size[0] / self.steps[k] + else: + y_f_k, x_f_k = f_k + + shifts_x = ((torch.arange(0, f_k[1]) + 0.5) / x_f_k).to(dtype=dtype) + shifts_y = ((torch.arange(0, f_k[0]) + 0.5) / y_f_k).to(dtype=dtype) + shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x, indexing="ij") + shift_x = shift_x.reshape(-1) + shift_y = shift_y.reshape(-1) + + shifts = torch.stack((shift_x, shift_y) * len(self._wh_pairs[k]), dim=-1).reshape(-1, 2) + # Clipping the default boxes while the boxes are encoded in format (cx, cy, w, h) + _wh_pair = self._wh_pairs[k].clamp(min=0, max=1) if self.clip else self._wh_pairs[k] + wh_pairs = _wh_pair.repeat((f_k[0] * f_k[1]), 1) + + default_box = torch.cat((shifts, wh_pairs), dim=1) + + default_boxes.append(default_box) + + return torch.cat(default_boxes, dim=0) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"aspect_ratios={self.aspect_ratios}" + f", clip={self.clip}" + f", scales={self.scales}" + f", steps={self.steps}" + ")" + ) + return s + + def forward(self, image_list: ImageList, feature_maps: list[Tensor]) -> list[Tensor]: + grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps] + image_size = image_list.tensors.shape[-2:] + dtype, device = feature_maps[0].dtype, feature_maps[0].device + default_boxes = self._grid_default_boxes(grid_sizes, image_size, dtype=dtype) + default_boxes = default_boxes.to(device) + + dboxes = [] + x_y_size = torch.tensor([image_size[1], image_size[0]], device=default_boxes.device) + for _ in image_list.image_sizes: + dboxes_in_image = default_boxes + dboxes_in_image = torch.cat( + [ + (dboxes_in_image[:, :2] - 0.5 * dboxes_in_image[:, 2:]) * x_y_size, + (dboxes_in_image[:, :2] + 0.5 * dboxes_in_image[:, 2:]) * x_y_size, + ], + -1, + ) + dboxes.append(dboxes_in_image) + return dboxes diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/backbone_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/backbone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f24c121d59a06186fc104cdfe5634bcd5615cf7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/backbone_utils.py @@ -0,0 +1,244 @@ +import warnings +from typing import Callable, Optional, Union + +from torch import nn, Tensor +from torchvision.ops import misc as misc_nn_ops +from torchvision.ops.feature_pyramid_network import ExtraFPNBlock, FeaturePyramidNetwork, LastLevelMaxPool + +from .. import mobilenet, resnet +from .._api import _get_enum_from_fn, WeightsEnum +from .._utils import handle_legacy_interface, IntermediateLayerGetter + + +class BackboneWithFPN(nn.Module): + """ + Adds a FPN on top of a model. + Internally, it uses torchvision.models._utils.IntermediateLayerGetter to + extract a submodel that returns the feature maps specified in return_layers. + The same limitations of IntermediateLayerGetter apply here. + Args: + backbone (nn.Module) + return_layers (Dict[name, new_name]): a dict containing the names + of the modules for which the activations will be returned as + the key of the dict, and the value of the dict is the name + of the returned activation (which the user can specify). + in_channels_list (List[int]): number of channels for each feature map + that is returned, in the order they are present in the OrderedDict + out_channels (int): number of channels in the FPN. + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + Attributes: + out_channels (int): the number of channels in the FPN + """ + + def __init__( + self, + backbone: nn.Module, + return_layers: dict[str, str], + in_channels_list: list[int], + out_channels: int, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + + if extra_blocks is None: + extra_blocks = LastLevelMaxPool() + + self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) + self.fpn = FeaturePyramidNetwork( + in_channels_list=in_channels_list, + out_channels=out_channels, + extra_blocks=extra_blocks, + norm_layer=norm_layer, + ) + self.out_channels = out_channels + + def forward(self, x: Tensor) -> dict[str, Tensor]: + x = self.body(x) + x = self.fpn(x) + return x + + +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: _get_enum_from_fn(resnet.__dict__[kwargs["backbone_name"]])["IMAGENET1K_V1"], + ), +) +def resnet_fpn_backbone( + *, + backbone_name: str, + weights: Optional[WeightsEnum], + norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d, + trainable_layers: int = 3, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, +) -> BackboneWithFPN: + """ + Constructs a specified ResNet backbone with FPN on top. Freezes the specified number of layers in the backbone. + + Examples:: + + >>> import torch + >>> from torchvision.models import ResNet50_Weights + >>> from torchvision.models.detection.backbone_utils import resnet_fpn_backbone + >>> backbone = resnet_fpn_backbone(backbone_name='resnet50', weights=ResNet50_Weights.DEFAULT, trainable_layers=3) + >>> # get some dummy image + >>> x = torch.rand(1,3,64,64) + >>> # compute the output + >>> output = backbone(x) + >>> print([(k, v.shape) for k, v in output.items()]) + >>> # returns + >>> [('0', torch.Size([1, 256, 16, 16])), + >>> ('1', torch.Size([1, 256, 8, 8])), + >>> ('2', torch.Size([1, 256, 4, 4])), + >>> ('3', torch.Size([1, 256, 2, 2])), + >>> ('pool', torch.Size([1, 256, 1, 1]))] + + Args: + backbone_name (string): resnet architecture. Possible values are 'resnet18', 'resnet34', 'resnet50', + 'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2' + weights (WeightsEnum, optional): The pretrained weights for the model + norm_layer (callable): it is recommended to use the default value. For details visit: + (https://github.com/facebookresearch/maskrcnn-benchmark/issues/267) + trainable_layers (int): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. + returned_layers (list of int): The layers of the network to return. Each entry must be in ``[1, 4]``. + By default, all layers are returned. + extra_blocks (ExtraFPNBlock or None): if provided, extra operations will + be performed. It is expected to take the fpn features, the original + features and the names of the original features as input, and returns + a new list of feature maps and their corresponding names. By + default, a ``LastLevelMaxPool`` is used. + """ + backbone = resnet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer) + return _resnet_fpn_extractor(backbone, trainable_layers, returned_layers, extra_blocks) + + +def _resnet_fpn_extractor( + backbone: resnet.ResNet, + trainable_layers: int, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, +) -> BackboneWithFPN: + + # select layers that won't be frozen + if trainable_layers < 0 or trainable_layers > 5: + raise ValueError(f"Trainable layers should be in the range [0,5], got {trainable_layers}") + layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers] + if trainable_layers == 5: + layers_to_train.append("bn1") + for name, parameter in backbone.named_parameters(): + if all([not name.startswith(layer) for layer in layers_to_train]): + parameter.requires_grad_(False) + + if extra_blocks is None: + extra_blocks = LastLevelMaxPool() + + if returned_layers is None: + returned_layers = [1, 2, 3, 4] + if min(returned_layers) <= 0 or max(returned_layers) >= 5: + raise ValueError(f"Each returned layer should be in the range [1,4]. Got {returned_layers}") + return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)} + + in_channels_stage2 = backbone.inplanes // 8 + in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers] + out_channels = 256 + return BackboneWithFPN( + backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer + ) + + +def _validate_trainable_layers( + is_trained: bool, + trainable_backbone_layers: Optional[int], + max_value: int, + default_value: int, +) -> int: + # don't freeze any layers if pretrained model or backbone is not used + if not is_trained: + if trainable_backbone_layers is not None: + warnings.warn( + "Changing trainable_backbone_layers has no effect if " + "neither pretrained nor pretrained_backbone have been set to True, " + f"falling back to trainable_backbone_layers={max_value} so that all layers are trainable" + ) + trainable_backbone_layers = max_value + + # by default freeze first blocks + if trainable_backbone_layers is None: + trainable_backbone_layers = default_value + if trainable_backbone_layers < 0 or trainable_backbone_layers > max_value: + raise ValueError( + f"Trainable backbone layers should be in the range [0,{max_value}], got {trainable_backbone_layers} " + ) + return trainable_backbone_layers + + +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: _get_enum_from_fn(mobilenet.__dict__[kwargs["backbone_name"]])["IMAGENET1K_V1"], + ), +) +def mobilenet_backbone( + *, + backbone_name: str, + weights: Optional[WeightsEnum], + fpn: bool, + norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d, + trainable_layers: int = 2, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, +) -> nn.Module: + backbone = mobilenet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer) + return _mobilenet_extractor(backbone, fpn, trainable_layers, returned_layers, extra_blocks) + + +def _mobilenet_extractor( + backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3], + fpn: bool, + trainable_layers: int, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, +) -> nn.Module: + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + num_stages = len(stage_indices) + + # find the index of the layer from which we won't freeze + if trainable_layers < 0 or trainable_layers > num_stages: + raise ValueError(f"Trainable layers should be in the range [0,{num_stages}], got {trainable_layers} ") + freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers] + + for b in backbone[:freeze_before]: + for parameter in b.parameters(): + parameter.requires_grad_(False) + + out_channels = 256 + if fpn: + if extra_blocks is None: + extra_blocks = LastLevelMaxPool() + + if returned_layers is None: + returned_layers = [num_stages - 2, num_stages - 1] + if min(returned_layers) < 0 or max(returned_layers) >= num_stages: + raise ValueError(f"Each returned layer should be in the range [0,{num_stages - 1}], got {returned_layers} ") + return_layers = {f"{stage_indices[k]}": str(v) for v, k in enumerate(returned_layers)} + + in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers] + return BackboneWithFPN( + backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer + ) + else: + m = nn.Sequential( + backbone, + # depthwise linear combination of channels to reduce their size + nn.Conv2d(backbone[-1].out_channels, out_channels, 1), + ) + m.out_channels = out_channels # type: ignore[assignment] + return m diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/faster_rcnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/faster_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f7063107b66af2ead318677e0c7b0001905eac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/faster_rcnn.py @@ -0,0 +1,846 @@ +from typing import Any, Callable, Optional, Union + +import torch +import torch.nn.functional as F +from torch import nn +from torchvision.ops import MultiScaleRoIAlign + +from ...ops import misc as misc_nn_ops +from ...transforms._presets import ObjectDetection +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights +from ..resnet import resnet50, ResNet50_Weights +from ._utils import overwrite_eps +from .anchor_utils import AnchorGenerator +from .backbone_utils import _mobilenet_extractor, _resnet_fpn_extractor, _validate_trainable_layers +from .generalized_rcnn import GeneralizedRCNN +from .roi_heads import RoIHeads +from .rpn import RegionProposalNetwork, RPNHead +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "FasterRCNN", + "FasterRCNN_ResNet50_FPN_Weights", + "FasterRCNN_ResNet50_FPN_V2_Weights", + "FasterRCNN_MobileNet_V3_Large_FPN_Weights", + "FasterRCNN_MobileNet_V3_Large_320_FPN_Weights", + "fasterrcnn_resnet50_fpn", + "fasterrcnn_resnet50_fpn_v2", + "fasterrcnn_mobilenet_v3_large_fpn", + "fasterrcnn_mobilenet_v3_large_320_fpn", +] + + +def _default_anchorgen(): + anchor_sizes = ((32,), (64,), (128,), (256,), (512,)) + aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) + return AnchorGenerator(anchor_sizes, aspect_ratios) + + +class FasterRCNN(GeneralizedRCNN): + """ + Implements Faster R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses for both the RPN and the R-CNN. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores or each prediction + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or and OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + If box_predictor is specified, num_classes should be None. + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN + rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training + rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing + rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training + rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing + rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh + box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes + box_head (nn.Module): module that takes the cropped feature maps as input + box_predictor (nn.Module): module that takes the output of box_head and returns the + classification logits and box regression deltas. + box_score_thresh (float): during inference, only return proposals with a classification score + greater than box_score_thresh + box_nms_thresh (float): NMS threshold for the prediction head. Used during inference + box_detections_per_img (int): maximum number of detections per image, for all classes. + box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be + considered as positive during training of the classification head + box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be + considered as negative during training of the classification head + box_batch_size_per_image (int): number of proposals that are sampled during training of the + classification head + box_positive_fraction (float): proportion of positive proposals in a mini-batch during training + of the classification head + bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the + bounding boxes + + Example:: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import FasterRCNN + >>> from torchvision.models.detection.rpn import AnchorGenerator + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # FasterRCNN needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the RPN generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),)) + >>> + >>> # let's define what are the feature maps that we will + >>> # use to perform the region of interest cropping, as well as + >>> # the size of the crop after rescaling. + >>> # if your backbone returns a Tensor, featmap_names is expected to + >>> # be ['0']. More generally, the backbone should return an + >>> # OrderedDict[Tensor], and in featmap_names you can choose which + >>> # feature maps to use. + >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=7, + >>> sampling_ratio=2) + >>> + >>> # put the pieces together inside a FasterRCNN model + >>> model = FasterRCNN(backbone, + >>> num_classes=2, + >>> rpn_anchor_generator=anchor_generator, + >>> box_roi_pool=roi_pooler) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + def __init__( + self, + backbone, + num_classes=None, + # transform parameters + min_size=800, + max_size=1333, + image_mean=None, + image_std=None, + # RPN parameters + rpn_anchor_generator=None, + rpn_head=None, + rpn_pre_nms_top_n_train=2000, + rpn_pre_nms_top_n_test=1000, + rpn_post_nms_top_n_train=2000, + rpn_post_nms_top_n_test=1000, + rpn_nms_thresh=0.7, + rpn_fg_iou_thresh=0.7, + rpn_bg_iou_thresh=0.3, + rpn_batch_size_per_image=256, + rpn_positive_fraction=0.5, + rpn_score_thresh=0.0, + # Box parameters + box_roi_pool=None, + box_head=None, + box_predictor=None, + box_score_thresh=0.05, + box_nms_thresh=0.5, + box_detections_per_img=100, + box_fg_iou_thresh=0.5, + box_bg_iou_thresh=0.5, + box_batch_size_per_image=512, + box_positive_fraction=0.25, + bbox_reg_weights=None, + **kwargs, + ): + + if not hasattr(backbone, "out_channels"): + raise ValueError( + "backbone should contain an attribute out_channels " + "specifying the number of output channels (assumed to be the " + "same for all the levels)" + ) + + if not isinstance(rpn_anchor_generator, (AnchorGenerator, type(None))): + raise TypeError( + f"rpn_anchor_generator should be of type AnchorGenerator or None instead of {type(rpn_anchor_generator)}" + ) + if not isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None))): + raise TypeError( + f"box_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(box_roi_pool)}" + ) + + if num_classes is not None: + if box_predictor is not None: + raise ValueError("num_classes should be None when box_predictor is specified") + else: + if box_predictor is None: + raise ValueError("num_classes should not be None when box_predictor is not specified") + + out_channels = backbone.out_channels + + if rpn_anchor_generator is None: + rpn_anchor_generator = _default_anchorgen() + if rpn_head is None: + rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0]) + + rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test) + rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test) + + rpn = RegionProposalNetwork( + rpn_anchor_generator, + rpn_head, + rpn_fg_iou_thresh, + rpn_bg_iou_thresh, + rpn_batch_size_per_image, + rpn_positive_fraction, + rpn_pre_nms_top_n, + rpn_post_nms_top_n, + rpn_nms_thresh, + score_thresh=rpn_score_thresh, + ) + + if box_roi_pool is None: + box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=7, sampling_ratio=2) + + if box_head is None: + resolution = box_roi_pool.output_size[0] + representation_size = 1024 + box_head = TwoMLPHead(out_channels * resolution**2, representation_size) + + if box_predictor is None: + representation_size = 1024 + box_predictor = FastRCNNPredictor(representation_size, num_classes) + + roi_heads = RoIHeads( + # Box + box_roi_pool, + box_head, + box_predictor, + box_fg_iou_thresh, + box_bg_iou_thresh, + box_batch_size_per_image, + box_positive_fraction, + bbox_reg_weights, + box_score_thresh, + box_nms_thresh, + box_detections_per_img, + ) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs) + + super().__init__(backbone, rpn, roi_heads, transform) + + +class TwoMLPHead(nn.Module): + """ + Standard heads for FPN-based models + + Args: + in_channels (int): number of input channels + representation_size (int): size of the intermediate representation + """ + + def __init__(self, in_channels, representation_size): + super().__init__() + + self.fc6 = nn.Linear(in_channels, representation_size) + self.fc7 = nn.Linear(representation_size, representation_size) + + def forward(self, x): + x = x.flatten(start_dim=1) + + x = F.relu(self.fc6(x)) + x = F.relu(self.fc7(x)) + + return x + + +class FastRCNNConvFCHead(nn.Sequential): + def __init__( + self, + input_size: tuple[int, int, int], + conv_layers: list[int], + fc_layers: list[int], + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + """ + Args: + input_size (Tuple[int, int, int]): the input size in CHW format. + conv_layers (list): feature dimensions of each Convolution layer + fc_layers (list): feature dimensions of each FCN layer + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + in_channels, in_height, in_width = input_size + + blocks = [] + previous_channels = in_channels + for current_channels in conv_layers: + blocks.append(misc_nn_ops.Conv2dNormActivation(previous_channels, current_channels, norm_layer=norm_layer)) + previous_channels = current_channels + blocks.append(nn.Flatten()) + previous_channels = previous_channels * in_height * in_width + for current_channels in fc_layers: + blocks.append(nn.Linear(previous_channels, current_channels)) + blocks.append(nn.ReLU(inplace=True)) + previous_channels = current_channels + + super().__init__(*blocks) + for layer in self.modules(): + if isinstance(layer, nn.Conv2d): + nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu") + if layer.bias is not None: + nn.init.zeros_(layer.bias) + + +class FastRCNNPredictor(nn.Module): + """ + Standard classification + bounding box regression layers + for Fast R-CNN. + + Args: + in_channels (int): number of input channels + num_classes (int): number of output classes (including background) + """ + + def __init__(self, in_channels, num_classes): + super().__init__() + self.cls_score = nn.Linear(in_channels, num_classes) + self.bbox_pred = nn.Linear(in_channels, num_classes * 4) + + def forward(self, x): + if x.dim() == 4: + torch._assert( + list(x.shape[2:]) == [1, 1], + f"x has the wrong shape, expecting the last two dimensions to be [1,1] instead of {list(x.shape[2:])}", + ) + x = x.flatten(start_dim=1) + scores = self.cls_score(x) + bbox_deltas = self.bbox_pred(x) + + return scores, bbox_deltas + + +_COMMON_META = { + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), +} + + +class FasterRCNN_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 41755286, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-resnet-50-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 37.0, + } + }, + "_ops": 134.38, + "_file_size": 159.743, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class FasterRCNN_ResNet50_FPN_V2_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_v2_coco-dd69338a.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 43712278, + "recipe": "https://github.com/pytorch/vision/pull/5763", + "_metrics": { + "COCO-val2017": { + "box_map": 46.7, + } + }, + "_ops": 280.371, + "_file_size": 167.104, + "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""", + }, + ) + DEFAULT = COCO_V1 + + +class FasterRCNN_MobileNet_V3_Large_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_fpn-fb6a3cc7.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 19386354, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 32.8, + } + }, + "_ops": 4.494, + "_file_size": 74.239, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class FasterRCNN_MobileNet_V3_Large_320_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 19386354, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-320-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 22.8, + } + }, + "_ops": 0.719, + "_file_size": 74.239, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fasterrcnn_resnet50_fpn( + *, + weights: Optional[FasterRCNN_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Faster R-CNN model with a ResNet-50-FPN backbone from the `Faster R-CNN: Towards Real-Time Object + Detection with Region Proposal Networks `__ + paper. + + .. betastatus:: detection module + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and a targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses for both the RPN and the R-CNN. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each detection + - scores (``Tensor[N]``): the scores of each detection + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size. + + Example:: + + >>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT) + >>> # For training + >>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4) + >>> boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4] + >>> labels = torch.randint(1, 91, (4, 11)) + >>> images = list(image for image in images) + >>> targets = [] + >>> for i in range(len(images)): + >>> d = {} + >>> d['boxes'] = boxes[i] + >>> d['labels'] = labels[i] + >>> targets.append(d) + >>> output = model(images, targets) + >>> # For inference + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + >>> + >>> # optionally, if you want to export the model to ONNX: + >>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11) + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights + :members: + """ + weights = FasterRCNN_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers) + model = FasterRCNN(backbone, num_classes=num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == FasterRCNN_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_ResNet50_FPN_V2_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fasterrcnn_resnet50_fpn_v2( + *, + weights: Optional[FasterRCNN_ResNet50_FPN_V2_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = None, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Constructs an improved Faster R-CNN model with a ResNet-50-FPN backbone from `Benchmarking Detection + Transfer Learning with Vision Transformers `__ paper. + + .. betastatus:: detection module + + It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See + :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more + details. + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights + :members: + """ + weights = FasterRCNN_ResNet50_FPN_V2_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + + backbone = resnet50(weights=weights_backbone, progress=progress) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d) + rpn_anchor_generator = _default_anchorgen() + rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2) + box_head = FastRCNNConvFCHead( + (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d + ) + model = FasterRCNN( + backbone, + num_classes=num_classes, + rpn_anchor_generator=rpn_anchor_generator, + rpn_head=rpn_head, + box_head=box_head, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +def _fasterrcnn_mobilenet_v3_large_fpn( + *, + weights: Optional[Union[FasterRCNN_MobileNet_V3_Large_FPN_Weights, FasterRCNN_MobileNet_V3_Large_320_FPN_Weights]], + progress: bool, + num_classes: Optional[int], + weights_backbone: Optional[MobileNet_V3_Large_Weights], + trainable_backbone_layers: Optional[int], + **kwargs: Any, +) -> FasterRCNN: + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 6, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = mobilenet_v3_large(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _mobilenet_extractor(backbone, True, trainable_backbone_layers) + anchor_sizes = ( + ( + 32, + 64, + 128, + 256, + 512, + ), + ) * 3 + aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) + model = FasterRCNN( + backbone, num_classes, rpn_anchor_generator=AnchorGenerator(anchor_sizes, aspect_ratios), **kwargs + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def fasterrcnn_mobilenet_v3_large_320_fpn( + *, + weights: Optional[FasterRCNN_MobileNet_V3_Large_320_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Low resolution Faster R-CNN model with a MobileNetV3-Large backbone tuned for mobile use cases. + + .. betastatus:: detection module + + It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See + :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more + details. + + Example:: + + >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(weights=FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights + :members: + """ + weights = FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + defaults = { + "min_size": 320, + "max_size": 640, + "rpn_pre_nms_top_n_test": 150, + "rpn_post_nms_top_n_test": 150, + "rpn_score_thresh": 0.05, + } + + kwargs = {**defaults, **kwargs} + return _fasterrcnn_mobilenet_v3_large_fpn( + weights=weights, + progress=progress, + num_classes=num_classes, + weights_backbone=weights_backbone, + trainable_backbone_layers=trainable_backbone_layers, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_MobileNet_V3_Large_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def fasterrcnn_mobilenet_v3_large_fpn( + *, + weights: Optional[FasterRCNN_MobileNet_V3_Large_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Constructs a high resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone. + + .. betastatus:: detection module + + It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See + :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more + details. + + Example:: + + >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(weights=FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights + :members: + """ + weights = FasterRCNN_MobileNet_V3_Large_FPN_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + defaults = { + "rpn_score_thresh": 0.05, + } + + kwargs = {**defaults, **kwargs} + return _fasterrcnn_mobilenet_v3_large_fpn( + weights=weights, + progress=progress, + num_classes=num_classes, + weights_backbone=weights_backbone, + trainable_backbone_layers=trainable_backbone_layers, + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/fcos.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/fcos.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbd2496517c33b74a1a1581e0cbf3b3f173bfed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/fcos.py @@ -0,0 +1,775 @@ +import math +import warnings +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ...ops import boxes as box_ops, generalized_box_iou_loss, misc as misc_nn_ops, sigmoid_focal_loss +from ...ops.feature_pyramid_network import LastLevelP6P7 +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from . import _utils as det_utils +from .anchor_utils import AnchorGenerator +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "FCOS", + "FCOS_ResNet50_FPN_Weights", + "fcos_resnet50_fpn", +] + + +class FCOSHead(nn.Module): + """ + A regression and classification head for use in FCOS. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_classes (int): number of classes to be predicted + num_convs (Optional[int]): number of conv layer of head. Default: 4. + """ + + __annotations__ = { + "box_coder": det_utils.BoxLinearCoder, + } + + def __init__(self, in_channels: int, num_anchors: int, num_classes: int, num_convs: Optional[int] = 4) -> None: + super().__init__() + self.box_coder = det_utils.BoxLinearCoder(normalize_by_size=True) + self.classification_head = FCOSClassificationHead(in_channels, num_anchors, num_classes, num_convs) + self.regression_head = FCOSRegressionHead(in_channels, num_anchors, num_convs) + + def compute_loss( + self, + targets: list[dict[str, Tensor]], + head_outputs: dict[str, Tensor], + anchors: list[Tensor], + matched_idxs: list[Tensor], + ) -> dict[str, Tensor]: + + cls_logits = head_outputs["cls_logits"] # [N, HWA, C] + bbox_regression = head_outputs["bbox_regression"] # [N, HWA, 4] + bbox_ctrness = head_outputs["bbox_ctrness"] # [N, HWA, 1] + + all_gt_classes_targets = [] + all_gt_boxes_targets = [] + for targets_per_image, matched_idxs_per_image in zip(targets, matched_idxs): + if len(targets_per_image["labels"]) == 0: + gt_classes_targets = targets_per_image["labels"].new_zeros((len(matched_idxs_per_image),)) + gt_boxes_targets = targets_per_image["boxes"].new_zeros((len(matched_idxs_per_image), 4)) + else: + gt_classes_targets = targets_per_image["labels"][matched_idxs_per_image.clip(min=0)] + gt_boxes_targets = targets_per_image["boxes"][matched_idxs_per_image.clip(min=0)] + gt_classes_targets[matched_idxs_per_image < 0] = -1 # background + all_gt_classes_targets.append(gt_classes_targets) + all_gt_boxes_targets.append(gt_boxes_targets) + + # List[Tensor] to Tensor conversion of `all_gt_boxes_target`, `all_gt_classes_targets` and `anchors` + all_gt_boxes_targets, all_gt_classes_targets, anchors = ( + torch.stack(all_gt_boxes_targets), + torch.stack(all_gt_classes_targets), + torch.stack(anchors), + ) + + # compute foregroud + foregroud_mask = all_gt_classes_targets >= 0 + num_foreground = foregroud_mask.sum().item() + + # classification loss + gt_classes_targets = torch.zeros_like(cls_logits) + gt_classes_targets[foregroud_mask, all_gt_classes_targets[foregroud_mask]] = 1.0 + loss_cls = sigmoid_focal_loss(cls_logits, gt_classes_targets, reduction="sum") + + # amp issue: pred_boxes need to convert float + pred_boxes = self.box_coder.decode(bbox_regression, anchors) + + # regression loss: GIoU loss + loss_bbox_reg = generalized_box_iou_loss( + pred_boxes[foregroud_mask], + all_gt_boxes_targets[foregroud_mask], + reduction="sum", + ) + + # ctrness loss + + bbox_reg_targets = self.box_coder.encode(anchors, all_gt_boxes_targets) + + if len(bbox_reg_targets) == 0: + gt_ctrness_targets = bbox_reg_targets.new_zeros(bbox_reg_targets.size()[:-1]) + else: + left_right = bbox_reg_targets[:, :, [0, 2]] + top_bottom = bbox_reg_targets[:, :, [1, 3]] + gt_ctrness_targets = torch.sqrt( + (left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) + * (top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0]) + ) + pred_centerness = bbox_ctrness.squeeze(dim=2) + loss_bbox_ctrness = nn.functional.binary_cross_entropy_with_logits( + pred_centerness[foregroud_mask], gt_ctrness_targets[foregroud_mask], reduction="sum" + ) + + return { + "classification": loss_cls / max(1, num_foreground), + "bbox_regression": loss_bbox_reg / max(1, num_foreground), + "bbox_ctrness": loss_bbox_ctrness / max(1, num_foreground), + } + + def forward(self, x: list[Tensor]) -> dict[str, Tensor]: + cls_logits = self.classification_head(x) + bbox_regression, bbox_ctrness = self.regression_head(x) + return { + "cls_logits": cls_logits, + "bbox_regression": bbox_regression, + "bbox_ctrness": bbox_ctrness, + } + + +class FCOSClassificationHead(nn.Module): + """ + A classification head for use in FCOS. + + Args: + in_channels (int): number of channels of the input feature. + num_anchors (int): number of anchors to be predicted. + num_classes (int): number of classes to be predicted. + num_convs (Optional[int]): number of conv layer. Default: 4. + prior_probability (Optional[float]): probability of prior. Default: 0.01. + norm_layer: Module specifying the normalization layer to use. + """ + + def __init__( + self, + in_channels: int, + num_anchors: int, + num_classes: int, + num_convs: int = 4, + prior_probability: float = 0.01, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + + self.num_classes = num_classes + self.num_anchors = num_anchors + + if norm_layer is None: + norm_layer = partial(nn.GroupNorm, 32) + + conv = [] + for _ in range(num_convs): + conv.append(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)) + conv.append(norm_layer(in_channels)) + conv.append(nn.ReLU()) + self.conv = nn.Sequential(*conv) + + for layer in self.conv.children(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.constant_(layer.bias, 0) + + self.cls_logits = nn.Conv2d(in_channels, num_anchors * num_classes, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.cls_logits.weight, std=0.01) + torch.nn.init.constant_(self.cls_logits.bias, -math.log((1 - prior_probability) / prior_probability)) + + def forward(self, x: list[Tensor]) -> Tensor: + all_cls_logits = [] + + for features in x: + cls_logits = self.conv(features) + cls_logits = self.cls_logits(cls_logits) + + # Permute classification output from (N, A * K, H, W) to (N, HWA, K). + N, _, H, W = cls_logits.shape + cls_logits = cls_logits.view(N, -1, self.num_classes, H, W) + cls_logits = cls_logits.permute(0, 3, 4, 1, 2) + cls_logits = cls_logits.reshape(N, -1, self.num_classes) # Size=(N, HWA, 4) + + all_cls_logits.append(cls_logits) + + return torch.cat(all_cls_logits, dim=1) + + +class FCOSRegressionHead(nn.Module): + """ + A regression head for use in FCOS, which combines regression branch and center-ness branch. + This can obtain better performance. + + Reference: `FCOS: A simple and strong anchor-free object detector `_. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_convs (Optional[int]): number of conv layer. Default: 4. + norm_layer: Module specifying the normalization layer to use. + """ + + def __init__( + self, + in_channels: int, + num_anchors: int, + num_convs: int = 4, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + super().__init__() + + if norm_layer is None: + norm_layer = partial(nn.GroupNorm, 32) + + conv = [] + for _ in range(num_convs): + conv.append(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)) + conv.append(norm_layer(in_channels)) + conv.append(nn.ReLU()) + self.conv = nn.Sequential(*conv) + + self.bbox_reg = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=3, stride=1, padding=1) + self.bbox_ctrness = nn.Conv2d(in_channels, num_anchors * 1, kernel_size=3, stride=1, padding=1) + for layer in [self.bbox_reg, self.bbox_ctrness]: + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.zeros_(layer.bias) + + for layer in self.conv.children(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.zeros_(layer.bias) + + def forward(self, x: list[Tensor]) -> tuple[Tensor, Tensor]: + all_bbox_regression = [] + all_bbox_ctrness = [] + + for features in x: + bbox_feature = self.conv(features) + bbox_regression = nn.functional.relu(self.bbox_reg(bbox_feature)) + bbox_ctrness = self.bbox_ctrness(bbox_feature) + + # permute bbox regression output from (N, 4 * A, H, W) to (N, HWA, 4). + N, _, H, W = bbox_regression.shape + bbox_regression = bbox_regression.view(N, -1, 4, H, W) + bbox_regression = bbox_regression.permute(0, 3, 4, 1, 2) + bbox_regression = bbox_regression.reshape(N, -1, 4) # Size=(N, HWA, 4) + all_bbox_regression.append(bbox_regression) + + # permute bbox ctrness output from (N, 1 * A, H, W) to (N, HWA, 1). + bbox_ctrness = bbox_ctrness.view(N, -1, 1, H, W) + bbox_ctrness = bbox_ctrness.permute(0, 3, 4, 1, 2) + bbox_ctrness = bbox_ctrness.reshape(N, -1, 1) + all_bbox_ctrness.append(bbox_ctrness) + + return torch.cat(all_bbox_regression, dim=1), torch.cat(all_bbox_ctrness, dim=1) + + +class FCOS(nn.Module): + """ + Implements FCOS. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification, regression + and centerness losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores for each prediction + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or an OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. For FCOS, only set one anchor for per position of each level, the width and height equal to + the stride of feature map, and set aspect ratio = 1.0, so the center of anchor is equivalent to the point + in FCOS paper. + head (nn.Module): Module run on top of the feature pyramid. + Defaults to a module containing a classification and regression module. + center_sampling_radius (int): radius of the "center" of a groundtruth box, + within which all anchor points are labeled positive. + score_thresh (float): Score threshold used for postprocessing the detections. + nms_thresh (float): NMS threshold used for postprocessing the detections. + detections_per_img (int): Number of best detections to keep after NMS. + topk_candidates (int): Number of best detections to keep before NMS. + + Example: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import FCOS + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # FCOS needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the network generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator( + >>> sizes=((8,), (16,), (32,), (64,), (128,)), + >>> aspect_ratios=((1.0,),) + >>> ) + >>> + >>> # put the pieces together inside a FCOS model + >>> model = FCOS( + >>> backbone, + >>> num_classes=80, + >>> anchor_generator=anchor_generator, + >>> ) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + __annotations__ = { + "box_coder": det_utils.BoxLinearCoder, + } + + def __init__( + self, + backbone: nn.Module, + num_classes: int, + # transform parameters + min_size: int = 800, + max_size: int = 1333, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + # Anchor parameters + anchor_generator: Optional[AnchorGenerator] = None, + head: Optional[nn.Module] = None, + center_sampling_radius: float = 1.5, + score_thresh: float = 0.2, + nms_thresh: float = 0.6, + detections_per_img: int = 100, + topk_candidates: int = 1000, + **kwargs, + ): + super().__init__() + _log_api_usage_once(self) + + if not hasattr(backbone, "out_channels"): + raise ValueError( + "backbone should contain an attribute out_channels " + "specifying the number of output channels (assumed to be the " + "same for all the levels)" + ) + self.backbone = backbone + + if not isinstance(anchor_generator, (AnchorGenerator, type(None))): + raise TypeError( + f"anchor_generator should be of type AnchorGenerator or None, instead got {type(anchor_generator)}" + ) + + if anchor_generator is None: + anchor_sizes = ((8,), (16,), (32,), (64,), (128,)) # equal to strides of multi-level feature map + aspect_ratios = ((1.0,),) * len(anchor_sizes) # set only one anchor + anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios) + self.anchor_generator = anchor_generator + if self.anchor_generator.num_anchors_per_location()[0] != 1: + raise ValueError( + f"anchor_generator.num_anchors_per_location()[0] should be 1 instead of {anchor_generator.num_anchors_per_location()[0]}" + ) + + if head is None: + head = FCOSHead(backbone.out_channels, anchor_generator.num_anchors_per_location()[0], num_classes) + self.head = head + + self.box_coder = det_utils.BoxLinearCoder(normalize_by_size=True) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + self.transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs) + + self.center_sampling_radius = center_sampling_radius + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + self.topk_candidates = topk_candidates + + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs( + self, losses: dict[str, Tensor], detections: list[dict[str, Tensor]] + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + if self.training: + return losses + + return detections + + def compute_loss( + self, + targets: list[dict[str, Tensor]], + head_outputs: dict[str, Tensor], + anchors: list[Tensor], + num_anchors_per_level: list[int], + ) -> dict[str, Tensor]: + matched_idxs = [] + for anchors_per_image, targets_per_image in zip(anchors, targets): + if targets_per_image["boxes"].numel() == 0: + matched_idxs.append( + torch.full((anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device) + ) + continue + + gt_boxes = targets_per_image["boxes"] + gt_centers = (gt_boxes[:, :2] + gt_boxes[:, 2:]) / 2 # Nx2 + anchor_centers = (anchors_per_image[:, :2] + anchors_per_image[:, 2:]) / 2 # N + anchor_sizes = anchors_per_image[:, 2] - anchors_per_image[:, 0] + # center sampling: anchor point must be close enough to gt center. + pairwise_match = (anchor_centers[:, None, :] - gt_centers[None, :, :]).abs_().max( + dim=2 + ).values < self.center_sampling_radius * anchor_sizes[:, None] + # compute pairwise distance between N points and M boxes + x, y = anchor_centers.unsqueeze(dim=2).unbind(dim=1) # (N, 1) + x0, y0, x1, y1 = gt_boxes.unsqueeze(dim=0).unbind(dim=2) # (1, M) + pairwise_dist = torch.stack([x - x0, y - y0, x1 - x, y1 - y], dim=2) # (N, M) + + # anchor point must be inside gt + pairwise_match &= pairwise_dist.min(dim=2).values > 0 + + # each anchor is only responsible for certain scale range. + lower_bound = anchor_sizes * 4 + lower_bound[: num_anchors_per_level[0]] = 0 + upper_bound = anchor_sizes * 8 + upper_bound[-num_anchors_per_level[-1] :] = float("inf") + pairwise_dist = pairwise_dist.max(dim=2).values + pairwise_match &= (pairwise_dist > lower_bound[:, None]) & (pairwise_dist < upper_bound[:, None]) + + # match the GT box with minimum area, if there are multiple GT matches + gt_areas = (gt_boxes[:, 2] - gt_boxes[:, 0]) * (gt_boxes[:, 3] - gt_boxes[:, 1]) # N + pairwise_match = pairwise_match.to(torch.float32) * (1e8 - gt_areas[None, :]) + min_values, matched_idx = pairwise_match.max(dim=1) # R, per-anchor match + matched_idx[min_values < 1e-5] = -1 # unmatched anchors are assigned -1 + + matched_idxs.append(matched_idx) + + return self.head.compute_loss(targets, head_outputs, anchors, matched_idxs) + + def postprocess_detections( + self, head_outputs: dict[str, list[Tensor]], anchors: list[list[Tensor]], image_shapes: list[tuple[int, int]] + ) -> list[dict[str, Tensor]]: + class_logits = head_outputs["cls_logits"] + box_regression = head_outputs["bbox_regression"] + box_ctrness = head_outputs["bbox_ctrness"] + + num_images = len(image_shapes) + + detections: list[dict[str, Tensor]] = [] + + for index in range(num_images): + box_regression_per_image = [br[index] for br in box_regression] + logits_per_image = [cl[index] for cl in class_logits] + box_ctrness_per_image = [bc[index] for bc in box_ctrness] + anchors_per_image, image_shape = anchors[index], image_shapes[index] + + image_boxes = [] + image_scores = [] + image_labels = [] + + for box_regression_per_level, logits_per_level, box_ctrness_per_level, anchors_per_level in zip( + box_regression_per_image, logits_per_image, box_ctrness_per_image, anchors_per_image + ): + num_classes = logits_per_level.shape[-1] + + # remove low scoring boxes + scores_per_level = torch.sqrt( + torch.sigmoid(logits_per_level) * torch.sigmoid(box_ctrness_per_level) + ).flatten() + keep_idxs = scores_per_level > self.score_thresh + scores_per_level = scores_per_level[keep_idxs] + topk_idxs = torch.where(keep_idxs)[0] + + # keep only topk scoring predictions + num_topk = det_utils._topk_min(topk_idxs, self.topk_candidates, 0) + scores_per_level, idxs = scores_per_level.topk(num_topk) + topk_idxs = topk_idxs[idxs] + + anchor_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + labels_per_level = topk_idxs % num_classes + + boxes_per_level = self.box_coder.decode( + box_regression_per_level[anchor_idxs], anchors_per_level[anchor_idxs] + ) + boxes_per_level = box_ops.clip_boxes_to_image(boxes_per_level, image_shape) + + image_boxes.append(boxes_per_level) + image_scores.append(scores_per_level) + image_labels.append(labels_per_level) + + image_boxes = torch.cat(image_boxes, dim=0) + image_scores = torch.cat(image_scores, dim=0) + image_labels = torch.cat(image_labels, dim=0) + + # non-maximum suppression + keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh) + keep = keep[: self.detections_per_img] + + detections.append( + { + "boxes": image_boxes[keep], + "scores": image_scores[keep], + "labels": image_labels[keep], + } + ) + + return detections + + def forward( + self, + images: list[Tensor], + targets: Optional[list[dict[str, Tensor]]] = None, + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + """ + Args: + images (list[Tensor]): images to be processed + targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional) + + Returns: + result (list[BoxList] or dict[Tensor]): the output from the model. + During training, it returns a dict[Tensor] which contains the losses. + During testing, it returns list[BoxList] contains additional fields + like `scores`, `labels` and `mask` (for Mask R-CNN models). + """ + if self.training: + + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + torch._assert(isinstance(boxes, torch.Tensor), "Expected target boxes to be of type Tensor.") + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.", + ) + + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + # transform the input + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + # print the first degenerate box + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + f"All bounding boxes should have positive height and width. Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + # get the features from the backbone + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + + features = list(features.values()) + + # compute the fcos heads outputs using the features + head_outputs = self.head(features) + + # create the set of anchors + anchors = self.anchor_generator(images, features) + # recover level sizes + num_anchors_per_level = [x.size(2) * x.size(3) for x in features] + + losses = {} + detections: list[dict[str, Tensor]] = [] + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + # compute the losses + losses = self.compute_loss(targets, head_outputs, anchors, num_anchors_per_level) + else: + # split outputs per level + split_head_outputs: dict[str, list[Tensor]] = {} + for k in head_outputs: + split_head_outputs[k] = list(head_outputs[k].split(num_anchors_per_level, dim=1)) + split_anchors = [list(a.split(num_anchors_per_level)) for a in anchors] + + # compute the detections + detections = self.postprocess_detections(split_head_outputs, split_anchors, images.image_sizes) + detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("FCOS always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + return self.eager_outputs(losses, detections) + + +class FCOS_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fcos_resnet50_fpn_coco-99b0c9b7.pth", + transforms=ObjectDetection, + meta={ + "num_params": 32269600, + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#fcos-resnet-50-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 39.2, + } + }, + "_ops": 128.207, + "_file_size": 123.608, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FCOS_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fcos_resnet50_fpn( + *, + weights: Optional[FCOS_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FCOS: + """ + Constructs a FCOS model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `FCOS: Fully Convolutional One-Stage Object Detection `_. + `FCOS: A simple and strong anchor-free object detector `_. + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each detection + - scores (``Tensor[N]``): the scores of each detection + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Example: + + >>> model = torchvision.models.detection.fcos_resnet50_fpn(weights=FCOS_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for + the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) resnet layers starting + from final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. Default: None + **kwargs: parameters passed to the ``torchvision.models.detection.FCOS`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FCOS_ResNet50_FPN_Weights + :members: + """ + weights = FCOS_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor( + backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(256, 256) + ) + model = FCOS(backbone, num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/generalized_rcnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/generalized_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..f07fa77aae95042f4997869c9164eb07122dd8de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/generalized_rcnn.py @@ -0,0 +1,133 @@ +""" +Implements the Generalized R-CNN framework +""" + +import warnings +from collections import OrderedDict +from typing import Optional, Union + +import torch +from torch import nn + +from ...utils import _log_api_usage_once + + +class GeneralizedRCNN(nn.Module): + """ + Main class for Generalized R-CNN. + + Args: + backbone (nn.Module): + rpn (nn.Module): + roi_heads (nn.Module): takes the features + the proposals from the RPN and computes + detections / masks from it. + transform (nn.Module): performs the data transformation from the inputs to feed into + the model + """ + + def __init__( + self, + backbone: nn.Module, + rpn: nn.Module, + roi_heads: nn.Module, + transform: nn.Module, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.transform = transform + self.backbone = backbone + self.rpn = rpn + self.roi_heads = roi_heads + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs( + self, losses: dict[str, torch.Tensor], detections: list[dict[str, torch.Tensor]] + ) -> Union[dict[str, torch.Tensor], list[dict[str, torch.Tensor]]]: + if self.training: + return losses + + return detections + + def forward( + self, + images: list[torch.Tensor], + targets: Optional[list[dict[str, torch.Tensor]]] = None, + ) -> tuple[dict[str, torch.Tensor], list[dict[str, torch.Tensor]]]: + """ + Args: + images (list[Tensor]): images to be processed + targets (list[dict[str, tensor]]): ground-truth boxes present in the image (optional) + + Returns: + result (list[BoxList] or dict[Tensor]): the output from the model. + During training, it returns a dict[Tensor] which contains the losses. + During testing, it returns list[BoxList] contains additional fields + like `scores`, `labels` and `mask` (for Mask R-CNN models). + + """ + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + if isinstance(boxes, torch.Tensor): + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.", + ) + else: + torch._assert( + False, + f"Expected target boxes to be of type Tensor, got {type(boxes)}.", + ) + + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + # TODO: Move this to a function + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + # print the first degenerate box + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + "All bounding boxes should have positive height and width." + f" Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + proposals, proposal_losses = self.rpn(images, features, targets) + detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets) + detections = self.transform.postprocess( + detections, images.image_sizes, original_image_sizes + ) # type: ignore[operator] + + losses = {} + losses.update(detector_losses) + losses.update(proposal_losses) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("RCNN always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + else: + return self.eager_outputs(losses, detections) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/image_list.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/image_list.py new file mode 100644 index 0000000000000000000000000000000000000000..08aabe3a486e2609b53352f2d50a3148c4428066 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/image_list.py @@ -0,0 +1,23 @@ +import torch +from torch import Tensor + + +class ImageList: + """ + Structure that holds a list of images (of possibly + varying sizes) as a single tensor. + This works by padding the images to the same size, + and storing in a field the original sizes of each image + + Args: + tensors (tensor): Tensor containing images. + image_sizes (list[tuple[int, int]]): List of Tuples each containing size of images. + """ + + def __init__(self, tensors: Tensor, image_sizes: list[tuple[int, int]]) -> None: + self.tensors = tensors + self.image_sizes = image_sizes + + def to(self, device: torch.device) -> "ImageList": + cast_tensor = self.tensors.to(device) + return ImageList(cast_tensor, self.image_sizes) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/keypoint_rcnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/keypoint_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..42b9d65562d81f9ce1be56180c433de44d5e9b4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/keypoint_rcnn.py @@ -0,0 +1,476 @@ +from typing import Any, Optional + +import torch +from torch import nn +from torchvision.ops import MultiScaleRoIAlign + +from ...ops import misc as misc_nn_ops +from ...transforms._presets import ObjectDetection +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from ._utils import overwrite_eps +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .faster_rcnn import FasterRCNN + + +__all__ = [ + "KeypointRCNN", + "KeypointRCNN_ResNet50_FPN_Weights", + "keypointrcnn_resnet50_fpn", +] + + +class KeypointRCNN(FasterRCNN): + """ + Implements Keypoint R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + - keypoints (FloatTensor[N, K, 3]): the K keypoints location for each of the N instances, in the + format [x, y, visibility], where visibility=0 means that the keypoint is not visible. + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the keypoint loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores or each prediction + - keypoints (FloatTensor[N, K, 3]): the locations of the predicted keypoints, in [x, y, v] format. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or and OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + If box_predictor is specified, num_classes should be None. + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN + rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training + rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing + rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training + rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing + rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh + box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes + box_head (nn.Module): module that takes the cropped feature maps as input + box_predictor (nn.Module): module that takes the output of box_head and returns the + classification logits and box regression deltas. + box_score_thresh (float): during inference, only return proposals with a classification score + greater than box_score_thresh + box_nms_thresh (float): NMS threshold for the prediction head. Used during inference + box_detections_per_img (int): maximum number of detections per image, for all classes. + box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be + considered as positive during training of the classification head + box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be + considered as negative during training of the classification head + box_batch_size_per_image (int): number of proposals that are sampled during training of the + classification head + box_positive_fraction (float): proportion of positive proposals in a mini-batch during training + of the classification head + bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the + bounding boxes + keypoint_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes, which will be used for the keypoint head. + keypoint_head (nn.Module): module that takes the cropped feature maps as input + keypoint_predictor (nn.Module): module that takes the output of the keypoint_head and returns the + heatmap logits + + Example:: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import KeypointRCNN + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # KeypointRCNN needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the RPN generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),)) + >>> + >>> # let's define what are the feature maps that we will + >>> # use to perform the region of interest cropping, as well as + >>> # the size of the crop after rescaling. + >>> # if your backbone returns a Tensor, featmap_names is expected to + >>> # be ['0']. More generally, the backbone should return an + >>> # OrderedDict[Tensor], and in featmap_names you can choose which + >>> # feature maps to use. + >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=7, + >>> sampling_ratio=2) + >>> + >>> keypoint_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=14, + >>> sampling_ratio=2) + >>> # put the pieces together inside a KeypointRCNN model + >>> model = KeypointRCNN(backbone, + >>> num_classes=2, + >>> rpn_anchor_generator=anchor_generator, + >>> box_roi_pool=roi_pooler, + >>> keypoint_roi_pool=keypoint_roi_pooler) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + def __init__( + self, + backbone, + num_classes=None, + # transform parameters + min_size=None, + max_size=1333, + image_mean=None, + image_std=None, + # RPN parameters + rpn_anchor_generator=None, + rpn_head=None, + rpn_pre_nms_top_n_train=2000, + rpn_pre_nms_top_n_test=1000, + rpn_post_nms_top_n_train=2000, + rpn_post_nms_top_n_test=1000, + rpn_nms_thresh=0.7, + rpn_fg_iou_thresh=0.7, + rpn_bg_iou_thresh=0.3, + rpn_batch_size_per_image=256, + rpn_positive_fraction=0.5, + rpn_score_thresh=0.0, + # Box parameters + box_roi_pool=None, + box_head=None, + box_predictor=None, + box_score_thresh=0.05, + box_nms_thresh=0.5, + box_detections_per_img=100, + box_fg_iou_thresh=0.5, + box_bg_iou_thresh=0.5, + box_batch_size_per_image=512, + box_positive_fraction=0.25, + bbox_reg_weights=None, + # keypoint parameters + keypoint_roi_pool=None, + keypoint_head=None, + keypoint_predictor=None, + num_keypoints=None, + **kwargs, + ): + + if not isinstance(keypoint_roi_pool, (MultiScaleRoIAlign, type(None))): + raise TypeError( + "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}" + ) + if min_size is None: + min_size = (640, 672, 704, 736, 768, 800) + + if num_keypoints is not None: + if keypoint_predictor is not None: + raise ValueError("num_keypoints should be None when keypoint_predictor is specified") + else: + num_keypoints = 17 + + out_channels = backbone.out_channels + + if keypoint_roi_pool is None: + keypoint_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2) + + if keypoint_head is None: + keypoint_layers = tuple(512 for _ in range(8)) + keypoint_head = KeypointRCNNHeads(out_channels, keypoint_layers) + + if keypoint_predictor is None: + keypoint_dim_reduced = 512 # == keypoint_layers[-1] + keypoint_predictor = KeypointRCNNPredictor(keypoint_dim_reduced, num_keypoints) + + super().__init__( + backbone, + num_classes, + # transform parameters + min_size, + max_size, + image_mean, + image_std, + # RPN-specific parameters + rpn_anchor_generator, + rpn_head, + rpn_pre_nms_top_n_train, + rpn_pre_nms_top_n_test, + rpn_post_nms_top_n_train, + rpn_post_nms_top_n_test, + rpn_nms_thresh, + rpn_fg_iou_thresh, + rpn_bg_iou_thresh, + rpn_batch_size_per_image, + rpn_positive_fraction, + rpn_score_thresh, + # Box parameters + box_roi_pool, + box_head, + box_predictor, + box_score_thresh, + box_nms_thresh, + box_detections_per_img, + box_fg_iou_thresh, + box_bg_iou_thresh, + box_batch_size_per_image, + box_positive_fraction, + bbox_reg_weights, + **kwargs, + ) + + self.roi_heads.keypoint_roi_pool = keypoint_roi_pool + self.roi_heads.keypoint_head = keypoint_head + self.roi_heads.keypoint_predictor = keypoint_predictor + + +class KeypointRCNNHeads(nn.Sequential): + def __init__(self, in_channels, layers): + d = [] + next_feature = in_channels + for out_channels in layers: + d.append(nn.Conv2d(next_feature, out_channels, 3, stride=1, padding=1)) + d.append(nn.ReLU(inplace=True)) + next_feature = out_channels + super().__init__(*d) + for m in self.children(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + nn.init.constant_(m.bias, 0) + + +class KeypointRCNNPredictor(nn.Module): + def __init__(self, in_channels, num_keypoints): + super().__init__() + input_features = in_channels + deconv_kernel = 4 + self.kps_score_lowres = nn.ConvTranspose2d( + input_features, + num_keypoints, + deconv_kernel, + stride=2, + padding=deconv_kernel // 2 - 1, + ) + nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu") + nn.init.constant_(self.kps_score_lowres.bias, 0) + self.up_scale = 2 + self.out_channels = num_keypoints + + def forward(self, x): + x = self.kps_score_lowres(x) + return torch.nn.functional.interpolate( + x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False + ) + + +_COMMON_META = { + "categories": _COCO_PERSON_CATEGORIES, + "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES, + "min_size": (1, 1), +} + + +class KeypointRCNN_ResNet50_FPN_Weights(WeightsEnum): + COCO_LEGACY = Weights( + url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-9f466800.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 59137258, + "recipe": "https://github.com/pytorch/vision/issues/1606", + "_metrics": { + "COCO-val2017": { + "box_map": 50.6, + "kp_map": 61.1, + } + }, + "_ops": 133.924, + "_file_size": 226.054, + "_docs": """ + These weights were produced by following a similar training recipe as on the paper but use a checkpoint + from an early epoch. + """, + }, + ) + COCO_V1 = Weights( + url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-fc266e95.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 59137258, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#keypoint-r-cnn", + "_metrics": { + "COCO-val2017": { + "box_map": 54.6, + "kp_map": 65.0, + } + }, + "_ops": 137.42, + "_file_size": 226.054, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + KeypointRCNN_ResNet50_FPN_Weights.COCO_LEGACY + if kwargs["pretrained"] == "legacy" + else KeypointRCNN_ResNet50_FPN_Weights.COCO_V1 + ), + ), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def keypointrcnn_resnet50_fpn( + *, + weights: Optional[KeypointRCNN_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + num_keypoints: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> KeypointRCNN: + """ + Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `Mask R-CNN `__. + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the + format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible. + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the keypoint loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detected instances: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each instance + - scores (``Tensor[N]``): the scores or each instance + - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format. + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size. + + Example:: + + >>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(weights=KeypointRCNN_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + >>> + >>> # optionally, if you want to export the model to ONNX: + >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11) + + Args: + weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr + num_classes (int, optional): number of output classes of the model (including the background) + num_keypoints (int, optional): number of keypoints + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 3. + + .. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights + :members: + """ + weights = KeypointRCNN_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"])) + else: + if num_classes is None: + num_classes = 2 + if num_keypoints is None: + num_keypoints = 17 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers) + model = KeypointRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == KeypointRCNN_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/mask_rcnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/mask_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..d1668ab423e52fee248d696d9d2f3ad1fcac90b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/mask_rcnn.py @@ -0,0 +1,590 @@ +from collections import OrderedDict +from typing import Any, Callable, Optional + +from torch import nn +from torchvision.ops import MultiScaleRoIAlign + +from ...ops import misc as misc_nn_ops +from ...transforms._presets import ObjectDetection +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from ._utils import overwrite_eps +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .faster_rcnn import _default_anchorgen, FasterRCNN, FastRCNNConvFCHead, RPNHead + + +__all__ = [ + "MaskRCNN", + "MaskRCNN_ResNet50_FPN_Weights", + "MaskRCNN_ResNet50_FPN_V2_Weights", + "maskrcnn_resnet50_fpn", + "maskrcnn_resnet50_fpn_v2", +] + + +class MaskRCNN(FasterRCNN): + """ + Implements Mask R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + - masks (UInt8Tensor[N, H, W]): the segmentation binary masks for each instance + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the mask loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores or each prediction + - masks (FloatTensor[N, 1, H, W]): the predicted masks for each instance, in 0-1 range. In order to + obtain the final segmentation masks, the soft masks can be thresholded, generally + with a value of 0.5 (mask >= 0.5) + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or and OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + If box_predictor is specified, num_classes should be None. + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN + rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training + rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing + rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training + rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing + rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh + box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes + box_head (nn.Module): module that takes the cropped feature maps as input + box_predictor (nn.Module): module that takes the output of box_head and returns the + classification logits and box regression deltas. + box_score_thresh (float): during inference, only return proposals with a classification score + greater than box_score_thresh + box_nms_thresh (float): NMS threshold for the prediction head. Used during inference + box_detections_per_img (int): maximum number of detections per image, for all classes. + box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be + considered as positive during training of the classification head + box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be + considered as negative during training of the classification head + box_batch_size_per_image (int): number of proposals that are sampled during training of the + classification head + box_positive_fraction (float): proportion of positive proposals in a mini-batch during training + of the classification head + bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the + bounding boxes + mask_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes, which will be used for the mask head. + mask_head (nn.Module): module that takes the cropped feature maps as input + mask_predictor (nn.Module): module that takes the output of the mask_head and returns the + segmentation mask logits + + Example:: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import MaskRCNN + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # MaskRCNN needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280 + >>> # so we need to add it here, + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the RPN generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),)) + >>> + >>> # let's define what are the feature maps that we will + >>> # use to perform the region of interest cropping, as well as + >>> # the size of the crop after rescaling. + >>> # if your backbone returns a Tensor, featmap_names is expected to + >>> # be ['0']. More generally, the backbone should return an + >>> # OrderedDict[Tensor], and in featmap_names you can choose which + >>> # feature maps to use. + >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=7, + >>> sampling_ratio=2) + >>> + >>> mask_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=14, + >>> sampling_ratio=2) + >>> # put the pieces together inside a MaskRCNN model + >>> model = MaskRCNN(backbone, + >>> num_classes=2, + >>> rpn_anchor_generator=anchor_generator, + >>> box_roi_pool=roi_pooler, + >>> mask_roi_pool=mask_roi_pooler) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + def __init__( + self, + backbone, + num_classes=None, + # transform parameters + min_size=800, + max_size=1333, + image_mean=None, + image_std=None, + # RPN parameters + rpn_anchor_generator=None, + rpn_head=None, + rpn_pre_nms_top_n_train=2000, + rpn_pre_nms_top_n_test=1000, + rpn_post_nms_top_n_train=2000, + rpn_post_nms_top_n_test=1000, + rpn_nms_thresh=0.7, + rpn_fg_iou_thresh=0.7, + rpn_bg_iou_thresh=0.3, + rpn_batch_size_per_image=256, + rpn_positive_fraction=0.5, + rpn_score_thresh=0.0, + # Box parameters + box_roi_pool=None, + box_head=None, + box_predictor=None, + box_score_thresh=0.05, + box_nms_thresh=0.5, + box_detections_per_img=100, + box_fg_iou_thresh=0.5, + box_bg_iou_thresh=0.5, + box_batch_size_per_image=512, + box_positive_fraction=0.25, + bbox_reg_weights=None, + # Mask parameters + mask_roi_pool=None, + mask_head=None, + mask_predictor=None, + **kwargs, + ): + + if not isinstance(mask_roi_pool, (MultiScaleRoIAlign, type(None))): + raise TypeError( + f"mask_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(mask_roi_pool)}" + ) + + if num_classes is not None: + if mask_predictor is not None: + raise ValueError("num_classes should be None when mask_predictor is specified") + + out_channels = backbone.out_channels + + if mask_roi_pool is None: + mask_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2) + + if mask_head is None: + mask_layers = (256, 256, 256, 256) + mask_dilation = 1 + mask_head = MaskRCNNHeads(out_channels, mask_layers, mask_dilation) + + if mask_predictor is None: + mask_predictor_in_channels = 256 # == mask_layers[-1] + mask_dim_reduced = 256 + mask_predictor = MaskRCNNPredictor(mask_predictor_in_channels, mask_dim_reduced, num_classes) + + super().__init__( + backbone, + num_classes, + # transform parameters + min_size, + max_size, + image_mean, + image_std, + # RPN-specific parameters + rpn_anchor_generator, + rpn_head, + rpn_pre_nms_top_n_train, + rpn_pre_nms_top_n_test, + rpn_post_nms_top_n_train, + rpn_post_nms_top_n_test, + rpn_nms_thresh, + rpn_fg_iou_thresh, + rpn_bg_iou_thresh, + rpn_batch_size_per_image, + rpn_positive_fraction, + rpn_score_thresh, + # Box parameters + box_roi_pool, + box_head, + box_predictor, + box_score_thresh, + box_nms_thresh, + box_detections_per_img, + box_fg_iou_thresh, + box_bg_iou_thresh, + box_batch_size_per_image, + box_positive_fraction, + bbox_reg_weights, + **kwargs, + ) + + self.roi_heads.mask_roi_pool = mask_roi_pool + self.roi_heads.mask_head = mask_head + self.roi_heads.mask_predictor = mask_predictor + + +class MaskRCNNHeads(nn.Sequential): + _version = 2 + + def __init__(self, in_channels, layers, dilation, norm_layer: Optional[Callable[..., nn.Module]] = None): + """ + Args: + in_channels (int): number of input channels + layers (list): feature dimensions of each FCN layer + dilation (int): dilation rate of kernel + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + blocks = [] + next_feature = in_channels + for layer_features in layers: + blocks.append( + misc_nn_ops.Conv2dNormActivation( + next_feature, + layer_features, + kernel_size=3, + stride=1, + padding=dilation, + dilation=dilation, + norm_layer=norm_layer, + ) + ) + next_feature = layer_features + + super().__init__(*blocks) + for layer in self.modules(): + if isinstance(layer, nn.Conv2d): + nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu") + if layer.bias is not None: + nn.init.zeros_(layer.bias) + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + num_blocks = len(self) + for i in range(num_blocks): + for type in ["weight", "bias"]: + old_key = f"{prefix}mask_fcn{i+1}.{type}" + new_key = f"{prefix}{i}.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + +class MaskRCNNPredictor(nn.Sequential): + def __init__(self, in_channels, dim_reduced, num_classes): + super().__init__( + OrderedDict( + [ + ("conv5_mask", nn.ConvTranspose2d(in_channels, dim_reduced, 2, 2, 0)), + ("relu", nn.ReLU(inplace=True)), + ("mask_fcn_logits", nn.Conv2d(dim_reduced, num_classes, 1, 1, 0)), + ] + ) + ) + + for name, param in self.named_parameters(): + if "weight" in name: + nn.init.kaiming_normal_(param, mode="fan_out", nonlinearity="relu") + # elif "bias" in name: + # nn.init.constant_(param, 0) + + +_COMMON_META = { + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), +} + + +class MaskRCNN_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 44401393, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#mask-r-cnn", + "_metrics": { + "COCO-val2017": { + "box_map": 37.9, + "mask_map": 34.6, + } + }, + "_ops": 134.38, + "_file_size": 169.84, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class MaskRCNN_ResNet50_FPN_V2_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/maskrcnn_resnet50_fpn_v2_coco-73cbd019.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 46359409, + "recipe": "https://github.com/pytorch/vision/pull/5773", + "_metrics": { + "COCO-val2017": { + "box_map": 47.4, + "mask_map": 41.8, + } + }, + "_ops": 333.577, + "_file_size": 177.219, + "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", MaskRCNN_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def maskrcnn_resnet50_fpn( + *, + weights: Optional[MaskRCNN_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> MaskRCNN: + """Mask R-CNN model with a ResNet-50-FPN backbone from the `Mask R-CNN + `_ paper. + + .. betastatus:: detection module + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + - masks (``UInt8Tensor[N, H, W]``): the segmentation binary masks for each instance + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the mask loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detected instances: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each instance + - scores (``Tensor[N]``): the scores or each instance + - masks (``UInt8Tensor[N, 1, H, W]``): the predicted masks for each instance, in ``0-1`` range. In order to + obtain the final segmentation masks, the soft masks can be thresholded, generally + with a value of 0.5 (``mask >= 0.5``) + + For more details on the output and on how to plot the masks, you may refer to :ref:`instance_seg_output`. + + Mask R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size. + + Example:: + + >>> model = torchvision.models.detection.maskrcnn_resnet50_fpn(weights=MaskRCNN_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + >>> + >>> # optionally, if you want to export the model to ONNX: + >>> torch.onnx.export(model, x, "mask_rcnn.onnx", opset_version = 11) + + Args: + weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.mask_rcnn.MaskRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights + :members: + """ + weights = MaskRCNN_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers) + model = MaskRCNN(backbone, num_classes=num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == MaskRCNN_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def maskrcnn_resnet50_fpn_v2( + *, + weights: Optional[MaskRCNN_ResNet50_FPN_V2_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = None, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> MaskRCNN: + """Improved Mask R-CNN model with a ResNet-50-FPN backbone from the `Benchmarking Detection Transfer + Learning with Vision Transformers `_ paper. + + .. betastatus:: detection module + + :func:`~torchvision.models.detection.maskrcnn_resnet50_fpn` for more details. + + Args: + weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.mask_rcnn.MaskRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights + :members: + """ + weights = MaskRCNN_ResNet50_FPN_V2_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + + backbone = resnet50(weights=weights_backbone, progress=progress) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d) + rpn_anchor_generator = _default_anchorgen() + rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2) + box_head = FastRCNNConvFCHead( + (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d + ) + mask_head = MaskRCNNHeads(backbone.out_channels, [256, 256, 256, 256], 1, norm_layer=nn.BatchNorm2d) + model = MaskRCNN( + backbone, + num_classes=num_classes, + rpn_anchor_generator=rpn_anchor_generator, + rpn_head=rpn_head, + box_head=box_head, + mask_head=mask_head, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/retinanet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/retinanet.py new file mode 100644 index 0000000000000000000000000000000000000000..cd77749d2c13778d4fec1d845247c1ab6297c33c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/retinanet.py @@ -0,0 +1,903 @@ +import math +import warnings +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ...ops import boxes as box_ops, misc as misc_nn_ops, sigmoid_focal_loss +from ...ops.feature_pyramid_network import LastLevelP6P7 +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from . import _utils as det_utils +from ._utils import _box_loss, overwrite_eps +from .anchor_utils import AnchorGenerator +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "RetinaNet", + "RetinaNet_ResNet50_FPN_Weights", + "RetinaNet_ResNet50_FPN_V2_Weights", + "retinanet_resnet50_fpn", + "retinanet_resnet50_fpn_v2", +] + + +def _sum(x: list[Tensor]) -> Tensor: + res = x[0] + for i in x[1:]: + res = res + i + return res + + +def _v1_to_v2_weights(state_dict, prefix): + for i in range(4): + for type in ["weight", "bias"]: + old_key = f"{prefix}conv.{2*i}.{type}" + new_key = f"{prefix}conv.{i}.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + +def _default_anchorgen(): + anchor_sizes = tuple((x, int(x * 2 ** (1.0 / 3)), int(x * 2 ** (2.0 / 3))) for x in [32, 64, 128, 256, 512]) + aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) + anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios) + return anchor_generator + + +class RetinaNetHead(nn.Module): + """ + A regression and classification head for use in RetinaNet. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_classes (int): number of classes to be predicted + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + + def __init__(self, in_channels, num_anchors, num_classes, norm_layer: Optional[Callable[..., nn.Module]] = None): + super().__init__() + self.classification_head = RetinaNetClassificationHead( + in_channels, num_anchors, num_classes, norm_layer=norm_layer + ) + self.regression_head = RetinaNetRegressionHead(in_channels, num_anchors, norm_layer=norm_layer) + + def compute_loss(self, targets, head_outputs, anchors, matched_idxs): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor], list[Tensor]) -> dict[str, Tensor] + return { + "classification": self.classification_head.compute_loss(targets, head_outputs, matched_idxs), + "bbox_regression": self.regression_head.compute_loss(targets, head_outputs, anchors, matched_idxs), + } + + def forward(self, x): + # type: (list[Tensor]) -> dict[str, Tensor] + return {"cls_logits": self.classification_head(x), "bbox_regression": self.regression_head(x)} + + +class RetinaNetClassificationHead(nn.Module): + """ + A classification head for use in RetinaNet. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_classes (int): number of classes to be predicted + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + + _version = 2 + + def __init__( + self, + in_channels, + num_anchors, + num_classes, + prior_probability=0.01, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + super().__init__() + + conv = [] + for _ in range(4): + conv.append(misc_nn_ops.Conv2dNormActivation(in_channels, in_channels, norm_layer=norm_layer)) + self.conv = nn.Sequential(*conv) + + for layer in self.conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0) + + self.cls_logits = nn.Conv2d(in_channels, num_anchors * num_classes, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.cls_logits.weight, std=0.01) + torch.nn.init.constant_(self.cls_logits.bias, -math.log((1 - prior_probability) / prior_probability)) + + self.num_classes = num_classes + self.num_anchors = num_anchors + + # This is to fix using det_utils.Matcher.BETWEEN_THRESHOLDS in TorchScript. + # TorchScript doesn't support class attributes. + # https://github.com/pytorch/vision/pull/1697#issuecomment-630255584 + self.BETWEEN_THRESHOLDS = det_utils.Matcher.BETWEEN_THRESHOLDS + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + _v1_to_v2_weights(state_dict, prefix) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def compute_loss(self, targets, head_outputs, matched_idxs): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor]) -> Tensor + losses = [] + + cls_logits = head_outputs["cls_logits"] + + for targets_per_image, cls_logits_per_image, matched_idxs_per_image in zip(targets, cls_logits, matched_idxs): + # determine only the foreground + foreground_idxs_per_image = matched_idxs_per_image >= 0 + num_foreground = foreground_idxs_per_image.sum() + + # create the target classification + gt_classes_target = torch.zeros_like(cls_logits_per_image) + gt_classes_target[ + foreground_idxs_per_image, + targets_per_image["labels"][matched_idxs_per_image[foreground_idxs_per_image]], + ] = 1.0 + + # find indices for which anchors should be ignored + valid_idxs_per_image = matched_idxs_per_image != self.BETWEEN_THRESHOLDS + + # compute the classification loss + losses.append( + sigmoid_focal_loss( + cls_logits_per_image[valid_idxs_per_image], + gt_classes_target[valid_idxs_per_image], + reduction="sum", + ) + / max(1, num_foreground) + ) + + return _sum(losses) / len(targets) + + def forward(self, x): + # type: (list[Tensor]) -> Tensor + all_cls_logits = [] + + for features in x: + cls_logits = self.conv(features) + cls_logits = self.cls_logits(cls_logits) + + # Permute classification output from (N, A * K, H, W) to (N, HWA, K). + N, _, H, W = cls_logits.shape + cls_logits = cls_logits.view(N, -1, self.num_classes, H, W) + cls_logits = cls_logits.permute(0, 3, 4, 1, 2) + cls_logits = cls_logits.reshape(N, -1, self.num_classes) # Size=(N, HWA, 4) + + all_cls_logits.append(cls_logits) + + return torch.cat(all_cls_logits, dim=1) + + +class RetinaNetRegressionHead(nn.Module): + """ + A regression head for use in RetinaNet. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + + _version = 2 + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + } + + def __init__(self, in_channels, num_anchors, norm_layer: Optional[Callable[..., nn.Module]] = None): + super().__init__() + + conv = [] + for _ in range(4): + conv.append(misc_nn_ops.Conv2dNormActivation(in_channels, in_channels, norm_layer=norm_layer)) + self.conv = nn.Sequential(*conv) + + self.bbox_reg = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.bbox_reg.weight, std=0.01) + torch.nn.init.zeros_(self.bbox_reg.bias) + + for layer in self.conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + if layer.bias is not None: + torch.nn.init.zeros_(layer.bias) + + self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0)) + self._loss_type = "l1" + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + _v1_to_v2_weights(state_dict, prefix) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def compute_loss(self, targets, head_outputs, anchors, matched_idxs): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor], list[Tensor]) -> Tensor + losses = [] + + bbox_regression = head_outputs["bbox_regression"] + + for targets_per_image, bbox_regression_per_image, anchors_per_image, matched_idxs_per_image in zip( + targets, bbox_regression, anchors, matched_idxs + ): + # determine only the foreground indices, ignore the rest + foreground_idxs_per_image = torch.where(matched_idxs_per_image >= 0)[0] + num_foreground = foreground_idxs_per_image.numel() + + # select only the foreground boxes + matched_gt_boxes_per_image = targets_per_image["boxes"][matched_idxs_per_image[foreground_idxs_per_image]] + bbox_regression_per_image = bbox_regression_per_image[foreground_idxs_per_image, :] + anchors_per_image = anchors_per_image[foreground_idxs_per_image, :] + + # compute the loss + losses.append( + _box_loss( + self._loss_type, + self.box_coder, + anchors_per_image, + matched_gt_boxes_per_image, + bbox_regression_per_image, + ) + / max(1, num_foreground) + ) + + return _sum(losses) / max(1, len(targets)) + + def forward(self, x): + # type: (list[Tensor]) -> Tensor + all_bbox_regression = [] + + for features in x: + bbox_regression = self.conv(features) + bbox_regression = self.bbox_reg(bbox_regression) + + # Permute bbox regression output from (N, 4 * A, H, W) to (N, HWA, 4). + N, _, H, W = bbox_regression.shape + bbox_regression = bbox_regression.view(N, -1, 4, H, W) + bbox_regression = bbox_regression.permute(0, 3, 4, 1, 2) + bbox_regression = bbox_regression.reshape(N, -1, 4) # Size=(N, HWA, 4) + + all_bbox_regression.append(bbox_regression) + + return torch.cat(all_bbox_regression, dim=1) + + +class RetinaNet(nn.Module): + """ + Implements RetinaNet. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores for each prediction + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or an OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + head (nn.Module): Module run on top of the feature pyramid. + Defaults to a module containing a classification and regression module. + score_thresh (float): Score threshold used for postprocessing the detections. + nms_thresh (float): NMS threshold used for postprocessing the detections. + detections_per_img (int): Number of best detections to keep after NMS. + fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training. + bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training. + topk_candidates (int): Number of best detections to keep before NMS. + + Example: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import RetinaNet + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # RetinaNet needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the network generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator( + >>> sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),) + >>> ) + >>> + >>> # put the pieces together inside a RetinaNet model + >>> model = RetinaNet(backbone, + >>> num_classes=2, + >>> anchor_generator=anchor_generator) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + } + + def __init__( + self, + backbone, + num_classes, + # transform parameters + min_size=800, + max_size=1333, + image_mean=None, + image_std=None, + # Anchor parameters + anchor_generator=None, + head=None, + proposal_matcher=None, + score_thresh=0.05, + nms_thresh=0.5, + detections_per_img=300, + fg_iou_thresh=0.5, + bg_iou_thresh=0.4, + topk_candidates=1000, + **kwargs, + ): + super().__init__() + _log_api_usage_once(self) + + if not hasattr(backbone, "out_channels"): + raise ValueError( + "backbone should contain an attribute out_channels " + "specifying the number of output channels (assumed to be the " + "same for all the levels)" + ) + self.backbone = backbone + + if not isinstance(anchor_generator, (AnchorGenerator, type(None))): + raise TypeError( + f"anchor_generator should be of type AnchorGenerator or None instead of {type(anchor_generator)}" + ) + + if anchor_generator is None: + anchor_generator = _default_anchorgen() + self.anchor_generator = anchor_generator + + if head is None: + head = RetinaNetHead(backbone.out_channels, anchor_generator.num_anchors_per_location()[0], num_classes) + self.head = head + + if proposal_matcher is None: + proposal_matcher = det_utils.Matcher( + fg_iou_thresh, + bg_iou_thresh, + allow_low_quality_matches=True, + ) + self.proposal_matcher = proposal_matcher + + self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0)) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + self.transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs) + + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + self.topk_candidates = topk_candidates + + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs(self, losses, detections): + # type: (dict[str, Tensor], list[dict[str, Tensor]]) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]] + if self.training: + return losses + + return detections + + def compute_loss(self, targets, head_outputs, anchors): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor]) -> dict[str, Tensor] + matched_idxs = [] + for anchors_per_image, targets_per_image in zip(anchors, targets): + if targets_per_image["boxes"].numel() == 0: + matched_idxs.append( + torch.full((anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device) + ) + continue + + match_quality_matrix = box_ops.box_iou(targets_per_image["boxes"], anchors_per_image) + matched_idxs.append(self.proposal_matcher(match_quality_matrix)) + + return self.head.compute_loss(targets, head_outputs, anchors, matched_idxs) + + def postprocess_detections(self, head_outputs, anchors, image_shapes): + # type: (dict[str, list[Tensor]], list[list[Tensor]], list[tuple[int, int]]) -> list[dict[str, Tensor]] + class_logits = head_outputs["cls_logits"] + box_regression = head_outputs["bbox_regression"] + + num_images = len(image_shapes) + + detections: list[dict[str, Tensor]] = [] + + for index in range(num_images): + box_regression_per_image = [br[index] for br in box_regression] + logits_per_image = [cl[index] for cl in class_logits] + anchors_per_image, image_shape = anchors[index], image_shapes[index] + + image_boxes = [] + image_scores = [] + image_labels = [] + + for box_regression_per_level, logits_per_level, anchors_per_level in zip( + box_regression_per_image, logits_per_image, anchors_per_image + ): + num_classes = logits_per_level.shape[-1] + + # remove low scoring boxes + scores_per_level = torch.sigmoid(logits_per_level).flatten() + keep_idxs = scores_per_level > self.score_thresh + scores_per_level = scores_per_level[keep_idxs] + topk_idxs = torch.where(keep_idxs)[0] + + # keep only topk scoring predictions + num_topk = det_utils._topk_min(topk_idxs, self.topk_candidates, 0) + scores_per_level, idxs = scores_per_level.topk(num_topk) + topk_idxs = topk_idxs[idxs] + + anchor_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + labels_per_level = topk_idxs % num_classes + + boxes_per_level = self.box_coder.decode_single( + box_regression_per_level[anchor_idxs], anchors_per_level[anchor_idxs] + ) + boxes_per_level = box_ops.clip_boxes_to_image(boxes_per_level, image_shape) + + image_boxes.append(boxes_per_level) + image_scores.append(scores_per_level) + image_labels.append(labels_per_level) + + image_boxes = torch.cat(image_boxes, dim=0) + image_scores = torch.cat(image_scores, dim=0) + image_labels = torch.cat(image_labels, dim=0) + + # non-maximum suppression + keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh) + keep = keep[: self.detections_per_img] + + detections.append( + { + "boxes": image_boxes[keep], + "scores": image_scores[keep], + "labels": image_labels[keep], + } + ) + + return detections + + def forward(self, images, targets=None): + # type: (list[Tensor], Optional[list[dict[str, Tensor]]]) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]] + """ + Args: + images (list[Tensor]): images to be processed + targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional) + + Returns: + result (list[BoxList] or dict[Tensor]): the output from the model. + During training, it returns a dict[Tensor] which contains the losses. + During testing, it returns list[BoxList] contains additional fields + like `scores`, `labels` and `mask` (for Mask R-CNN models). + + """ + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + torch._assert(isinstance(boxes, torch.Tensor), "Expected target boxes to be of type Tensor.") + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + "Expected target boxes to be a tensor of shape [N, 4].", + ) + + # get the original image sizes + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + # transform the input + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + # TODO: Move this to a function + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + # print the first degenerate box + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + "All bounding boxes should have positive height and width." + f" Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + # get the features from the backbone + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + + # TODO: Do we want a list or a dict? + features = list(features.values()) + + # compute the retinanet heads outputs using the features + head_outputs = self.head(features) + + # create the set of anchors + anchors = self.anchor_generator(images, features) + + losses = {} + detections: list[dict[str, Tensor]] = [] + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + # compute the losses + losses = self.compute_loss(targets, head_outputs, anchors) + else: + # recover level sizes + num_anchors_per_level = [x.size(2) * x.size(3) for x in features] + HW = 0 + for v in num_anchors_per_level: + HW += v + HWA = head_outputs["cls_logits"].size(1) + A = HWA // HW + num_anchors_per_level = [hw * A for hw in num_anchors_per_level] + + # split outputs per level + split_head_outputs: dict[str, list[Tensor]] = {} + for k in head_outputs: + split_head_outputs[k] = list(head_outputs[k].split(num_anchors_per_level, dim=1)) + split_anchors = [list(a.split(num_anchors_per_level)) for a in anchors] + + # compute the detections + detections = self.postprocess_detections(split_head_outputs, split_anchors, images.image_sizes) + detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("RetinaNet always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + return self.eager_outputs(losses, detections) + + +_COMMON_META = { + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), +} + + +class RetinaNet_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/retinanet_resnet50_fpn_coco-eeacb38b.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 34014999, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#retinanet", + "_metrics": { + "COCO-val2017": { + "box_map": 36.4, + } + }, + "_ops": 151.54, + "_file_size": 130.267, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class RetinaNet_ResNet50_FPN_V2_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/retinanet_resnet50_fpn_v2_coco-5905b1c5.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 38198935, + "recipe": "https://github.com/pytorch/vision/pull/5756", + "_metrics": { + "COCO-val2017": { + "box_map": 41.5, + } + }, + "_ops": 152.238, + "_file_size": 146.037, + "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", RetinaNet_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def retinanet_resnet50_fpn( + *, + weights: Optional[RetinaNet_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> RetinaNet: + """ + Constructs a RetinaNet model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `Focal Loss for Dense Object Detection `_. + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each detection + - scores (``Tensor[N]``): the scores of each detection + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Example:: + + >>> model = torchvision.models.detection.retinanet_resnet50_fpn(weights=RetinaNet_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for + the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights + :members: + """ + weights = RetinaNet_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + # skip P2 because it generates too many anchors (according to their paper) + backbone = _resnet_fpn_extractor( + backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(256, 256) + ) + model = RetinaNet(backbone, num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == RetinaNet_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", RetinaNet_ResNet50_FPN_V2_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def retinanet_resnet50_fpn_v2( + *, + weights: Optional[RetinaNet_ResNet50_FPN_V2_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = None, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> RetinaNet: + """ + Constructs an improved RetinaNet model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection + `_. + + :func:`~torchvision.models.detection.retinanet_resnet50_fpn` for more details. + + Args: + weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for + the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights + :members: + """ + weights = RetinaNet_ResNet50_FPN_V2_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + + backbone = resnet50(weights=weights_backbone, progress=progress) + backbone = _resnet_fpn_extractor( + backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(2048, 256) + ) + anchor_generator = _default_anchorgen() + head = RetinaNetHead( + backbone.out_channels, + anchor_generator.num_anchors_per_location()[0], + num_classes, + norm_layer=partial(nn.GroupNorm, 32), + ) + head.regression_head._loss_type = "giou" + model = RetinaNet(backbone, num_classes, anchor_generator=anchor_generator, head=head, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/roi_heads.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/roi_heads.py new file mode 100644 index 0000000000000000000000000000000000000000..4e7216745370f87e2dd5fdb2ce926dcb0a188e6d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/roi_heads.py @@ -0,0 +1,878 @@ +from typing import Optional + +import torch +import torch.nn.functional as F +import torchvision +from torch import nn +from torchvision.ops import boxes as box_ops, roi_align + +from . import _utils as det_utils + + +def fastrcnn_loss( + class_logits: torch.Tensor, + box_regression: torch.Tensor, + labels: list[torch.Tensor], + regression_targets: list[torch.Tensor], +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Computes the loss for Faster R-CNN. + + Args: + class_logits (Tensor) + box_regression (Tensor) + labels (list[BoxList]) + regression_targets (Tensor) + + Returns: + classification_loss (Tensor) + box_loss (Tensor) + """ + + labels = torch.cat(labels, dim=0) + regression_targets = torch.cat(regression_targets, dim=0) + + classification_loss = F.cross_entropy(class_logits, labels) + + # get indices that correspond to the regression targets for + # the corresponding ground truth labels, to be used with + # advanced indexing + sampled_pos_inds_subset = torch.where(labels > 0)[0] + labels_pos = labels[sampled_pos_inds_subset] + N, num_classes = class_logits.shape + box_regression = box_regression.reshape(N, box_regression.size(-1) // 4, 4) + + box_loss = F.smooth_l1_loss( + box_regression[sampled_pos_inds_subset, labels_pos], + regression_targets[sampled_pos_inds_subset], + beta=1 / 9, + reduction="sum", + ) + box_loss = box_loss / labels.numel() + + return classification_loss, box_loss + + +def maskrcnn_inference(x: torch.Tensor, labels: list[torch.Tensor]) -> list[torch.Tensor]: + """ + From the results of the CNN, post process the masks + by taking the mask corresponding to the class with max + probability (which are of fixed size and directly output + by the CNN) and return the masks in the mask field of the BoxList. + + Args: + x (Tensor): the mask logits + labels (list[BoxList]): bounding boxes that are used as + reference, one for each image + + Returns: + results (list[BoxList]): one BoxList for each image, containing + the extra field mask + """ + mask_prob = x.sigmoid() + + # select masks corresponding to the predicted classes + num_masks = x.shape[0] + boxes_per_image = [label.shape[0] for label in labels] + labels = torch.cat(labels) + index = torch.arange(num_masks, device=labels.device) + mask_prob = mask_prob[index, labels][:, None] + mask_prob = mask_prob.split(boxes_per_image, dim=0) + + return mask_prob + + +def project_masks_on_boxes(gt_masks, boxes, matched_idxs, M): + # type: (Tensor, Tensor, Tensor, int) -> Tensor + """ + Given segmentation masks and the bounding boxes corresponding + to the location of the masks in the image, this function + crops and resizes the masks in the position defined by the + boxes. This prepares the masks for them to be fed to the + loss computation as the targets. + """ + matched_idxs = matched_idxs.to(boxes) + rois = torch.cat([matched_idxs[:, None], boxes], dim=1) + gt_masks = gt_masks[:, None].to(rois) + return roi_align(gt_masks, rois, (M, M), 1.0)[:, 0] + + +def maskrcnn_loss(mask_logits, proposals, gt_masks, gt_labels, mask_matched_idxs): + # type: (Tensor, list[Tensor], list[Tensor], list[Tensor], list[Tensor]) -> Tensor + """ + Args: + proposals (list[BoxList]) + mask_logits (Tensor) + targets (list[BoxList]) + + Return: + mask_loss (Tensor): scalar tensor containing the loss + """ + + discretization_size = mask_logits.shape[-1] + labels = [gt_label[idxs] for gt_label, idxs in zip(gt_labels, mask_matched_idxs)] + mask_targets = [ + project_masks_on_boxes(m, p, i, discretization_size) for m, p, i in zip(gt_masks, proposals, mask_matched_idxs) + ] + + labels = torch.cat(labels, dim=0) + mask_targets = torch.cat(mask_targets, dim=0) + + # torch.mean (in binary_cross_entropy_with_logits) doesn't + # accept empty tensors, so handle it separately + if mask_targets.numel() == 0: + return mask_logits.sum() * 0 + + mask_loss = F.binary_cross_entropy_with_logits( + mask_logits[torch.arange(labels.shape[0], device=labels.device), labels], mask_targets + ) + return mask_loss + + +def keypoints_to_heatmap(keypoints, rois, heatmap_size): + # type: (Tensor, Tensor, int) -> tuple[Tensor, Tensor] + offset_x = rois[:, 0] + offset_y = rois[:, 1] + scale_x = heatmap_size / (rois[:, 2] - rois[:, 0]) + scale_y = heatmap_size / (rois[:, 3] - rois[:, 1]) + + offset_x = offset_x[:, None] + offset_y = offset_y[:, None] + scale_x = scale_x[:, None] + scale_y = scale_y[:, None] + + x = keypoints[..., 0] + y = keypoints[..., 1] + + x_boundary_inds = x == rois[:, 2][:, None] + y_boundary_inds = y == rois[:, 3][:, None] + + x = (x - offset_x) * scale_x + x = x.floor().long() + y = (y - offset_y) * scale_y + y = y.floor().long() + + x[x_boundary_inds] = heatmap_size - 1 + y[y_boundary_inds] = heatmap_size - 1 + + valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size) + vis = keypoints[..., 2] > 0 + valid = (valid_loc & vis).long() + + lin_ind = y * heatmap_size + x + heatmaps = lin_ind * valid + + return heatmaps, valid + + +def _onnx_heatmaps_to_keypoints( + maps, maps_i, roi_map_width, roi_map_height, widths_i, heights_i, offset_x_i, offset_y_i +): + num_keypoints = torch.scalar_tensor(maps.size(1), dtype=torch.int64) + + width_correction = widths_i / roi_map_width + height_correction = heights_i / roi_map_height + + roi_map = F.interpolate( + maps_i[:, None], size=(int(roi_map_height), int(roi_map_width)), mode="bicubic", align_corners=False + )[:, 0] + + w = torch.scalar_tensor(roi_map.size(2), dtype=torch.int64) + pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1) + + x_int = pos % w + y_int = (pos - x_int) // w + + x = (torch.tensor(0.5, dtype=torch.float32) + x_int.to(dtype=torch.float32)) * width_correction.to( + dtype=torch.float32 + ) + y = (torch.tensor(0.5, dtype=torch.float32) + y_int.to(dtype=torch.float32)) * height_correction.to( + dtype=torch.float32 + ) + + xy_preds_i_0 = x + offset_x_i.to(dtype=torch.float32) + xy_preds_i_1 = y + offset_y_i.to(dtype=torch.float32) + xy_preds_i_2 = torch.ones(xy_preds_i_1.shape, dtype=torch.float32) + xy_preds_i = torch.stack( + [ + xy_preds_i_0.to(dtype=torch.float32), + xy_preds_i_1.to(dtype=torch.float32), + xy_preds_i_2.to(dtype=torch.float32), + ], + 0, + ) + + # TODO: simplify when indexing without rank will be supported by ONNX + base = num_keypoints * num_keypoints + num_keypoints + 1 + ind = torch.arange(num_keypoints) + ind = ind.to(dtype=torch.int64) * base + end_scores_i = ( + roi_map.index_select(1, y_int.to(dtype=torch.int64)) + .index_select(2, x_int.to(dtype=torch.int64)) + .view(-1) + .index_select(0, ind.to(dtype=torch.int64)) + ) + + return xy_preds_i, end_scores_i + + +@torch.jit._script_if_tracing +def _onnx_heatmaps_to_keypoints_loop( + maps, rois, widths_ceil, heights_ceil, widths, heights, offset_x, offset_y, num_keypoints +): + xy_preds = torch.zeros((0, 3, int(num_keypoints)), dtype=torch.float32, device=maps.device) + end_scores = torch.zeros((0, int(num_keypoints)), dtype=torch.float32, device=maps.device) + + for i in range(int(rois.size(0))): + xy_preds_i, end_scores_i = _onnx_heatmaps_to_keypoints( + maps, maps[i], widths_ceil[i], heights_ceil[i], widths[i], heights[i], offset_x[i], offset_y[i] + ) + xy_preds = torch.cat((xy_preds.to(dtype=torch.float32), xy_preds_i.unsqueeze(0).to(dtype=torch.float32)), 0) + end_scores = torch.cat( + (end_scores.to(dtype=torch.float32), end_scores_i.to(dtype=torch.float32).unsqueeze(0)), 0 + ) + return xy_preds, end_scores + + +def heatmaps_to_keypoints(maps, rois): + """Extract predicted keypoint locations from heatmaps. Output has shape + (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob) + for each keypoint. + """ + # This function converts a discrete image coordinate in a HEATMAP_SIZE x + # HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain + # consistency with keypoints_to_heatmap_labels by using the conversion from + # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a + # continuous coordinate. + offset_x = rois[:, 0] + offset_y = rois[:, 1] + + widths = rois[:, 2] - rois[:, 0] + heights = rois[:, 3] - rois[:, 1] + widths = widths.clamp(min=1) + heights = heights.clamp(min=1) + widths_ceil = widths.ceil() + heights_ceil = heights.ceil() + + num_keypoints = maps.shape[1] + + if torchvision._is_tracing(): + xy_preds, end_scores = _onnx_heatmaps_to_keypoints_loop( + maps, + rois, + widths_ceil, + heights_ceil, + widths, + heights, + offset_x, + offset_y, + torch.scalar_tensor(num_keypoints, dtype=torch.int64), + ) + return xy_preds.permute(0, 2, 1), end_scores + + xy_preds = torch.zeros((len(rois), 3, num_keypoints), dtype=torch.float32, device=maps.device) + end_scores = torch.zeros((len(rois), num_keypoints), dtype=torch.float32, device=maps.device) + for i in range(len(rois)): + roi_map_width = int(widths_ceil[i].item()) + roi_map_height = int(heights_ceil[i].item()) + width_correction = widths[i] / roi_map_width + height_correction = heights[i] / roi_map_height + roi_map = F.interpolate( + maps[i][:, None], size=(roi_map_height, roi_map_width), mode="bicubic", align_corners=False + )[:, 0] + # roi_map_probs = scores_to_probs(roi_map.copy()) + w = roi_map.shape[2] + pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1) + + x_int = pos % w + y_int = torch.div(pos - x_int, w, rounding_mode="floor") + # assert (roi_map_probs[k, y_int, x_int] == + # roi_map_probs[k, :, :].max()) + x = (x_int.float() + 0.5) * width_correction + y = (y_int.float() + 0.5) * height_correction + xy_preds[i, 0, :] = x + offset_x[i] + xy_preds[i, 1, :] = y + offset_y[i] + xy_preds[i, 2, :] = 1 + end_scores[i, :] = roi_map[torch.arange(num_keypoints, device=roi_map.device), y_int, x_int] + + return xy_preds.permute(0, 2, 1), end_scores + + +def keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs): + # type: (Tensor, list[Tensor], list[Tensor], list[Tensor]) -> Tensor + N, K, H, W = keypoint_logits.shape + if H != W: + raise ValueError( + f"keypoint_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}" + ) + discretization_size = H + heatmaps = [] + valid = [] + for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs): + kp = gt_kp_in_image[midx] + heatmaps_per_image, valid_per_image = keypoints_to_heatmap(kp, proposals_per_image, discretization_size) + heatmaps.append(heatmaps_per_image.view(-1)) + valid.append(valid_per_image.view(-1)) + + keypoint_targets = torch.cat(heatmaps, dim=0) + valid = torch.cat(valid, dim=0).to(dtype=torch.uint8) + valid = torch.where(valid)[0] + + # torch.mean (in binary_cross_entropy_with_logits) doesn't + # accept empty tensors, so handle it sepaartely + if keypoint_targets.numel() == 0 or len(valid) == 0: + return keypoint_logits.sum() * 0 + + keypoint_logits = keypoint_logits.view(N * K, H * W) + + keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid]) + return keypoint_loss + + +def keypointrcnn_inference(x, boxes): + # type: (Tensor, list[Tensor]) -> tuple[list[Tensor], list[Tensor]] + kp_probs = [] + kp_scores = [] + + boxes_per_image = [box.size(0) for box in boxes] + x2 = x.split(boxes_per_image, dim=0) + + for xx, bb in zip(x2, boxes): + kp_prob, scores = heatmaps_to_keypoints(xx, bb) + kp_probs.append(kp_prob) + kp_scores.append(scores) + + return kp_probs, kp_scores + + +def _onnx_expand_boxes(boxes, scale): + # type: (Tensor, float) -> Tensor + w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5 + h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5 + x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5 + y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5 + + w_half = w_half.to(dtype=torch.float32) * scale + h_half = h_half.to(dtype=torch.float32) * scale + + boxes_exp0 = x_c - w_half + boxes_exp1 = y_c - h_half + boxes_exp2 = x_c + w_half + boxes_exp3 = y_c + h_half + boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1) + return boxes_exp + + +# the next two functions should be merged inside Masker +# but are kept here for the moment while we need them +# temporarily for paste_mask_in_image +def expand_boxes(boxes, scale): + # type: (Tensor, float) -> Tensor + if torchvision._is_tracing(): + return _onnx_expand_boxes(boxes, scale) + w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5 + h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5 + x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5 + y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5 + + w_half *= scale + h_half *= scale + + boxes_exp = torch.zeros_like(boxes) + boxes_exp[:, 0] = x_c - w_half + boxes_exp[:, 2] = x_c + w_half + boxes_exp[:, 1] = y_c - h_half + boxes_exp[:, 3] = y_c + h_half + return boxes_exp + + +@torch.jit.unused +def expand_masks_tracing_scale(M, padding): + # type: (int, int) -> float + return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32) + + +def expand_masks(mask, padding): + # type: (Tensor, int) -> tuple[Tensor, float] + M = mask.shape[-1] + if torch._C._get_tracing_state(): # could not import is_tracing(), not sure why + scale = expand_masks_tracing_scale(M, padding) + else: + scale = float(M + 2 * padding) / M + padded_mask = F.pad(mask, (padding,) * 4) + return padded_mask, scale + + +def paste_mask_in_image(mask, box, im_h, im_w): + # type: (Tensor, Tensor, int, int) -> Tensor + TO_REMOVE = 1 + w = int(box[2] - box[0] + TO_REMOVE) + h = int(box[3] - box[1] + TO_REMOVE) + w = max(w, 1) + h = max(h, 1) + + # Set shape to [batchxCxHxW] + mask = mask.expand((1, 1, -1, -1)) + + # Resize mask + mask = F.interpolate(mask, size=(h, w), mode="bilinear", align_corners=False) + mask = mask[0][0] + + im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device) + x_0 = max(box[0], 0) + x_1 = min(box[2] + 1, im_w) + y_0 = max(box[1], 0) + y_1 = min(box[3] + 1, im_h) + + im_mask[y_0:y_1, x_0:x_1] = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])] + return im_mask + + +def _onnx_paste_mask_in_image(mask, box, im_h, im_w): + one = torch.ones(1, dtype=torch.int64) + zero = torch.zeros(1, dtype=torch.int64) + + w = box[2] - box[0] + one + h = box[3] - box[1] + one + w = torch.max(torch.cat((w, one))) + h = torch.max(torch.cat((h, one))) + + # Set shape to [batchxCxHxW] + mask = mask.expand((1, 1, mask.size(0), mask.size(1))) + + # Resize mask + mask = F.interpolate(mask, size=(int(h), int(w)), mode="bilinear", align_corners=False) + mask = mask[0][0] + + x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero))) + x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0)))) + y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero))) + y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0)))) + + unpaded_im_mask = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])] + + # TODO : replace below with a dynamic padding when support is added in ONNX + + # pad y + zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1)) + zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1)) + concat_0 = torch.cat((zeros_y0, unpaded_im_mask.to(dtype=torch.float32), zeros_y1), 0)[0:im_h, :] + # pad x + zeros_x0 = torch.zeros(concat_0.size(0), x_0) + zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1) + im_mask = torch.cat((zeros_x0, concat_0, zeros_x1), 1)[:, :im_w] + return im_mask + + +@torch.jit._script_if_tracing +def _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w): + res_append = torch.zeros(0, im_h, im_w) + for i in range(masks.size(0)): + mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w) + mask_res = mask_res.unsqueeze(0) + res_append = torch.cat((res_append, mask_res)) + return res_append + + +def paste_masks_in_image(masks, boxes, img_shape, padding=1): + # type: (Tensor, Tensor, tuple[int, int], int) -> Tensor + masks, scale = expand_masks(masks, padding=padding) + boxes = expand_boxes(boxes, scale).to(dtype=torch.int64) + im_h, im_w = img_shape + + if torchvision._is_tracing(): + return _onnx_paste_masks_in_image_loop( + masks, boxes, torch.scalar_tensor(im_h, dtype=torch.int64), torch.scalar_tensor(im_w, dtype=torch.int64) + )[:, None] + res = [paste_mask_in_image(m[0], b, im_h, im_w) for m, b in zip(masks, boxes)] + if len(res) > 0: + ret = torch.stack(res, dim=0)[:, None] + else: + ret = masks.new_empty((0, 1, im_h, im_w)) + return ret + + +class RoIHeads(nn.Module): + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler, + } + + def __init__( + self, + box_roi_pool, + box_head, + box_predictor, + # Faster R-CNN training + fg_iou_thresh, + bg_iou_thresh, + batch_size_per_image, + positive_fraction, + bbox_reg_weights, + # Faster R-CNN inference + score_thresh, + nms_thresh, + detections_per_img, + # Mask + mask_roi_pool=None, + mask_head=None, + mask_predictor=None, + keypoint_roi_pool=None, + keypoint_head=None, + keypoint_predictor=None, + ): + super().__init__() + + self.box_similarity = box_ops.box_iou + # assign ground-truth boxes for each proposal + self.proposal_matcher = det_utils.Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False) + + self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction) + + if bbox_reg_weights is None: + bbox_reg_weights = (10.0, 10.0, 5.0, 5.0) + self.box_coder = det_utils.BoxCoder(bbox_reg_weights) + + self.box_roi_pool = box_roi_pool + self.box_head = box_head + self.box_predictor = box_predictor + + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + + self.mask_roi_pool = mask_roi_pool + self.mask_head = mask_head + self.mask_predictor = mask_predictor + + self.keypoint_roi_pool = keypoint_roi_pool + self.keypoint_head = keypoint_head + self.keypoint_predictor = keypoint_predictor + + def has_mask(self): + if self.mask_roi_pool is None: + return False + if self.mask_head is None: + return False + if self.mask_predictor is None: + return False + return True + + def has_keypoint(self): + if self.keypoint_roi_pool is None: + return False + if self.keypoint_head is None: + return False + if self.keypoint_predictor is None: + return False + return True + + def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels): + # type: (list[Tensor], list[Tensor], list[Tensor]) -> tuple[list[Tensor], list[Tensor]] + matched_idxs = [] + labels = [] + for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels): + + if gt_boxes_in_image.numel() == 0: + # Background image + device = proposals_in_image.device + clamped_matched_idxs_in_image = torch.zeros( + (proposals_in_image.shape[0],), dtype=torch.int64, device=device + ) + labels_in_image = torch.zeros((proposals_in_image.shape[0],), dtype=torch.int64, device=device) + else: + # set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands + match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image) + matched_idxs_in_image = self.proposal_matcher(match_quality_matrix) + + clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0) + + labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image] + labels_in_image = labels_in_image.to(dtype=torch.int64) + + # Label background (below the low threshold) + bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD + labels_in_image[bg_inds] = 0 + + # Label ignore proposals (between low and high thresholds) + ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS + labels_in_image[ignore_inds] = -1 # -1 is ignored by sampler + + matched_idxs.append(clamped_matched_idxs_in_image) + labels.append(labels_in_image) + return matched_idxs, labels + + def subsample(self, labels): + # type: (list[Tensor]) -> list[Tensor] + sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) + sampled_inds = [] + for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)): + img_sampled_inds = torch.where(pos_inds_img | neg_inds_img)[0] + sampled_inds.append(img_sampled_inds) + return sampled_inds + + def add_gt_proposals(self, proposals, gt_boxes): + # type: (list[Tensor], list[Tensor]) -> list[Tensor] + proposals = [torch.cat((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)] + + return proposals + + def check_targets(self, targets): + # type: (Optional[list[dict[str, Tensor]]]) -> None + if targets is None: + raise ValueError("targets should not be None") + if not all(["boxes" in t for t in targets]): + raise ValueError("Every element of targets should have a boxes key") + if not all(["labels" in t for t in targets]): + raise ValueError("Every element of targets should have a labels key") + if self.has_mask(): + if not all(["masks" in t for t in targets]): + raise ValueError("Every element of targets should have a masks key") + + def select_training_samples( + self, + proposals, # type: list[Tensor] + targets, # type: Optional[list[dict[str, Tensor]]] + ): + # type: (...) -> tuple[list[Tensor], list[Tensor], list[Tensor], list[Tensor]] + self.check_targets(targets) + if targets is None: + raise ValueError("targets should not be None") + dtype = proposals[0].dtype + device = proposals[0].device + + gt_boxes = [t["boxes"].to(dtype) for t in targets] + gt_labels = [t["labels"] for t in targets] + + # append ground-truth bboxes to propos + proposals = self.add_gt_proposals(proposals, gt_boxes) + + # get matching gt indices for each proposal + matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels) + # sample a fixed proportion of positive-negative proposals + sampled_inds = self.subsample(labels) + matched_gt_boxes = [] + num_images = len(proposals) + for img_id in range(num_images): + img_sampled_inds = sampled_inds[img_id] + proposals[img_id] = proposals[img_id][img_sampled_inds] + labels[img_id] = labels[img_id][img_sampled_inds] + matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds] + + gt_boxes_in_image = gt_boxes[img_id] + if gt_boxes_in_image.numel() == 0: + gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device) + matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]]) + + regression_targets = self.box_coder.encode(matched_gt_boxes, proposals) + return proposals, matched_idxs, labels, regression_targets + + def postprocess_detections( + self, + class_logits, # type: Tensor + box_regression, # type: Tensor + proposals, # type: list[Tensor] + image_shapes, # type: list[tuple[int, int]] + ): + # type: (...) -> tuple[list[Tensor], list[Tensor], list[Tensor]] + device = class_logits.device + num_classes = class_logits.shape[-1] + + boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals] + pred_boxes = self.box_coder.decode(box_regression, proposals) + + pred_scores = F.softmax(class_logits, -1) + + pred_boxes_list = pred_boxes.split(boxes_per_image, 0) + pred_scores_list = pred_scores.split(boxes_per_image, 0) + + all_boxes = [] + all_scores = [] + all_labels = [] + for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes): + boxes = box_ops.clip_boxes_to_image(boxes, image_shape) + + # create labels for each prediction + labels = torch.arange(num_classes, device=device) + labels = labels.view(1, -1).expand_as(scores) + + # remove predictions with the background label + boxes = boxes[:, 1:] + scores = scores[:, 1:] + labels = labels[:, 1:] + + # batch everything, by making every class prediction be a separate instance + boxes = boxes.reshape(-1, 4) + scores = scores.reshape(-1) + labels = labels.reshape(-1) + + # remove low scoring boxes + inds = torch.where(scores > self.score_thresh)[0] + boxes, scores, labels = boxes[inds], scores[inds], labels[inds] + + # remove empty boxes + keep = box_ops.remove_small_boxes(boxes, min_size=1e-2) + boxes, scores, labels = boxes[keep], scores[keep], labels[keep] + + # non-maximum suppression, independently done per class + keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh) + # keep only topk scoring predictions + keep = keep[: self.detections_per_img] + boxes, scores, labels = boxes[keep], scores[keep], labels[keep] + + all_boxes.append(boxes) + all_scores.append(scores) + all_labels.append(labels) + + return all_boxes, all_scores, all_labels + + def forward( + self, + features: dict[str, torch.Tensor], + proposals: list[torch.Tensor], + image_shapes: list[tuple[int, int]], + targets: Optional[list[dict[str, torch.Tensor]]] = None, + ) -> tuple[list[dict[str, torch.Tensor]], dict[str, torch.Tensor]]: + """ + Args: + features (List[Tensor]) + proposals (List[Tensor[N, 4]]) + image_shapes (List[Tuple[H, W]]) + targets (List[Dict]) + """ + if targets is not None: + for t in targets: + # TODO: https://github.com/pytorch/pytorch/issues/26731 + floating_point_types = (torch.float, torch.double, torch.half) + if t["boxes"].dtype not in floating_point_types: + raise TypeError(f"target boxes must of float type, instead got {t['boxes'].dtype}") + if not t["labels"].dtype == torch.int64: + raise TypeError(f"target labels must of int64 type, instead got {t['labels'].dtype}") + if self.has_keypoint(): + if not t["keypoints"].dtype == torch.float32: + raise TypeError(f"target keypoints must of float type, instead got {t['keypoints'].dtype}") + + if self.training: + proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets) + else: + labels = None + regression_targets = None + matched_idxs = None + + box_features = self.box_roi_pool(features, proposals, image_shapes) + box_features = self.box_head(box_features) + class_logits, box_regression = self.box_predictor(box_features) + + result: list[dict[str, torch.Tensor]] = [] + losses = {} + if self.training: + if labels is None: + raise ValueError("labels cannot be None") + if regression_targets is None: + raise ValueError("regression_targets cannot be None") + loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets) + losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg} + else: + boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals, image_shapes) + num_images = len(boxes) + for i in range(num_images): + result.append( + { + "boxes": boxes[i], + "labels": labels[i], + "scores": scores[i], + } + ) + + if self.has_mask(): + mask_proposals = [p["boxes"] for p in result] + if self.training: + if matched_idxs is None: + raise ValueError("if in training, matched_idxs should not be None") + + # during training, only focus on positive boxes + num_images = len(proposals) + mask_proposals = [] + pos_matched_idxs = [] + for img_id in range(num_images): + pos = torch.where(labels[img_id] > 0)[0] + mask_proposals.append(proposals[img_id][pos]) + pos_matched_idxs.append(matched_idxs[img_id][pos]) + else: + pos_matched_idxs = None + + if self.mask_roi_pool is not None: + mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes) + mask_features = self.mask_head(mask_features) + mask_logits = self.mask_predictor(mask_features) + else: + raise Exception("Expected mask_roi_pool to be not None") + + loss_mask = {} + if self.training: + if targets is None or pos_matched_idxs is None or mask_logits is None: + raise ValueError("targets, pos_matched_idxs, mask_logits cannot be None when training") + + gt_masks = [t["masks"] for t in targets] + gt_labels = [t["labels"] for t in targets] + rcnn_loss_mask = maskrcnn_loss(mask_logits, mask_proposals, gt_masks, gt_labels, pos_matched_idxs) + loss_mask = {"loss_mask": rcnn_loss_mask} + else: + labels = [r["labels"] for r in result] + masks_probs = maskrcnn_inference(mask_logits, labels) + for mask_prob, r in zip(masks_probs, result): + r["masks"] = mask_prob + + losses.update(loss_mask) + + # keep none checks in if conditional so torchscript will conditionally + # compile each branch + if ( + self.keypoint_roi_pool is not None + and self.keypoint_head is not None + and self.keypoint_predictor is not None + ): + keypoint_proposals = [p["boxes"] for p in result] + if self.training: + # during training, only focus on positive boxes + num_images = len(proposals) + keypoint_proposals = [] + pos_matched_idxs = [] + if matched_idxs is None: + raise ValueError("if in trainning, matched_idxs should not be None") + + for img_id in range(num_images): + pos = torch.where(labels[img_id] > 0)[0] + keypoint_proposals.append(proposals[img_id][pos]) + pos_matched_idxs.append(matched_idxs[img_id][pos]) + else: + pos_matched_idxs = None + + keypoint_features = self.keypoint_roi_pool(features, keypoint_proposals, image_shapes) + keypoint_features = self.keypoint_head(keypoint_features) + keypoint_logits = self.keypoint_predictor(keypoint_features) + + loss_keypoint = {} + if self.training: + if targets is None or pos_matched_idxs is None: + raise ValueError("both targets and pos_matched_idxs should not be None when in training mode") + + gt_keypoints = [t["keypoints"] for t in targets] + rcnn_loss_keypoint = keypointrcnn_loss( + keypoint_logits, keypoint_proposals, gt_keypoints, pos_matched_idxs + ) + loss_keypoint = {"loss_keypoint": rcnn_loss_keypoint} + else: + if keypoint_logits is None or keypoint_proposals is None: + raise ValueError( + "both keypoint_logits and keypoint_proposals should not be None when not in training mode" + ) + + keypoints_probs, kp_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals) + for keypoint_prob, kps, r in zip(keypoints_probs, kp_scores, result): + r["keypoints"] = keypoint_prob + r["keypoints_scores"] = kps + losses.update(loss_keypoint) + + return result, losses diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/rpn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/rpn.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5718922cb2cb001a5e47f48731b733ffd808eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/rpn.py @@ -0,0 +1,387 @@ +from typing import Optional + +import torch +from torch import nn, Tensor +from torch.nn import functional as F +from torchvision.ops import boxes as box_ops, Conv2dNormActivation + +from . import _utils as det_utils + +# Import AnchorGenerator to keep compatibility. +from .anchor_utils import AnchorGenerator # noqa: 401 +from .image_list import ImageList + + +class RPNHead(nn.Module): + """ + Adds a simple RPN Head with classification and regression heads + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + conv_depth (int, optional): number of convolutions + """ + + _version = 2 + + def __init__(self, in_channels: int, num_anchors: int, conv_depth=1) -> None: + super().__init__() + convs = [] + for _ in range(conv_depth): + convs.append(Conv2dNormActivation(in_channels, in_channels, kernel_size=3, norm_layer=None)) + self.conv = nn.Sequential(*convs) + self.cls_logits = nn.Conv2d(in_channels, num_anchors, kernel_size=1, stride=1) + self.bbox_pred = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=1, stride=1) + + for layer in self.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) # type: ignore[arg-type] + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0) # type: ignore[arg-type] + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + for type in ["weight", "bias"]: + old_key = f"{prefix}conv.{type}" + new_key = f"{prefix}conv.0.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def forward(self, x: list[Tensor]) -> tuple[list[Tensor], list[Tensor]]: + logits = [] + bbox_reg = [] + for feature in x: + t = self.conv(feature) + logits.append(self.cls_logits(t)) + bbox_reg.append(self.bbox_pred(t)) + return logits, bbox_reg + + +def permute_and_flatten(layer: Tensor, N: int, A: int, C: int, H: int, W: int) -> Tensor: + layer = layer.view(N, -1, C, H, W) + layer = layer.permute(0, 3, 4, 1, 2) + layer = layer.reshape(N, -1, C) + return layer + + +def concat_box_prediction_layers(box_cls: list[Tensor], box_regression: list[Tensor]) -> tuple[Tensor, Tensor]: + box_cls_flattened = [] + box_regression_flattened = [] + # for each feature level, permute the outputs to make them be in the + # same format as the labels. Note that the labels are computed for + # all feature levels concatenated, so we keep the same representation + # for the objectness and the box_regression + for box_cls_per_level, box_regression_per_level in zip(box_cls, box_regression): + N, AxC, H, W = box_cls_per_level.shape + Ax4 = box_regression_per_level.shape[1] + A = Ax4 // 4 + C = AxC // A + box_cls_per_level = permute_and_flatten(box_cls_per_level, N, A, C, H, W) + box_cls_flattened.append(box_cls_per_level) + + box_regression_per_level = permute_and_flatten(box_regression_per_level, N, A, 4, H, W) + box_regression_flattened.append(box_regression_per_level) + # concatenate on the first dimension (representing the feature levels), to + # take into account the way the labels were generated (with all feature maps + # being concatenated as well) + box_cls = torch.cat(box_cls_flattened, dim=1).flatten(0, -2) + box_regression = torch.cat(box_regression_flattened, dim=1).reshape(-1, 4) + return box_cls, box_regression + + +class RegionProposalNetwork(torch.nn.Module): + """ + Implements Region Proposal Network (RPN). + + Args: + anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + head (nn.Module): module that computes the objectness and regression deltas + fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + pre_nms_top_n (Dict[str, int]): number of proposals to keep before applying NMS. It should + contain two fields: training and testing, to allow for different values depending + on training or evaluation + post_nms_top_n (Dict[str, int]): number of proposals to keep after applying NMS. It should + contain two fields: training and testing, to allow for different values depending + on training or evaluation + nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + score_thresh (float): only return proposals with an objectness score greater than score_thresh + + """ + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler, + } + + def __init__( + self, + anchor_generator: AnchorGenerator, + head: nn.Module, + # Faster-RCNN Training + fg_iou_thresh: float, + bg_iou_thresh: float, + batch_size_per_image: int, + positive_fraction: float, + # Faster-RCNN Inference + pre_nms_top_n: dict[str, int], + post_nms_top_n: dict[str, int], + nms_thresh: float, + score_thresh: float = 0.0, + ) -> None: + super().__init__() + self.anchor_generator = anchor_generator + self.head = head + self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0)) + + # used during training + self.box_similarity = box_ops.box_iou + + self.proposal_matcher = det_utils.Matcher( + fg_iou_thresh, + bg_iou_thresh, + allow_low_quality_matches=True, + ) + + self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction) + # used during testing + self._pre_nms_top_n = pre_nms_top_n + self._post_nms_top_n = post_nms_top_n + self.nms_thresh = nms_thresh + self.score_thresh = score_thresh + self.min_size = 1e-3 + + def pre_nms_top_n(self) -> int: + if self.training: + return self._pre_nms_top_n["training"] + return self._pre_nms_top_n["testing"] + + def post_nms_top_n(self) -> int: + if self.training: + return self._post_nms_top_n["training"] + return self._post_nms_top_n["testing"] + + def assign_targets_to_anchors( + self, anchors: list[Tensor], targets: list[dict[str, Tensor]] + ) -> tuple[list[Tensor], list[Tensor]]: + + labels = [] + matched_gt_boxes = [] + for anchors_per_image, targets_per_image in zip(anchors, targets): + gt_boxes = targets_per_image["boxes"] + + if gt_boxes.numel() == 0: + # Background image (negative example) + device = anchors_per_image.device + matched_gt_boxes_per_image = torch.zeros(anchors_per_image.shape, dtype=torch.float32, device=device) + labels_per_image = torch.zeros((anchors_per_image.shape[0],), dtype=torch.float32, device=device) + else: + match_quality_matrix = self.box_similarity(gt_boxes, anchors_per_image) + matched_idxs = self.proposal_matcher(match_quality_matrix) + # get the targets corresponding GT for each proposal + # NB: need to clamp the indices because we can have a single + # GT in the image, and matched_idxs can be -2, which goes + # out of bounds + matched_gt_boxes_per_image = gt_boxes[matched_idxs.clamp(min=0)] + + labels_per_image = matched_idxs >= 0 + labels_per_image = labels_per_image.to(dtype=torch.float32) + + # Background (negative examples) + bg_indices = matched_idxs == self.proposal_matcher.BELOW_LOW_THRESHOLD + labels_per_image[bg_indices] = 0.0 + + # discard indices that are between thresholds + inds_to_discard = matched_idxs == self.proposal_matcher.BETWEEN_THRESHOLDS + labels_per_image[inds_to_discard] = -1.0 + + labels.append(labels_per_image) + matched_gt_boxes.append(matched_gt_boxes_per_image) + return labels, matched_gt_boxes + + def _get_top_n_idx(self, objectness: Tensor, num_anchors_per_level: list[int]) -> Tensor: + r = [] + offset = 0 + for ob in objectness.split(num_anchors_per_level, 1): + num_anchors = ob.shape[1] + pre_nms_top_n = det_utils._topk_min(ob, self.pre_nms_top_n(), 1) + _, top_n_idx = ob.topk(pre_nms_top_n, dim=1) + r.append(top_n_idx + offset) + offset += num_anchors + return torch.cat(r, dim=1) + + def filter_proposals( + self, + proposals: Tensor, + objectness: Tensor, + image_shapes: list[tuple[int, int]], + num_anchors_per_level: list[int], + ) -> tuple[list[Tensor], list[Tensor]]: + + num_images = proposals.shape[0] + device = proposals.device + # do not backprop through objectness + objectness = objectness.detach() + objectness = objectness.reshape(num_images, -1) + + levels = [ + torch.full((n,), idx, dtype=torch.int64, device=device) for idx, n in enumerate(num_anchors_per_level) + ] + levels = torch.cat(levels, 0) + levels = levels.reshape(1, -1).expand_as(objectness) + + # select top_n boxes independently per level before applying nms + top_n_idx = self._get_top_n_idx(objectness, num_anchors_per_level) + + image_range = torch.arange(num_images, device=device) + batch_idx = image_range[:, None] + + objectness = objectness[batch_idx, top_n_idx] + levels = levels[batch_idx, top_n_idx] + proposals = proposals[batch_idx, top_n_idx] + + objectness_prob = torch.sigmoid(objectness) + + final_boxes = [] + final_scores = [] + for boxes, scores, lvl, img_shape in zip(proposals, objectness_prob, levels, image_shapes): + boxes = box_ops.clip_boxes_to_image(boxes, img_shape) + + # remove small boxes + keep = box_ops.remove_small_boxes(boxes, self.min_size) + boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep] + + # remove low scoring boxes + # use >= for Backwards compatibility + keep = torch.where(scores >= self.score_thresh)[0] + boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep] + + # non-maximum suppression, independently done per level + keep = box_ops.batched_nms(boxes, scores, lvl, self.nms_thresh) + + # keep only topk scoring predictions + keep = keep[: self.post_nms_top_n()] + boxes, scores = boxes[keep], scores[keep] + + final_boxes.append(boxes) + final_scores.append(scores) + return final_boxes, final_scores + + def compute_loss( + self, objectness: Tensor, pred_bbox_deltas: Tensor, labels: list[Tensor], regression_targets: list[Tensor] + ) -> tuple[Tensor, Tensor]: + """ + Args: + objectness (Tensor) + pred_bbox_deltas (Tensor) + labels (List[Tensor]) + regression_targets (List[Tensor]) + + Returns: + objectness_loss (Tensor) + box_loss (Tensor) + """ + + sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) + sampled_pos_inds = torch.where(torch.cat(sampled_pos_inds, dim=0))[0] + sampled_neg_inds = torch.where(torch.cat(sampled_neg_inds, dim=0))[0] + + sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0) + + objectness = objectness.flatten() + + labels = torch.cat(labels, dim=0) + regression_targets = torch.cat(regression_targets, dim=0) + + box_loss = F.smooth_l1_loss( + pred_bbox_deltas[sampled_pos_inds], + regression_targets[sampled_pos_inds], + beta=1 / 9, + reduction="sum", + ) / (sampled_inds.numel()) + + objectness_loss = F.binary_cross_entropy_with_logits(objectness[sampled_inds], labels[sampled_inds]) + + return objectness_loss, box_loss + + def forward( + self, + images: ImageList, + features: dict[str, Tensor], + targets: Optional[list[dict[str, Tensor]]] = None, + ) -> tuple[list[Tensor], dict[str, Tensor]]: + """ + Args: + images (ImageList): images for which we want to compute the predictions + features (Dict[str, Tensor]): features computed from the images that are + used for computing the predictions. Each tensor in the list + correspond to different feature levels + targets (List[Dict[str, Tensor]]): ground-truth boxes present in the image (optional). + If provided, each element in the dict should contain a field `boxes`, + with the locations of the ground-truth boxes. + + Returns: + boxes (List[Tensor]): the predicted boxes from the RPN, one Tensor per + image. + losses (Dict[str, Tensor]): the losses for the model during training. During + testing, it is an empty dict. + """ + # RPN uses all feature maps that are available + features = list(features.values()) + objectness, pred_bbox_deltas = self.head(features) + anchors = self.anchor_generator(images, features) + + num_images = len(anchors) + num_anchors_per_level_shape_tensors = [o[0].shape for o in objectness] + num_anchors_per_level = [s[0] * s[1] * s[2] for s in num_anchors_per_level_shape_tensors] + objectness, pred_bbox_deltas = concat_box_prediction_layers(objectness, pred_bbox_deltas) + # apply pred_bbox_deltas to anchors to obtain the decoded proposals + # note that we detach the deltas because Faster R-CNN do not backprop through + # the proposals + proposals = self.box_coder.decode(pred_bbox_deltas.detach(), anchors) + proposals = proposals.view(num_images, -1, 4) + boxes, scores = self.filter_proposals(proposals, objectness, images.image_sizes, num_anchors_per_level) + + losses = {} + if self.training: + if targets is None: + raise ValueError("targets should not be None") + labels, matched_gt_boxes = self.assign_targets_to_anchors(anchors, targets) + regression_targets = self.box_coder.encode(matched_gt_boxes, anchors) + loss_objectness, loss_rpn_box_reg = self.compute_loss( + objectness, pred_bbox_deltas, labels, regression_targets + ) + losses = { + "loss_objectness": loss_objectness, + "loss_rpn_box_reg": loss_rpn_box_reg, + } + return boxes, losses diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/ssd.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/ssd.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd43d04c7520965a8e9eed11d7d184e9991f805 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/ssd.py @@ -0,0 +1,682 @@ +import warnings +from collections import OrderedDict +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ...ops import boxes as box_ops +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..vgg import VGG, vgg16, VGG16_Weights +from . import _utils as det_utils +from .anchor_utils import DefaultBoxGenerator +from .backbone_utils import _validate_trainable_layers +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "SSD300_VGG16_Weights", + "ssd300_vgg16", +] + + +class SSD300_VGG16_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/ssd300_vgg16_coco-b556d3b4.pth", + transforms=ObjectDetection, + meta={ + "num_params": 35641826, + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#ssd300-vgg16", + "_metrics": { + "COCO-val2017": { + "box_map": 25.1, + } + }, + "_ops": 34.858, + "_file_size": 135.988, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +def _xavier_init(conv: nn.Module): + for layer in conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.xavier_uniform_(layer.weight) + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0.0) + + +class SSDHead(nn.Module): + def __init__(self, in_channels: list[int], num_anchors: list[int], num_classes: int): + super().__init__() + self.classification_head = SSDClassificationHead(in_channels, num_anchors, num_classes) + self.regression_head = SSDRegressionHead(in_channels, num_anchors) + + def forward(self, x: list[Tensor]) -> dict[str, Tensor]: + return { + "bbox_regression": self.regression_head(x), + "cls_logits": self.classification_head(x), + } + + +class SSDScoringHead(nn.Module): + def __init__(self, module_list: nn.ModuleList, num_columns: int): + super().__init__() + self.module_list = module_list + self.num_columns = num_columns + + def _get_result_from_module_list(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.module_list[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.module_list) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.module_list): + if i == idx: + out = module(x) + return out + + def forward(self, x: list[Tensor]) -> Tensor: + all_results = [] + + for i, features in enumerate(x): + results = self._get_result_from_module_list(features, i) + + # Permute output from (N, A * K, H, W) to (N, HWA, K). + N, _, H, W = results.shape + results = results.view(N, -1, self.num_columns, H, W) + results = results.permute(0, 3, 4, 1, 2) + results = results.reshape(N, -1, self.num_columns) # Size=(N, HWA, K) + + all_results.append(results) + + return torch.cat(all_results, dim=1) + + +class SSDClassificationHead(SSDScoringHead): + def __init__(self, in_channels: list[int], num_anchors: list[int], num_classes: int): + cls_logits = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + cls_logits.append(nn.Conv2d(channels, num_classes * anchors, kernel_size=3, padding=1)) + _xavier_init(cls_logits) + super().__init__(cls_logits, num_classes) + + +class SSDRegressionHead(SSDScoringHead): + def __init__(self, in_channels: list[int], num_anchors: list[int]): + bbox_reg = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + bbox_reg.append(nn.Conv2d(channels, 4 * anchors, kernel_size=3, padding=1)) + _xavier_init(bbox_reg) + super().__init__(bbox_reg, 4) + + +class SSD(nn.Module): + """ + Implements SSD architecture from `"SSD: Single Shot MultiBox Detector" `_. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes, but they will be resized + to a fixed size before passing it to the backbone. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each detection + - scores (Tensor[N]): the scores for each detection + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute with the list of the output channels of + each feature map. The backbone should return a single Tensor or an OrderedDict[Tensor]. + anchor_generator (DefaultBoxGenerator): module that generates the default boxes for a + set of feature maps. + size (Tuple[int, int]): the width and height to which images will be rescaled before feeding them + to the backbone. + num_classes (int): number of output classes of the model (including the background). + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + head (nn.Module, optional): Module run on top of the backbone features. Defaults to a module containing + a classification and regression module. + score_thresh (float): Score threshold used for postprocessing the detections. + nms_thresh (float): NMS threshold used for postprocessing the detections. + detections_per_img (int): Number of best detections to keep after NMS. + iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training. + topk_candidates (int): Number of best detections to keep before NMS. + positive_fraction (float): a number between 0 and 1 which indicates the proportion of positive + proposals used during the training of the classification head. It is used to estimate the negative to + positive ratio. + """ + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + } + + def __init__( + self, + backbone: nn.Module, + anchor_generator: DefaultBoxGenerator, + size: tuple[int, int], + num_classes: int, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + head: Optional[nn.Module] = None, + score_thresh: float = 0.01, + nms_thresh: float = 0.45, + detections_per_img: int = 200, + iou_thresh: float = 0.5, + topk_candidates: int = 400, + positive_fraction: float = 0.25, + **kwargs: Any, + ): + super().__init__() + _log_api_usage_once(self) + + self.backbone = backbone + + self.anchor_generator = anchor_generator + + self.box_coder = det_utils.BoxCoder(weights=(10.0, 10.0, 5.0, 5.0)) + + if head is None: + if hasattr(backbone, "out_channels"): + out_channels = backbone.out_channels + else: + out_channels = det_utils.retrieve_out_channels(backbone, size) + + if len(out_channels) != len(anchor_generator.aspect_ratios): + raise ValueError( + f"The length of the output channels from the backbone ({len(out_channels)}) do not match the length of the anchor generator aspect ratios ({len(anchor_generator.aspect_ratios)})" + ) + + num_anchors = self.anchor_generator.num_anchors_per_location() + head = SSDHead(out_channels, num_anchors, num_classes) + self.head = head + + self.proposal_matcher = det_utils.SSDMatcher(iou_thresh) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + self.transform = GeneralizedRCNNTransform( + min(size), max(size), image_mean, image_std, size_divisible=1, fixed_size=size, **kwargs + ) + + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + self.topk_candidates = topk_candidates + self.neg_to_pos_ratio = (1.0 - positive_fraction) / positive_fraction + + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs( + self, losses: dict[str, Tensor], detections: list[dict[str, Tensor]] + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + if self.training: + return losses + + return detections + + def compute_loss( + self, + targets: list[dict[str, Tensor]], + head_outputs: dict[str, Tensor], + anchors: list[Tensor], + matched_idxs: list[Tensor], + ) -> dict[str, Tensor]: + bbox_regression = head_outputs["bbox_regression"] + cls_logits = head_outputs["cls_logits"] + + # Match original targets with default boxes + num_foreground = 0 + bbox_loss = [] + cls_targets = [] + for ( + targets_per_image, + bbox_regression_per_image, + cls_logits_per_image, + anchors_per_image, + matched_idxs_per_image, + ) in zip(targets, bbox_regression, cls_logits, anchors, matched_idxs): + # produce the matching between boxes and targets + foreground_idxs_per_image = torch.where(matched_idxs_per_image >= 0)[0] + foreground_matched_idxs_per_image = matched_idxs_per_image[foreground_idxs_per_image] + num_foreground += foreground_matched_idxs_per_image.numel() + + # Calculate regression loss + matched_gt_boxes_per_image = targets_per_image["boxes"][foreground_matched_idxs_per_image] + bbox_regression_per_image = bbox_regression_per_image[foreground_idxs_per_image, :] + anchors_per_image = anchors_per_image[foreground_idxs_per_image, :] + target_regression = self.box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image) + bbox_loss.append( + torch.nn.functional.smooth_l1_loss(bbox_regression_per_image, target_regression, reduction="sum") + ) + + # Estimate ground truth for class targets + gt_classes_target = torch.zeros( + (cls_logits_per_image.size(0),), + dtype=targets_per_image["labels"].dtype, + device=targets_per_image["labels"].device, + ) + gt_classes_target[foreground_idxs_per_image] = targets_per_image["labels"][ + foreground_matched_idxs_per_image + ] + cls_targets.append(gt_classes_target) + + bbox_loss = torch.stack(bbox_loss) + cls_targets = torch.stack(cls_targets) + + # Calculate classification loss + num_classes = cls_logits.size(-1) + cls_loss = F.cross_entropy(cls_logits.view(-1, num_classes), cls_targets.view(-1), reduction="none").view( + cls_targets.size() + ) + + # Hard Negative Sampling + foreground_idxs = cls_targets > 0 + num_negative = self.neg_to_pos_ratio * foreground_idxs.sum(1, keepdim=True) + # num_negative[num_negative < self.neg_to_pos_ratio] = self.neg_to_pos_ratio + negative_loss = cls_loss.clone() + negative_loss[foreground_idxs] = -float("inf") # use -inf to detect positive values that creeped in the sample + values, idx = negative_loss.sort(1, descending=True) + # background_idxs = torch.logical_and(idx.sort(1)[1] < num_negative, torch.isfinite(values)) + background_idxs = idx.sort(1)[1] < num_negative + + N = max(1, num_foreground) + return { + "bbox_regression": bbox_loss.sum() / N, + "classification": (cls_loss[foreground_idxs].sum() + cls_loss[background_idxs].sum()) / N, + } + + def forward( + self, images: list[Tensor], targets: Optional[list[dict[str, Tensor]]] = None + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + if isinstance(boxes, torch.Tensor): + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.", + ) + else: + torch._assert(False, f"Expected target boxes to be of type Tensor, got {type(boxes)}.") + + # get the original image sizes + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + # transform the input + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + "All bounding boxes should have positive height and width." + f" Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + # get the features from the backbone + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + + features = list(features.values()) + + # compute the ssd heads outputs using the features + head_outputs = self.head(features) + + # create the set of anchors + anchors = self.anchor_generator(images, features) + + losses = {} + detections: list[dict[str, Tensor]] = [] + if self.training: + matched_idxs = [] + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for anchors_per_image, targets_per_image in zip(anchors, targets): + if targets_per_image["boxes"].numel() == 0: + matched_idxs.append( + torch.full( + (anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device + ) + ) + continue + + match_quality_matrix = box_ops.box_iou(targets_per_image["boxes"], anchors_per_image) + matched_idxs.append(self.proposal_matcher(match_quality_matrix)) + + losses = self.compute_loss(targets, head_outputs, anchors, matched_idxs) + else: + detections = self.postprocess_detections(head_outputs, anchors, images.image_sizes) + detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("SSD always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + return self.eager_outputs(losses, detections) + + def postprocess_detections( + self, head_outputs: dict[str, Tensor], image_anchors: list[Tensor], image_shapes: list[tuple[int, int]] + ) -> list[dict[str, Tensor]]: + bbox_regression = head_outputs["bbox_regression"] + pred_scores = F.softmax(head_outputs["cls_logits"], dim=-1) + + num_classes = pred_scores.size(-1) + device = pred_scores.device + + detections: list[dict[str, Tensor]] = [] + + for boxes, scores, anchors, image_shape in zip(bbox_regression, pred_scores, image_anchors, image_shapes): + boxes = self.box_coder.decode_single(boxes, anchors) + boxes = box_ops.clip_boxes_to_image(boxes, image_shape) + + image_boxes = [] + image_scores = [] + image_labels = [] + for label in range(1, num_classes): + score = scores[:, label] + + keep_idxs = score > self.score_thresh + score = score[keep_idxs] + box = boxes[keep_idxs] + + # keep only topk scoring predictions + num_topk = det_utils._topk_min(score, self.topk_candidates, 0) + score, idxs = score.topk(num_topk) + box = box[idxs] + + image_boxes.append(box) + image_scores.append(score) + image_labels.append(torch.full_like(score, fill_value=label, dtype=torch.int64, device=device)) + + image_boxes = torch.cat(image_boxes, dim=0) + image_scores = torch.cat(image_scores, dim=0) + image_labels = torch.cat(image_labels, dim=0) + + # non-maximum suppression + keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh) + keep = keep[: self.detections_per_img] + + detections.append( + { + "boxes": image_boxes[keep], + "scores": image_scores[keep], + "labels": image_labels[keep], + } + ) + return detections + + +class SSDFeatureExtractorVGG(nn.Module): + def __init__(self, backbone: nn.Module, highres: bool): + super().__init__() + + _, _, maxpool3_pos, maxpool4_pos, _ = (i for i, layer in enumerate(backbone) if isinstance(layer, nn.MaxPool2d)) + + # Patch ceil_mode for maxpool3 to get the same WxH output sizes as the paper + backbone[maxpool3_pos].ceil_mode = True + + # parameters used for L2 regularization + rescaling + self.scale_weight = nn.Parameter(torch.ones(512) * 20) + + # Multiple Feature maps - page 4, Fig 2 of SSD paper + self.features = nn.Sequential(*backbone[:maxpool4_pos]) # until conv4_3 + + # SSD300 case - page 4, Fig 2 of SSD paper + extra = nn.ModuleList( + [ + nn.Sequential( + nn.Conv2d(1024, 256, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(256, 512, kernel_size=3, padding=1, stride=2), # conv8_2 + nn.ReLU(inplace=True), + ), + nn.Sequential( + nn.Conv2d(512, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2), # conv9_2 + nn.ReLU(inplace=True), + ), + nn.Sequential( + nn.Conv2d(256, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=3), # conv10_2 + nn.ReLU(inplace=True), + ), + nn.Sequential( + nn.Conv2d(256, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=3), # conv11_2 + nn.ReLU(inplace=True), + ), + ] + ) + if highres: + # Additional layers for the SSD512 case. See page 11, footernote 5. + extra.append( + nn.Sequential( + nn.Conv2d(256, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=4), # conv12_2 + nn.ReLU(inplace=True), + ) + ) + _xavier_init(extra) + + fc = nn.Sequential( + nn.MaxPool2d(kernel_size=3, stride=1, padding=1, ceil_mode=False), # add modified maxpool5 + nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, padding=6, dilation=6), # FC6 with atrous + nn.ReLU(inplace=True), + nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=1), # FC7 + nn.ReLU(inplace=True), + ) + _xavier_init(fc) + extra.insert( + 0, + nn.Sequential( + *backbone[maxpool4_pos:-1], # until conv5_3, skip maxpool5 + fc, + ), + ) + self.extra = extra + + def forward(self, x: Tensor) -> dict[str, Tensor]: + # L2 regularization + Rescaling of 1st block's feature map + x = self.features(x) + rescaled = self.scale_weight.view(1, -1, 1, 1) * F.normalize(x) + output = [rescaled] + + # Calculating Feature maps for the rest blocks + for block in self.extra: + x = block(x) + output.append(x) + + return OrderedDict([(str(i), v) for i, v in enumerate(output)]) + + +def _vgg_extractor(backbone: VGG, highres: bool, trainable_layers: int): + backbone = backbone.features + # Gather the indices of maxpools. These are the locations of output blocks. + stage_indices = [0] + [i for i, b in enumerate(backbone) if isinstance(b, nn.MaxPool2d)][:-1] + num_stages = len(stage_indices) + + # find the index of the layer from which we won't freeze + torch._assert( + 0 <= trainable_layers <= num_stages, + f"trainable_layers should be in the range [0, {num_stages}]. Instead got {trainable_layers}", + ) + freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers] + + for b in backbone[:freeze_before]: + for parameter in b.parameters(): + parameter.requires_grad_(False) + + return SSDFeatureExtractorVGG(backbone, highres) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", SSD300_VGG16_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", VGG16_Weights.IMAGENET1K_FEATURES), +) +def ssd300_vgg16( + *, + weights: Optional[SSD300_VGG16_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[VGG16_Weights] = VGG16_Weights.IMAGENET1K_FEATURES, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> SSD: + """The SSD300 model is based on the `SSD: Single Shot MultiBox Detector + `_ paper. + + .. betastatus:: detection module + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes, but they will be resized + to a fixed size before passing it to the backbone. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each detection + - scores (Tensor[N]): the scores for each detection + + Example: + + >>> model = torchvision.models.detection.ssd300_vgg16(weights=SSD300_VGG16_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 300), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.SSD300_VGG16_Weights`, optional): The pretrained + weights to use. See + :class:`~torchvision.models.detection.SSD300_VGG16_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr + Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.VGG16_Weights`, optional): The pretrained weights for the + backbone + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 4. + **kwargs: parameters passed to the ``torchvision.models.detection.SSD`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.SSD300_VGG16_Weights + :members: + """ + weights = SSD300_VGG16_Weights.verify(weights) + weights_backbone = VGG16_Weights.verify(weights_backbone) + + if "size" in kwargs: + warnings.warn("The size of the model is already fixed; ignoring the parameter.") + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + trainable_backbone_layers = _validate_trainable_layers( + weights is not None or weights_backbone is not None, trainable_backbone_layers, 5, 4 + ) + + # Use custom backbones more appropriate for SSD + backbone = vgg16(weights=weights_backbone, progress=progress) + backbone = _vgg_extractor(backbone, False, trainable_backbone_layers) + anchor_generator = DefaultBoxGenerator( + [[2], [2, 3], [2, 3], [2, 3], [2], [2]], + scales=[0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05], + steps=[8, 16, 32, 64, 100, 300], + ) + + defaults = { + # Rescale the input in a way compatible to the backbone + "image_mean": [0.48235, 0.45882, 0.40784], + "image_std": [1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0], # undo the 0-1 scaling of toTensor + } + kwargs: Any = {**defaults, **kwargs} + model = SSD(backbone, anchor_generator, (300, 300), num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/ssdlite.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/ssdlite.py new file mode 100644 index 0000000000000000000000000000000000000000..6b05aae0c0fc38d25388550ce27df35bfc45c3a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/ssdlite.py @@ -0,0 +1,331 @@ +import warnings +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch +from torch import nn, Tensor + +from ...ops.misc import Conv2dNormActivation +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .. import mobilenet +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights +from . import _utils as det_utils +from .anchor_utils import DefaultBoxGenerator +from .backbone_utils import _validate_trainable_layers +from .ssd import SSD, SSDScoringHead + + +__all__ = [ + "SSDLite320_MobileNet_V3_Large_Weights", + "ssdlite320_mobilenet_v3_large", +] + + +# Building blocks of SSDlite as described in section 6.2 of MobileNetV2 paper +def _prediction_block( + in_channels: int, out_channels: int, kernel_size: int, norm_layer: Callable[..., nn.Module] +) -> nn.Sequential: + return nn.Sequential( + # 3x3 depthwise with stride 1 and padding 1 + Conv2dNormActivation( + in_channels, + in_channels, + kernel_size=kernel_size, + groups=in_channels, + norm_layer=norm_layer, + activation_layer=nn.ReLU6, + ), + # 1x1 projetion to output channels + nn.Conv2d(in_channels, out_channels, 1), + ) + + +def _extra_block(in_channels: int, out_channels: int, norm_layer: Callable[..., nn.Module]) -> nn.Sequential: + activation = nn.ReLU6 + intermediate_channels = out_channels // 2 + return nn.Sequential( + # 1x1 projection to half output channels + Conv2dNormActivation( + in_channels, intermediate_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=activation + ), + # 3x3 depthwise with stride 2 and padding 1 + Conv2dNormActivation( + intermediate_channels, + intermediate_channels, + kernel_size=3, + stride=2, + groups=intermediate_channels, + norm_layer=norm_layer, + activation_layer=activation, + ), + # 1x1 projetion to output channels + Conv2dNormActivation( + intermediate_channels, out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=activation + ), + ) + + +def _normal_init(conv: nn.Module): + for layer in conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, mean=0.0, std=0.03) + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0.0) + + +class SSDLiteHead(nn.Module): + def __init__( + self, in_channels: list[int], num_anchors: list[int], num_classes: int, norm_layer: Callable[..., nn.Module] + ): + super().__init__() + self.classification_head = SSDLiteClassificationHead(in_channels, num_anchors, num_classes, norm_layer) + self.regression_head = SSDLiteRegressionHead(in_channels, num_anchors, norm_layer) + + def forward(self, x: list[Tensor]) -> dict[str, Tensor]: + return { + "bbox_regression": self.regression_head(x), + "cls_logits": self.classification_head(x), + } + + +class SSDLiteClassificationHead(SSDScoringHead): + def __init__( + self, in_channels: list[int], num_anchors: list[int], num_classes: int, norm_layer: Callable[..., nn.Module] + ): + cls_logits = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + cls_logits.append(_prediction_block(channels, num_classes * anchors, 3, norm_layer)) + _normal_init(cls_logits) + super().__init__(cls_logits, num_classes) + + +class SSDLiteRegressionHead(SSDScoringHead): + def __init__(self, in_channels: list[int], num_anchors: list[int], norm_layer: Callable[..., nn.Module]): + bbox_reg = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + bbox_reg.append(_prediction_block(channels, 4 * anchors, 3, norm_layer)) + _normal_init(bbox_reg) + super().__init__(bbox_reg, 4) + + +class SSDLiteFeatureExtractorMobileNet(nn.Module): + def __init__( + self, + backbone: nn.Module, + c4_pos: int, + norm_layer: Callable[..., nn.Module], + width_mult: float = 1.0, + min_depth: int = 16, + ): + super().__init__() + _log_api_usage_once(self) + + if backbone[c4_pos].use_res_connect: + raise ValueError("backbone[c4_pos].use_res_connect should be False") + + self.features = nn.Sequential( + # As described in section 6.3 of MobileNetV3 paper + nn.Sequential(*backbone[:c4_pos], backbone[c4_pos].block[0]), # from start until C4 expansion layer + nn.Sequential(backbone[c4_pos].block[1:], *backbone[c4_pos + 1 :]), # from C4 depthwise until end + ) + + get_depth = lambda d: max(min_depth, int(d * width_mult)) # noqa: E731 + extra = nn.ModuleList( + [ + _extra_block(backbone[-1].out_channels, get_depth(512), norm_layer), + _extra_block(get_depth(512), get_depth(256), norm_layer), + _extra_block(get_depth(256), get_depth(256), norm_layer), + _extra_block(get_depth(256), get_depth(128), norm_layer), + ] + ) + _normal_init(extra) + + self.extra = extra + + def forward(self, x: Tensor) -> dict[str, Tensor]: + # Get feature maps from backbone and extra. Can't be refactored due to JIT limitations. + output = [] + for block in self.features: + x = block(x) + output.append(x) + + for block in self.extra: + x = block(x) + output.append(x) + + return OrderedDict([(str(i), v) for i, v in enumerate(output)]) + + +def _mobilenet_extractor( + backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3], + trainable_layers: int, + norm_layer: Callable[..., nn.Module], +): + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + num_stages = len(stage_indices) + + # find the index of the layer from which we won't freeze + if not 0 <= trainable_layers <= num_stages: + raise ValueError("trainable_layers should be in the range [0, {num_stages}], instead got {trainable_layers}") + freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers] + + for b in backbone[:freeze_before]: + for parameter in b.parameters(): + parameter.requires_grad_(False) + + return SSDLiteFeatureExtractorMobileNet(backbone, stage_indices[-2], norm_layer) + + +class SSDLite320_MobileNet_V3_Large_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/ssdlite320_mobilenet_v3_large_coco-a79551df.pth", + transforms=ObjectDetection, + meta={ + "num_params": 3440060, + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#ssdlite320-mobilenetv3-large", + "_metrics": { + "COCO-val2017": { + "box_map": 21.3, + } + }, + "_ops": 0.583, + "_file_size": 13.418, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", SSDLite320_MobileNet_V3_Large_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def ssdlite320_mobilenet_v3_large( + *, + weights: Optional[SSDLite320_MobileNet_V3_Large_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + **kwargs: Any, +) -> SSD: + """SSDlite model architecture with input size 320x320 and a MobileNetV3 Large backbone, as + described at `Searching for MobileNetV3 `__ and + `MobileNetV2: Inverted Residuals and Linear Bottlenecks `__. + + .. betastatus:: detection module + + See :func:`~torchvision.models.detection.ssd300_vgg16` for more details. + + Example: + + >>> model = torchvision.models.detection.ssdlite320_mobilenet_v3_large(weights=SSDLite320_MobileNet_V3_Large_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 320, 320), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model + (including the background). + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained + weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers + starting from final block. Valid values are between 0 and 6, with 6 meaning all + backbone layers are trainable. If ``None`` is passed (the default) this value is + set to 6. + norm_layer (callable, optional): Module specifying the normalization layer to use. + **kwargs: parameters passed to the ``torchvision.models.detection.ssd.SSD`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights + :members: + """ + + weights = SSDLite320_MobileNet_V3_Large_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + if "size" in kwargs: + warnings.warn("The size of the model is already fixed; ignoring the parameter.") + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + trainable_backbone_layers = _validate_trainable_layers( + weights is not None or weights_backbone is not None, trainable_backbone_layers, 6, 6 + ) + + # Enable reduced tail if no pretrained backbone is selected. See Table 6 of MobileNetV3 paper. + reduce_tail = weights_backbone is None + + if norm_layer is None: + norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.03) + + backbone = mobilenet_v3_large( + weights=weights_backbone, progress=progress, norm_layer=norm_layer, reduced_tail=reduce_tail, **kwargs + ) + if weights_backbone is None: + # Change the default initialization scheme if not pretrained + _normal_init(backbone) + backbone = _mobilenet_extractor( + backbone, + trainable_backbone_layers, + norm_layer, + ) + + size = (320, 320) + anchor_generator = DefaultBoxGenerator([[2, 3] for _ in range(6)], min_ratio=0.2, max_ratio=0.95) + out_channels = det_utils.retrieve_out_channels(backbone, size) + num_anchors = anchor_generator.num_anchors_per_location() + if len(out_channels) != len(anchor_generator.aspect_ratios): + raise ValueError( + f"The length of the output channels from the backbone {len(out_channels)} do not match the length of the anchor generator aspect ratios {len(anchor_generator.aspect_ratios)}" + ) + + defaults = { + "score_thresh": 0.001, + "nms_thresh": 0.55, + "detections_per_img": 300, + "topk_candidates": 300, + # Rescale the input in a way compatible to the backbone: + # The following mean/std rescale the data from [0, 1] to [-1, 1] + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + } + kwargs: Any = {**defaults, **kwargs} + model = SSD( + backbone, + anchor_generator, + size, + num_classes, + head=SSDLiteHead(out_channels, num_anchors, num_classes, norm_layer), + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/transform.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..ac54873dee8b798761db2b00f407d24bdafec33f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/detection/transform.py @@ -0,0 +1,319 @@ +import math +from typing import Any, Optional + +import torch +import torchvision +from torch import nn, Tensor + +from .image_list import ImageList +from .roi_heads import paste_masks_in_image + + +@torch.jit.unused +def _get_shape_onnx(image: Tensor) -> Tensor: + from torch.onnx import operators + + return operators.shape_as_tensor(image)[-2:] + + +@torch.jit.unused +def _fake_cast_onnx(v: Tensor) -> float: + # ONNX requires a tensor but here we fake its type for JIT. + return v + + +def _resize_image_and_masks( + image: Tensor, + self_min_size: int, + self_max_size: int, + target: Optional[dict[str, Tensor]] = None, + fixed_size: Optional[tuple[int, int]] = None, +) -> tuple[Tensor, Optional[dict[str, Tensor]]]: + if torchvision._is_tracing(): + im_shape = _get_shape_onnx(image) + elif torch.jit.is_scripting(): + im_shape = torch.tensor(image.shape[-2:]) + else: + im_shape = image.shape[-2:] + + size: Optional[list[int]] = None + scale_factor: Optional[float] = None + recompute_scale_factor: Optional[bool] = None + if fixed_size is not None: + size = [fixed_size[1], fixed_size[0]] + else: + if torch.jit.is_scripting() or torchvision._is_tracing(): + min_size = torch.min(im_shape).to(dtype=torch.float32) + max_size = torch.max(im_shape).to(dtype=torch.float32) + self_min_size_f = float(self_min_size) + self_max_size_f = float(self_max_size) + scale = torch.min(self_min_size_f / min_size, self_max_size_f / max_size) + + if torchvision._is_tracing(): + scale_factor = _fake_cast_onnx(scale) + else: + scale_factor = scale.item() + + else: + # Do it the normal way + min_size = min(im_shape) + max_size = max(im_shape) + scale_factor = min(self_min_size / min_size, self_max_size / max_size) + + recompute_scale_factor = True + + image = torch.nn.functional.interpolate( + image[None], + size=size, + scale_factor=scale_factor, + mode="bilinear", + recompute_scale_factor=recompute_scale_factor, + align_corners=False, + )[0] + + if target is None: + return image, target + + if "masks" in target: + mask = target["masks"] + mask = torch.nn.functional.interpolate( + mask[:, None].float(), size=size, scale_factor=scale_factor, recompute_scale_factor=recompute_scale_factor + )[:, 0].byte() + target["masks"] = mask + return image, target + + +class GeneralizedRCNNTransform(nn.Module): + """ + Performs input / target transformation before feeding the data to a GeneralizedRCNN + model. + + The transformations it performs are: + - input normalization (mean subtraction and std division) + - input / target resizing to match min_size / max_size + + It returns a ImageList for the inputs, and a List[Dict[Tensor]] for the targets + """ + + def __init__( + self, + min_size: int, + max_size: int, + image_mean: list[float], + image_std: list[float], + size_divisible: int = 32, + fixed_size: Optional[tuple[int, int]] = None, + **kwargs: Any, + ): + super().__init__() + if not isinstance(min_size, (list, tuple)): + min_size = (min_size,) + self.min_size = min_size + self.max_size = max_size + self.image_mean = image_mean + self.image_std = image_std + self.size_divisible = size_divisible + self.fixed_size = fixed_size + self._skip_resize = kwargs.pop("_skip_resize", False) + + def forward( + self, images: list[Tensor], targets: Optional[list[dict[str, Tensor]]] = None + ) -> tuple[ImageList, Optional[list[dict[str, Tensor]]]]: + images = [img for img in images] + if targets is not None: + # make a copy of targets to avoid modifying it in-place + # once torchscript supports dict comprehension + # this can be simplified as follows + # targets = [{k: v for k,v in t.items()} for t in targets] + targets_copy: list[dict[str, Tensor]] = [] + for t in targets: + data: dict[str, Tensor] = {} + for k, v in t.items(): + data[k] = v + targets_copy.append(data) + targets = targets_copy + for i in range(len(images)): + image = images[i] + target_index = targets[i] if targets is not None else None + + if image.dim() != 3: + raise ValueError(f"images is expected to be a list of 3d tensors of shape [C, H, W], got {image.shape}") + image = self.normalize(image) + image, target_index = self.resize(image, target_index) + images[i] = image + if targets is not None and target_index is not None: + targets[i] = target_index + + image_sizes = [img.shape[-2:] for img in images] + images = self.batch_images(images, size_divisible=self.size_divisible) + image_sizes_list: list[tuple[int, int]] = [] + for image_size in image_sizes: + torch._assert( + len(image_size) == 2, + f"Input tensors expected to have in the last two elements H and W, instead got {image_size}", + ) + image_sizes_list.append((image_size[0], image_size[1])) + + image_list = ImageList(images, image_sizes_list) + return image_list, targets + + def normalize(self, image: Tensor) -> Tensor: + if not image.is_floating_point(): + raise TypeError( + f"Expected input images to be of floating type (in range [0, 1]), " + f"but found type {image.dtype} instead" + ) + dtype, device = image.dtype, image.device + mean = torch.as_tensor(self.image_mean, dtype=dtype, device=device) + std = torch.as_tensor(self.image_std, dtype=dtype, device=device) + return (image - mean[:, None, None]) / std[:, None, None] + + def torch_choice(self, k: list[int]) -> int: + """ + Implements `random.choice` via torch ops, so it can be compiled with + TorchScript and we use PyTorch's RNG (not native RNG) + """ + index = int(torch.empty(1).uniform_(0.0, float(len(k))).item()) + return k[index] + + def resize( + self, + image: Tensor, + target: Optional[dict[str, Tensor]] = None, + ) -> tuple[Tensor, Optional[dict[str, Tensor]]]: + h, w = image.shape[-2:] + if self.training: + if self._skip_resize: + return image, target + size = self.torch_choice(self.min_size) + else: + size = self.min_size[-1] + image, target = _resize_image_and_masks(image, size, self.max_size, target, self.fixed_size) + + if target is None: + return image, target + + bbox = target["boxes"] + bbox = resize_boxes(bbox, (h, w), image.shape[-2:]) + target["boxes"] = bbox + + if "keypoints" in target: + keypoints = target["keypoints"] + keypoints = resize_keypoints(keypoints, (h, w), image.shape[-2:]) + target["keypoints"] = keypoints + return image, target + + # _onnx_batch_images() is an implementation of + # batch_images() that is supported by ONNX tracing. + @torch.jit.unused + def _onnx_batch_images(self, images: list[Tensor], size_divisible: int = 32) -> Tensor: + max_size = [] + for i in range(images[0].dim()): + max_size_i = torch.max(torch.stack([img.shape[i] for img in images]).to(torch.float32)).to(torch.int64) + max_size.append(max_size_i) + stride = size_divisible + max_size[1] = (torch.ceil((max_size[1].to(torch.float32)) / stride) * stride).to(torch.int64) + max_size[2] = (torch.ceil((max_size[2].to(torch.float32)) / stride) * stride).to(torch.int64) + max_size = tuple(max_size) + + # work around for + # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + # which is not yet supported in onnx + padded_imgs = [] + for img in images: + padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))] + padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0])) + padded_imgs.append(padded_img) + + return torch.stack(padded_imgs) + + def max_by_axis(self, the_list: list[list[int]]) -> list[int]: + maxes = the_list[0] + for sublist in the_list[1:]: + for index, item in enumerate(sublist): + maxes[index] = max(maxes[index], item) + return maxes + + def batch_images(self, images: list[Tensor], size_divisible: int = 32) -> Tensor: + if torchvision._is_tracing(): + # batch_images() does not export well to ONNX + # call _onnx_batch_images() instead + return self._onnx_batch_images(images, size_divisible) + + max_size = self.max_by_axis([list(img.shape) for img in images]) + stride = float(size_divisible) + max_size = list(max_size) + max_size[1] = int(math.ceil(float(max_size[1]) / stride) * stride) + max_size[2] = int(math.ceil(float(max_size[2]) / stride) * stride) + + batch_shape = [len(images)] + max_size + batched_imgs = images[0].new_full(batch_shape, 0) + for i in range(batched_imgs.shape[0]): + img = images[i] + batched_imgs[i, : img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + + return batched_imgs + + def postprocess( + self, + result: list[dict[str, Tensor]], + image_shapes: list[tuple[int, int]], + original_image_sizes: list[tuple[int, int]], + ) -> list[dict[str, Tensor]]: + if self.training: + return result + for i, (pred, im_s, o_im_s) in enumerate(zip(result, image_shapes, original_image_sizes)): + boxes = pred["boxes"] + boxes = resize_boxes(boxes, im_s, o_im_s) + result[i]["boxes"] = boxes + if "masks" in pred: + masks = pred["masks"] + masks = paste_masks_in_image(masks, boxes, o_im_s) + result[i]["masks"] = masks + if "keypoints" in pred: + keypoints = pred["keypoints"] + keypoints = resize_keypoints(keypoints, im_s, o_im_s) + result[i]["keypoints"] = keypoints + return result + + def __repr__(self) -> str: + format_string = f"{self.__class__.__name__}(" + _indent = "\n " + format_string += f"{_indent}Normalize(mean={self.image_mean}, std={self.image_std})" + format_string += f"{_indent}Resize(min_size={self.min_size}, max_size={self.max_size}, mode='bilinear')" + format_string += "\n)" + return format_string + + +def resize_keypoints(keypoints: Tensor, original_size: list[int], new_size: list[int]) -> Tensor: + ratios = [ + torch.tensor(s, dtype=torch.float32, device=keypoints.device) + / torch.tensor(s_orig, dtype=torch.float32, device=keypoints.device) + for s, s_orig in zip(new_size, original_size) + ] + ratio_h, ratio_w = ratios + resized_data = keypoints.clone() + if torch._C._get_tracing_state(): + resized_data_0 = resized_data[:, :, 0] * ratio_w + resized_data_1 = resized_data[:, :, 1] * ratio_h + resized_data = torch.stack((resized_data_0, resized_data_1, resized_data[:, :, 2]), dim=2) + else: + resized_data[..., 0] *= ratio_w + resized_data[..., 1] *= ratio_h + return resized_data + + +def resize_boxes(boxes: Tensor, original_size: list[int], new_size: list[int]) -> Tensor: + ratios = [ + torch.tensor(s, dtype=torch.float32, device=boxes.device) + / torch.tensor(s_orig, dtype=torch.float32, device=boxes.device) + for s, s_orig in zip(new_size, original_size) + ] + ratio_height, ratio_width = ratios + xmin, ymin, xmax, ymax = boxes.unbind(1) + + xmin = xmin * ratio_width + xmax = xmax * ratio_width + ymin = ymin * ratio_height + ymax = ymax * ratio_height + return torch.stack((xmin, ymin, xmax, ymax), dim=1) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/efficientnet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/efficientnet.py new file mode 100644 index 0000000000000000000000000000000000000000..4b755a3e20751631993eedade35ec549a5b917c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/efficientnet.py @@ -0,0 +1,1132 @@ +import copy +import math +from collections.abc import Sequence +from dataclasses import dataclass +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch +from torch import nn, Tensor +from torchvision.ops import StochasticDepth + +from ..ops.misc import Conv2dNormActivation, SqueezeExcitation +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "EfficientNet", + "EfficientNet_B0_Weights", + "EfficientNet_B1_Weights", + "EfficientNet_B2_Weights", + "EfficientNet_B3_Weights", + "EfficientNet_B4_Weights", + "EfficientNet_B5_Weights", + "EfficientNet_B6_Weights", + "EfficientNet_B7_Weights", + "EfficientNet_V2_S_Weights", + "EfficientNet_V2_M_Weights", + "EfficientNet_V2_L_Weights", + "efficientnet_b0", + "efficientnet_b1", + "efficientnet_b2", + "efficientnet_b3", + "efficientnet_b4", + "efficientnet_b5", + "efficientnet_b6", + "efficientnet_b7", + "efficientnet_v2_s", + "efficientnet_v2_m", + "efficientnet_v2_l", +] + + +@dataclass +class _MBConvConfig: + expand_ratio: float + kernel: int + stride: int + input_channels: int + out_channels: int + num_layers: int + block: Callable[..., nn.Module] + + @staticmethod + def adjust_channels(channels: int, width_mult: float, min_value: Optional[int] = None) -> int: + return _make_divisible(channels * width_mult, 8, min_value) + + +class MBConvConfig(_MBConvConfig): + # Stores information listed at Table 1 of the EfficientNet paper & Table 4 of the EfficientNetV2 paper + def __init__( + self, + expand_ratio: float, + kernel: int, + stride: int, + input_channels: int, + out_channels: int, + num_layers: int, + width_mult: float = 1.0, + depth_mult: float = 1.0, + block: Optional[Callable[..., nn.Module]] = None, + ) -> None: + input_channels = self.adjust_channels(input_channels, width_mult) + out_channels = self.adjust_channels(out_channels, width_mult) + num_layers = self.adjust_depth(num_layers, depth_mult) + if block is None: + block = MBConv + super().__init__(expand_ratio, kernel, stride, input_channels, out_channels, num_layers, block) + + @staticmethod + def adjust_depth(num_layers: int, depth_mult: float): + return int(math.ceil(num_layers * depth_mult)) + + +class FusedMBConvConfig(_MBConvConfig): + # Stores information listed at Table 4 of the EfficientNetV2 paper + def __init__( + self, + expand_ratio: float, + kernel: int, + stride: int, + input_channels: int, + out_channels: int, + num_layers: int, + block: Optional[Callable[..., nn.Module]] = None, + ) -> None: + if block is None: + block = FusedMBConv + super().__init__(expand_ratio, kernel, stride, input_channels, out_channels, num_layers, block) + + +class MBConv(nn.Module): + def __init__( + self, + cnf: MBConvConfig, + stochastic_depth_prob: float, + norm_layer: Callable[..., nn.Module], + se_layer: Callable[..., nn.Module] = SqueezeExcitation, + ) -> None: + super().__init__() + + if not (1 <= cnf.stride <= 2): + raise ValueError("illegal stride value") + + self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels + + layers: list[nn.Module] = [] + activation_layer = nn.SiLU + + # expand + expanded_channels = cnf.adjust_channels(cnf.input_channels, cnf.expand_ratio) + if expanded_channels != cnf.input_channels: + layers.append( + Conv2dNormActivation( + cnf.input_channels, + expanded_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # depthwise + layers.append( + Conv2dNormActivation( + expanded_channels, + expanded_channels, + kernel_size=cnf.kernel, + stride=cnf.stride, + groups=expanded_channels, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # squeeze and excitation + squeeze_channels = max(1, cnf.input_channels // 4) + layers.append(se_layer(expanded_channels, squeeze_channels, activation=partial(nn.SiLU, inplace=True))) + + # project + layers.append( + Conv2dNormActivation( + expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None + ) + ) + + self.block = nn.Sequential(*layers) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + self.out_channels = cnf.out_channels + + def forward(self, input: Tensor) -> Tensor: + result = self.block(input) + if self.use_res_connect: + result = self.stochastic_depth(result) + result += input + return result + + +class FusedMBConv(nn.Module): + def __init__( + self, + cnf: FusedMBConvConfig, + stochastic_depth_prob: float, + norm_layer: Callable[..., nn.Module], + ) -> None: + super().__init__() + + if not (1 <= cnf.stride <= 2): + raise ValueError("illegal stride value") + + self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels + + layers: list[nn.Module] = [] + activation_layer = nn.SiLU + + expanded_channels = cnf.adjust_channels(cnf.input_channels, cnf.expand_ratio) + if expanded_channels != cnf.input_channels: + # fused expand + layers.append( + Conv2dNormActivation( + cnf.input_channels, + expanded_channels, + kernel_size=cnf.kernel, + stride=cnf.stride, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # project + layers.append( + Conv2dNormActivation( + expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None + ) + ) + else: + layers.append( + Conv2dNormActivation( + cnf.input_channels, + cnf.out_channels, + kernel_size=cnf.kernel, + stride=cnf.stride, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + self.block = nn.Sequential(*layers) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + self.out_channels = cnf.out_channels + + def forward(self, input: Tensor) -> Tensor: + result = self.block(input) + if self.use_res_connect: + result = self.stochastic_depth(result) + result += input + return result + + +class EfficientNet(nn.Module): + def __init__( + self, + inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]], + dropout: float, + stochastic_depth_prob: float = 0.2, + num_classes: int = 1000, + norm_layer: Optional[Callable[..., nn.Module]] = None, + last_channel: Optional[int] = None, + ) -> None: + """ + EfficientNet V1 and V2 main class + + Args: + inverted_residual_setting (Sequence[Union[MBConvConfig, FusedMBConvConfig]]): Network structure + dropout (float): The droupout probability + stochastic_depth_prob (float): The stochastic depth probability + num_classes (int): Number of classes + norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use + last_channel (int): The number of channels on the penultimate layer + """ + super().__init__() + _log_api_usage_once(self) + + if not inverted_residual_setting: + raise ValueError("The inverted_residual_setting should not be empty") + elif not ( + isinstance(inverted_residual_setting, Sequence) + and all([isinstance(s, _MBConvConfig) for s in inverted_residual_setting]) + ): + raise TypeError("The inverted_residual_setting should be List[MBConvConfig]") + + if norm_layer is None: + norm_layer = nn.BatchNorm2d + + layers: list[nn.Module] = [] + + # building first layer + firstconv_output_channels = inverted_residual_setting[0].input_channels + layers.append( + Conv2dNormActivation( + 3, firstconv_output_channels, kernel_size=3, stride=2, norm_layer=norm_layer, activation_layer=nn.SiLU + ) + ) + + # building inverted residual blocks + total_stage_blocks = sum(cnf.num_layers for cnf in inverted_residual_setting) + stage_block_id = 0 + for cnf in inverted_residual_setting: + stage: list[nn.Module] = [] + for _ in range(cnf.num_layers): + # copy to avoid modifications. shallow copy is enough + block_cnf = copy.copy(cnf) + + # overwrite info if not the first conv in the stage + if stage: + block_cnf.input_channels = block_cnf.out_channels + block_cnf.stride = 1 + + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * float(stage_block_id) / total_stage_blocks + + stage.append(block_cnf.block(block_cnf, sd_prob, norm_layer)) + stage_block_id += 1 + + layers.append(nn.Sequential(*stage)) + + # building last several layers + lastconv_input_channels = inverted_residual_setting[-1].out_channels + lastconv_output_channels = last_channel if last_channel is not None else 4 * lastconv_input_channels + layers.append( + Conv2dNormActivation( + lastconv_input_channels, + lastconv_output_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=nn.SiLU, + ) + ) + + self.features = nn.Sequential(*layers) + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout, inplace=True), + nn.Linear(lastconv_output_channels, num_classes), + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + init_range = 1.0 / math.sqrt(m.out_features) + nn.init.uniform_(m.weight, -init_range, init_range) + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + x = self.features(x) + + x = self.avgpool(x) + x = torch.flatten(x, 1) + + x = self.classifier(x) + + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _efficientnet( + inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]], + dropout: float, + last_channel: Optional[int], + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> EfficientNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = EfficientNet(inverted_residual_setting, dropout, last_channel=last_channel, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +def _efficientnet_conf( + arch: str, + **kwargs: Any, +) -> tuple[Sequence[Union[MBConvConfig, FusedMBConvConfig]], Optional[int]]: + inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]] + if arch.startswith("efficientnet_b"): + bneck_conf = partial(MBConvConfig, width_mult=kwargs.pop("width_mult"), depth_mult=kwargs.pop("depth_mult")) + inverted_residual_setting = [ + bneck_conf(1, 3, 1, 32, 16, 1), + bneck_conf(6, 3, 2, 16, 24, 2), + bneck_conf(6, 5, 2, 24, 40, 2), + bneck_conf(6, 3, 2, 40, 80, 3), + bneck_conf(6, 5, 1, 80, 112, 3), + bneck_conf(6, 5, 2, 112, 192, 4), + bneck_conf(6, 3, 1, 192, 320, 1), + ] + last_channel = None + elif arch.startswith("efficientnet_v2_s"): + inverted_residual_setting = [ + FusedMBConvConfig(1, 3, 1, 24, 24, 2), + FusedMBConvConfig(4, 3, 2, 24, 48, 4), + FusedMBConvConfig(4, 3, 2, 48, 64, 4), + MBConvConfig(4, 3, 2, 64, 128, 6), + MBConvConfig(6, 3, 1, 128, 160, 9), + MBConvConfig(6, 3, 2, 160, 256, 15), + ] + last_channel = 1280 + elif arch.startswith("efficientnet_v2_m"): + inverted_residual_setting = [ + FusedMBConvConfig(1, 3, 1, 24, 24, 3), + FusedMBConvConfig(4, 3, 2, 24, 48, 5), + FusedMBConvConfig(4, 3, 2, 48, 80, 5), + MBConvConfig(4, 3, 2, 80, 160, 7), + MBConvConfig(6, 3, 1, 160, 176, 14), + MBConvConfig(6, 3, 2, 176, 304, 18), + MBConvConfig(6, 3, 1, 304, 512, 5), + ] + last_channel = 1280 + elif arch.startswith("efficientnet_v2_l"): + inverted_residual_setting = [ + FusedMBConvConfig(1, 3, 1, 32, 32, 4), + FusedMBConvConfig(4, 3, 2, 32, 64, 7), + FusedMBConvConfig(4, 3, 2, 64, 96, 7), + MBConvConfig(4, 3, 2, 96, 192, 10), + MBConvConfig(6, 3, 1, 192, 224, 19), + MBConvConfig(6, 3, 2, 224, 384, 25), + MBConvConfig(6, 3, 1, 384, 640, 7), + ] + last_channel = 1280 + else: + raise ValueError(f"Unsupported model type {arch}") + + return inverted_residual_setting, last_channel + + +_COMMON_META: dict[str, Any] = { + "categories": _IMAGENET_CATEGORIES, +} + + +_COMMON_META_V1 = { + **_COMMON_META, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#efficientnet-v1", +} + + +_COMMON_META_V2 = { + **_COMMON_META, + "min_size": (33, 33), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#efficientnet-v2", +} + + +class EfficientNet_B0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b0_rwightman-7f5810bc.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=256, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 5288548, + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.692, + "acc@5": 93.532, + } + }, + "_ops": 0.386, + "_file_size": 20.451, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B1_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b1_rwightman-bac287d4.pth", + transforms=partial( + ImageClassification, crop_size=240, resize_size=256, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 7794184, + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.642, + "acc@5": 94.186, + } + }, + "_ops": 0.687, + "_file_size": 30.134, + "_docs": """These weights are ported from the original paper.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/efficientnet_b1-c27df63c.pth", + transforms=partial( + ImageClassification, crop_size=240, resize_size=255, interpolation=InterpolationMode.BILINEAR + ), + meta={ + **_COMMON_META_V1, + "num_params": 7794184, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-lr-wd-crop-tuning", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.838, + "acc@5": 94.934, + } + }, + "_ops": 0.687, + "_file_size": 30.136, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class EfficientNet_B2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b2_rwightman-c35c1473.pth", + transforms=partial( + ImageClassification, crop_size=288, resize_size=288, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 9109994, + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.608, + "acc@5": 95.310, + } + }, + "_ops": 1.088, + "_file_size": 35.174, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B3_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b3_rwightman-b3899882.pth", + transforms=partial( + ImageClassification, crop_size=300, resize_size=320, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 12233232, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.008, + "acc@5": 96.054, + } + }, + "_ops": 1.827, + "_file_size": 47.184, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B4_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b4_rwightman-23ab8bcd.pth", + transforms=partial( + ImageClassification, crop_size=380, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 19341616, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.384, + "acc@5": 96.594, + } + }, + "_ops": 4.394, + "_file_size": 74.489, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/lukemelas/EfficientNet-PyTorch/ + url="https://download.pytorch.org/models/efficientnet_b5_lukemelas-1a07897c.pth", + transforms=partial( + ImageClassification, crop_size=456, resize_size=456, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 30389784, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.444, + "acc@5": 96.628, + } + }, + "_ops": 10.266, + "_file_size": 116.864, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B6_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/lukemelas/EfficientNet-PyTorch/ + url="https://download.pytorch.org/models/efficientnet_b6_lukemelas-24a108a5.pth", + transforms=partial( + ImageClassification, crop_size=528, resize_size=528, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 43040704, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.008, + "acc@5": 96.916, + } + }, + "_ops": 19.068, + "_file_size": 165.362, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B7_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/lukemelas/EfficientNet-PyTorch/ + url="https://download.pytorch.org/models/efficientnet_b7_lukemelas-c5b4e57e.pth", + transforms=partial( + ImageClassification, crop_size=600, resize_size=600, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 66347960, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.122, + "acc@5": 96.908, + } + }, + "_ops": 37.746, + "_file_size": 254.675, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_V2_S_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/efficientnet_v2_s-dd5fe13b.pth", + transforms=partial( + ImageClassification, + crop_size=384, + resize_size=384, + interpolation=InterpolationMode.BILINEAR, + ), + meta={ + **_COMMON_META_V2, + "num_params": 21458488, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.228, + "acc@5": 96.878, + } + }, + "_ops": 8.366, + "_file_size": 82.704, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_V2_M_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/efficientnet_v2_m-dc08266a.pth", + transforms=partial( + ImageClassification, + crop_size=480, + resize_size=480, + interpolation=InterpolationMode.BILINEAR, + ), + meta={ + **_COMMON_META_V2, + "num_params": 54139356, + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.112, + "acc@5": 97.156, + } + }, + "_ops": 24.582, + "_file_size": 208.01, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_V2_L_Weights(WeightsEnum): + # Weights ported from https://github.com/google/automl/tree/master/efficientnetv2 + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/efficientnet_v2_l-59c71312.pth", + transforms=partial( + ImageClassification, + crop_size=480, + resize_size=480, + interpolation=InterpolationMode.BICUBIC, + mean=(0.5, 0.5, 0.5), + std=(0.5, 0.5, 0.5), + ), + meta={ + **_COMMON_META_V2, + "num_params": 118515272, + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.808, + "acc@5": 97.788, + } + }, + "_ops": 56.08, + "_file_size": 454.573, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B0_Weights.IMAGENET1K_V1)) +def efficientnet_b0( + *, weights: Optional[EfficientNet_B0_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B0 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B0_Weights + :members: + """ + weights = EfficientNet_B0_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b0", width_mult=1.0, depth_mult=1.0) + return _efficientnet( + inverted_residual_setting, kwargs.pop("dropout", 0.2), last_channel, weights, progress, **kwargs + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B1_Weights.IMAGENET1K_V1)) +def efficientnet_b1( + *, weights: Optional[EfficientNet_B1_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B1 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B1_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B1_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B1_Weights + :members: + """ + weights = EfficientNet_B1_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b1", width_mult=1.0, depth_mult=1.1) + return _efficientnet( + inverted_residual_setting, kwargs.pop("dropout", 0.2), last_channel, weights, progress, **kwargs + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B2_Weights.IMAGENET1K_V1)) +def efficientnet_b2( + *, weights: Optional[EfficientNet_B2_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B2 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B2_Weights + :members: + """ + weights = EfficientNet_B2_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b2", width_mult=1.1, depth_mult=1.2) + return _efficientnet( + inverted_residual_setting, kwargs.pop("dropout", 0.3), last_channel, weights, progress, **kwargs + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B3_Weights.IMAGENET1K_V1)) +def efficientnet_b3( + *, weights: Optional[EfficientNet_B3_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B3 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B3_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B3_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B3_Weights + :members: + """ + weights = EfficientNet_B3_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b3", width_mult=1.2, depth_mult=1.4) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.3), + last_channel, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B4_Weights.IMAGENET1K_V1)) +def efficientnet_b4( + *, weights: Optional[EfficientNet_B4_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B4 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B4_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B4_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B4_Weights + :members: + """ + weights = EfficientNet_B4_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b4", width_mult=1.4, depth_mult=1.8) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.4), + last_channel, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B5_Weights.IMAGENET1K_V1)) +def efficientnet_b5( + *, weights: Optional[EfficientNet_B5_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B5 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B5_Weights + :members: + """ + weights = EfficientNet_B5_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b5", width_mult=1.6, depth_mult=2.2) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.4), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B6_Weights.IMAGENET1K_V1)) +def efficientnet_b6( + *, weights: Optional[EfficientNet_B6_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B6 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B6_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B6_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B6_Weights + :members: + """ + weights = EfficientNet_B6_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b6", width_mult=1.8, depth_mult=2.6) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.5), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B7_Weights.IMAGENET1K_V1)) +def efficientnet_b7( + *, weights: Optional[EfficientNet_B7_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B7 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B7_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B7_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B7_Weights + :members: + """ + weights = EfficientNet_B7_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b7", width_mult=2.0, depth_mult=3.1) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.5), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_V2_S_Weights.IMAGENET1K_V1)) +def efficientnet_v2_s( + *, weights: Optional[EfficientNet_V2_S_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """ + Constructs an EfficientNetV2-S architecture from + `EfficientNetV2: Smaller Models and Faster Training `_. + + Args: + weights (:class:`~torchvision.models.EfficientNet_V2_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_V2_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_V2_S_Weights + :members: + """ + weights = EfficientNet_V2_S_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_v2_s") + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.2), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=1e-03), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_V2_M_Weights.IMAGENET1K_V1)) +def efficientnet_v2_m( + *, weights: Optional[EfficientNet_V2_M_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """ + Constructs an EfficientNetV2-M architecture from + `EfficientNetV2: Smaller Models and Faster Training `_. + + Args: + weights (:class:`~torchvision.models.EfficientNet_V2_M_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_V2_M_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_V2_M_Weights + :members: + """ + weights = EfficientNet_V2_M_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_v2_m") + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.3), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=1e-03), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_V2_L_Weights.IMAGENET1K_V1)) +def efficientnet_v2_l( + *, weights: Optional[EfficientNet_V2_L_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """ + Constructs an EfficientNetV2-L architecture from + `EfficientNetV2: Smaller Models and Faster Training `_. + + Args: + weights (:class:`~torchvision.models.EfficientNet_V2_L_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_V2_L_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_V2_L_Weights + :members: + """ + weights = EfficientNet_V2_L_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_v2_l") + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.4), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=1e-03), + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/feature_extraction.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..320b1936d6f8897d6f324b6c4938dbe289fd466e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/feature_extraction.py @@ -0,0 +1,607 @@ +import copy +import inspect +import math +import re +import warnings +from collections import OrderedDict +from copy import deepcopy +from itertools import chain +from typing import Any, Callable, Optional, Union + +import torch +import torchvision +from torch import fx, nn +from torch.fx.graph_module import _CodeOnlyModule, _copy_attr, _USER_PRESERVED_ATTRIBUTES_KEY + + +__all__ = ["create_feature_extractor", "get_graph_node_names"] + + +class LeafModuleAwareTracer(fx.Tracer): + """ + An fx.Tracer that allows the user to specify a set of leaf modules, i.e. + modules that are not to be traced through. The resulting graph ends up + having single nodes referencing calls to the leaf modules' forward methods. + """ + + def __init__(self, *args, **kwargs): + self.leaf_modules = {} + if "leaf_modules" in kwargs: + leaf_modules = kwargs.pop("leaf_modules") + self.leaf_modules = leaf_modules + super().__init__(*args, **kwargs) + + def is_leaf_module(self, m: nn.Module, module_qualname: str) -> bool: + if isinstance(m, tuple(self.leaf_modules)): + return True + return super().is_leaf_module(m, module_qualname) + + +class NodePathTracer(LeafModuleAwareTracer): + """ + NodePathTracer is an FX tracer that, for each operation, also records the + name of the Node from which the operation originated. A node name here is + a `.` separated path walking the hierarchy from top level module down to + leaf operation or leaf module. The name of the top level module is not + included as part of the node name. For example, if we trace a module whose + forward method applies a ReLU module, the name for that node will simply + be 'relu'. + + Some notes on the specifics: + - Nodes are recorded to `self.node_to_qualname` which is a dictionary + mapping a given Node object to its node name. + - Nodes are recorded in the order which they are executed during + tracing. + - When a duplicate node name is encountered, a suffix of the form + _{int} is added. The counter starts from 1. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Track the qualified name of the Node being traced + self.current_module_qualname = "" + # A map from FX Node to the qualified name\# + # NOTE: This is loosely like the "qualified name" mentioned in the + # torch.fx docs https://pytorch.org/docs/stable/fx.html but adapted + # for the purposes of the torchvision feature extractor + self.node_to_qualname = OrderedDict() + + def call_module(self, m: torch.nn.Module, forward: Callable, args, kwargs): + """ + Override of `fx.Tracer.call_module` + This override: + 1) Stores away the qualified name of the caller for restoration later + 2) Adds the qualified name of the caller to + `current_module_qualname` for retrieval by `create_proxy` + 3) Once a leaf module is reached, calls `create_proxy` + 4) Restores the caller's qualified name into current_module_qualname + """ + old_qualname = self.current_module_qualname + try: + module_qualname = self.path_of_module(m) + self.current_module_qualname = module_qualname + if not self.is_leaf_module(m, module_qualname): + out = forward(*args, **kwargs) + return out + return self.create_proxy("call_module", module_qualname, args, kwargs) + finally: + self.current_module_qualname = old_qualname + + def create_proxy( + self, kind: str, target: fx.node.Target, args, kwargs, name=None, type_expr=None, *_ + ) -> fx.proxy.Proxy: + """ + Override of `Tracer.create_proxy`. This override intercepts the recording + of every operation and stores away the current traced module's qualified + name in `node_to_qualname` + """ + proxy = super().create_proxy(kind, target, args, kwargs, name, type_expr) + self.node_to_qualname[proxy.node] = self._get_node_qualname(self.current_module_qualname, proxy.node) + return proxy + + def _get_node_qualname(self, module_qualname: str, node: fx.node.Node) -> str: + node_qualname = module_qualname + + if node.op != "call_module": + # In this case module_qualname from torch.fx doesn't go all the + # way to the leaf function/op, so we need to append it + if len(node_qualname) > 0: + # Only append '.' if we are deeper than the top level module + node_qualname += "." + node_qualname += str(node) + + # Now we need to add an _{index} postfix on any repeated node names + # For modules we do this from scratch + # But for anything else, torch.fx already has a globally scoped + # _{index} postfix. But we want it locally (relative to direct parent) + # scoped. So first we need to undo the torch.fx postfix + if re.match(r".+_[0-9]+$", node_qualname) is not None: + node_qualname = node_qualname.rsplit("_", 1)[0] + + # ... and now we add on our own postfix + for existing_qualname in reversed(self.node_to_qualname.values()): + # Check to see if existing_qualname is of the form + # {node_qualname} or {node_qualname}_{int} + if re.match(rf"{node_qualname}(_[0-9]+)?$", existing_qualname) is not None: + postfix = existing_qualname.replace(node_qualname, "") + if len(postfix): + # existing_qualname is of the form {node_qualname}_{int} + next_index = int(postfix[1:]) + 1 + else: + # existing_qualname is of the form {node_qualname} + next_index = 1 + node_qualname += f"_{next_index}" + break + + return node_qualname + + +def _is_subseq(x, y): + """Check if y is a subsequence of x + https://stackoverflow.com/a/24017747/4391249 + """ + iter_x = iter(x) + return all(any(x_item == y_item for x_item in iter_x) for y_item in y) + + +def _warn_graph_differences(train_tracer: NodePathTracer, eval_tracer: NodePathTracer): + """ + Utility function for warning the user if there are differences between + the train graph nodes and the eval graph nodes. + """ + train_nodes = list(train_tracer.node_to_qualname.values()) + eval_nodes = list(eval_tracer.node_to_qualname.values()) + + if len(train_nodes) == len(eval_nodes) and all(t == e for t, e in zip(train_nodes, eval_nodes)): + return + + suggestion_msg = ( + "When choosing nodes for feature extraction, you may need to specify " + "output nodes for train and eval mode separately." + ) + + if _is_subseq(train_nodes, eval_nodes): + msg = ( + "NOTE: The nodes obtained by tracing the model in eval mode " + "are a subsequence of those obtained in train mode. " + ) + elif _is_subseq(eval_nodes, train_nodes): + msg = ( + "NOTE: The nodes obtained by tracing the model in train mode " + "are a subsequence of those obtained in eval mode. " + ) + else: + msg = "The nodes obtained by tracing the model in train mode are different to those obtained in eval mode. " + warnings.warn(msg + suggestion_msg) + + +def _get_leaf_modules_for_ops() -> list[type]: + members = inspect.getmembers(torchvision.ops) + result = [] + for _, obj in members: + if inspect.isclass(obj) and issubclass(obj, torch.nn.Module): + result.append(obj) + return result + + +def _set_default_tracer_kwargs(original_tr_kwargs: Optional[dict[str, Any]]) -> dict[str, Any]: + default_autowrap_modules = (math, torchvision.ops) + default_leaf_modules = _get_leaf_modules_for_ops() + result_tracer_kwargs = {} if original_tr_kwargs is None else original_tr_kwargs + result_tracer_kwargs["autowrap_modules"] = ( + tuple(set(result_tracer_kwargs["autowrap_modules"] + default_autowrap_modules)) + if "autowrap_modules" in result_tracer_kwargs + else default_autowrap_modules + ) + result_tracer_kwargs["leaf_modules"] = ( + list(set(result_tracer_kwargs["leaf_modules"] + default_leaf_modules)) + if "leaf_modules" in result_tracer_kwargs + else default_leaf_modules + ) + return result_tracer_kwargs + + +def get_graph_node_names( + model: nn.Module, + tracer_kwargs: Optional[dict[str, Any]] = None, + suppress_diff_warning: bool = False, + concrete_args: Optional[dict[str, Any]] = None, +) -> tuple[list[str], list[str]]: + """ + Dev utility to return node names in order of execution. See note on node + names under :func:`create_feature_extractor`. Useful for seeing which node + names are available for feature extraction. There are two reasons that + node names can't easily be read directly from the code for a model: + + 1. Not all submodules are traced through. Modules from ``torch.nn`` all + fall within this category. + 2. Nodes representing the repeated application of the same operation + or leaf module get a ``_{counter}`` postfix. + + The model is traced twice: once in train mode, and once in eval mode. Both + sets of node names are returned. + + For more details on the node naming conventions used here, please see the + :ref:`relevant subheading ` in the + `documentation `_. + + Args: + model (nn.Module): model for which we'd like to print node names + tracer_kwargs (dict, optional): a dictionary of keyword arguments for + ``NodePathTracer`` (they are eventually passed onto + `torch.fx.Tracer `_). + By default, it will be set to wrap and make leaf nodes all torchvision ops: + {"autowrap_modules": (math, torchvision.ops,),"leaf_modules": _get_leaf_modules_for_ops(),} + WARNING: In case the user provides tracer_kwargs, above default arguments will be appended to the user + provided dictionary. + suppress_diff_warning (bool, optional): whether to suppress a warning + when there are discrepancies between the train and eval version of + the graph. Defaults to False. + concrete_args (Optional[Dict[str, any]]): Concrete arguments that should + not be treated as Proxies. According to the `Pytorch docs + `_, + this parameter's API may not be guaranteed. + + Returns: + tuple(list, list): a list of node names from tracing the model in + train mode, and another from tracing the model in eval mode. + + Examples:: + + >>> model = torchvision.models.resnet18() + >>> train_nodes, eval_nodes = get_graph_node_names(model) + """ + tracer_kwargs = _set_default_tracer_kwargs(tracer_kwargs) + is_training = model.training + train_tracer = NodePathTracer(**tracer_kwargs) + train_tracer.trace(model.train(), concrete_args=concrete_args) + eval_tracer = NodePathTracer(**tracer_kwargs) + eval_tracer.trace(model.eval(), concrete_args=concrete_args) + train_nodes = list(train_tracer.node_to_qualname.values()) + eval_nodes = list(eval_tracer.node_to_qualname.values()) + if not suppress_diff_warning: + _warn_graph_differences(train_tracer, eval_tracer) + # Restore training state + model.train(is_training) + return train_nodes, eval_nodes + + +class DualGraphModule(fx.GraphModule): + """ + A derivative of `fx.GraphModule`. Differs in the following ways: + - Requires a train and eval version of the underlying graph + - Copies submodules according to the nodes of both train and eval graphs. + - Calling train(mode) switches between train graph and eval graph. + """ + + def __init__( + self, root: torch.nn.Module, train_graph: fx.Graph, eval_graph: fx.Graph, class_name: str = "GraphModule" + ): + """ + Args: + root (nn.Module): module from which the copied module hierarchy is + built + train_graph (fx.Graph): the graph that should be used in train mode + eval_graph (fx.Graph): the graph that should be used in eval mode + """ + super(fx.GraphModule, self).__init__() + + self.__class__.__name__ = class_name + + self.train_graph = train_graph + self.eval_graph = eval_graph + + # Copy all get_attr and call_module ops (indicated by BOTH train and + # eval graphs) + for node in chain(iter(train_graph.nodes), iter(eval_graph.nodes)): + if node.op in ["get_attr", "call_module"]: + if not isinstance(node.target, str): + raise TypeError(f"node.target should be of type str instead of {type(node.target)}") + _copy_attr(root, self, node.target) + + # train mode by default + self.train() + self.graph = train_graph + + # (borrowed from fx.GraphModule): + # Store the Tracer class responsible for creating a Graph separately as part of the + # GraphModule state, except when the Tracer is defined in a local namespace. + # Locally defined Tracers are not pickleable. This is needed because torch.package will + # serialize a GraphModule without retaining the Graph, and needs to use the correct Tracer + # to re-create the Graph during deserialization. + if self.eval_graph._tracer_cls != self.train_graph._tracer_cls: + raise TypeError( + f"Train mode and eval mode should use the same tracer class. Instead got {self.eval_graph._tracer_cls} for eval vs {self.train_graph._tracer_cls} for train" + ) + self._tracer_cls = None + if self.graph._tracer_cls and "" not in self.graph._tracer_cls.__qualname__: + self._tracer_cls = self.graph._tracer_cls + + def train(self, mode=True): + """ + Swap out the graph depending on the selected training mode. + NOTE this should be safe when calling model.eval() because that just + calls this with mode == False. + """ + # NOTE: Only set self.graph if the current graph is not the desired + # one. This saves us from recompiling the graph where not necessary. + if mode and not self.training: + self.graph = self.train_graph + elif not mode and self.training: + self.graph = self.eval_graph + return super().train(mode=mode) + + def _deepcopy_init(self): + # See __deepcopy__ below + return DualGraphModule.__init__ + + def __deepcopy__(self, memo): + # Same as the base class' __deepcopy__ from pytorch, with minor + # modification to account for train_graph and eval_graph + # https://github.com/pytorch/pytorch/blob/f684dbd0026f98f8fa291cab74dbc4d61ba30580/torch/fx/graph_module.py#L875 + # + # This is using a bunch of private stuff from torch, so if that breaks, + # we'll likely have to remove this, along with the associated + # non-regression test. + res = type(self).__new__(type(self)) + memo[id(self)] = res + fake_mod = _CodeOnlyModule(copy.deepcopy(self.__dict__, memo)) + self._deepcopy_init()(res, fake_mod, fake_mod.__dict__["train_graph"], fake_mod.__dict__["eval_graph"]) + + extra_preserved_attrs = [ + "_state_dict_hooks", + "_load_state_dict_pre_hooks", + "_load_state_dict_post_hooks", + "_replace_hook", + "_create_node_hooks", + "_erase_node_hooks", + ] + for attr in extra_preserved_attrs: + if attr in self.__dict__: + setattr(res, attr, copy.deepcopy(self.__dict__[attr], memo)) + res.meta = copy.deepcopy(getattr(self, "meta", {}), memo) + if _USER_PRESERVED_ATTRIBUTES_KEY in res.meta: + for attr_name, attr in res.meta[_USER_PRESERVED_ATTRIBUTES_KEY].items(): + setattr(res, attr_name, attr) + return res + + +def create_feature_extractor( + model: nn.Module, + return_nodes: Optional[Union[list[str], dict[str, str]]] = None, + train_return_nodes: Optional[Union[list[str], dict[str, str]]] = None, + eval_return_nodes: Optional[Union[list[str], dict[str, str]]] = None, + tracer_kwargs: Optional[dict[str, Any]] = None, + suppress_diff_warning: bool = False, + concrete_args: Optional[dict[str, Any]] = None, +) -> fx.GraphModule: + """ + Creates a new graph module that returns intermediate nodes from a given + model as dictionary with user specified keys as strings, and the requested + outputs as values. This is achieved by re-writing the computation graph of + the model via FX to return the desired nodes as outputs. All unused nodes + are removed, together with their corresponding parameters. + + Desired output nodes must be specified as a ``.`` separated + path walking the module hierarchy from top level module down to leaf + operation or leaf module. For more details on the node naming conventions + used here, please see the :ref:`relevant subheading ` + in the `documentation `_. + + Not all models will be FX traceable, although with some massaging they can + be made to cooperate. Here's a (not exhaustive) list of tips: + + - If you don't need to trace through a particular, problematic + sub-module, turn it into a "leaf module" by passing a list of + ``leaf_modules`` as one of the ``tracer_kwargs`` (see example below). + It will not be traced through, but rather, the resulting graph will + hold a reference to that module's forward method. + - Likewise, you may turn functions into leaf functions by passing a + list of ``autowrap_functions`` as one of the ``tracer_kwargs`` (see + example below). + - Some inbuilt Python functions can be problematic. For instance, + ``int`` will raise an error during tracing. You may wrap them in your + own function and then pass that in ``autowrap_functions`` as one of + the ``tracer_kwargs``. + + For further information on FX see the + `torch.fx documentation `_. + + Args: + model (nn.Module): model on which we will extract the features + return_nodes (list or dict, optional): either a ``List`` or a ``Dict`` + containing the names (or partial names - see note above) + of the nodes for which the activations will be returned. If it is + a ``Dict``, the keys are the node names, and the values + are the user-specified keys for the graph module's returned + dictionary. If it is a ``List``, it is treated as a ``Dict`` mapping + node specification strings directly to output names. In the case + that ``train_return_nodes`` and ``eval_return_nodes`` are specified, + this should not be specified. + train_return_nodes (list or dict, optional): similar to + ``return_nodes``. This can be used if the return nodes + for train mode are different than those from eval mode. + If this is specified, ``eval_return_nodes`` must also be specified, + and ``return_nodes`` should not be specified. + eval_return_nodes (list or dict, optional): similar to + ``return_nodes``. This can be used if the return nodes + for train mode are different than those from eval mode. + If this is specified, ``train_return_nodes`` must also be specified, + and `return_nodes` should not be specified. + tracer_kwargs (dict, optional): a dictionary of keyword arguments for + ``NodePathTracer`` (which passes them onto it's parent class + `torch.fx.Tracer `_). + By default, it will be set to wrap and make leaf nodes all torchvision ops: + {"autowrap_modules": (math, torchvision.ops,),"leaf_modules": _get_leaf_modules_for_ops(),} + WARNING: In case the user provides tracer_kwargs, above default arguments will be appended to the user + provided dictionary. + suppress_diff_warning (bool, optional): whether to suppress a warning + when there are discrepancies between the train and eval version of + the graph. Defaults to False. + concrete_args (Optional[Dict[str, any]]): Concrete arguments that should + not be treated as Proxies. According to the `Pytorch docs + `_, + this parameter's API may not be guaranteed. + + Examples:: + + >>> # Feature extraction with resnet + >>> model = torchvision.models.resnet18() + >>> # extract layer1 and layer3, giving as names `feat1` and feat2` + >>> model = create_feature_extractor( + >>> model, {'layer1': 'feat1', 'layer3': 'feat2'}) + >>> out = model(torch.rand(1, 3, 224, 224)) + >>> print([(k, v.shape) for k, v in out.items()]) + >>> [('feat1', torch.Size([1, 64, 56, 56])), + >>> ('feat2', torch.Size([1, 256, 14, 14]))] + + >>> # Specifying leaf modules and leaf functions + >>> def leaf_function(x): + >>> # This would raise a TypeError if traced through + >>> return int(x) + >>> + >>> class LeafModule(torch.nn.Module): + >>> def forward(self, x): + >>> # This would raise a TypeError if traced through + >>> int(x.shape[0]) + >>> return torch.nn.functional.relu(x + 4) + >>> + >>> class MyModule(torch.nn.Module): + >>> def __init__(self): + >>> super().__init__() + >>> self.conv = torch.nn.Conv2d(3, 1, 3) + >>> self.leaf_module = LeafModule() + >>> + >>> def forward(self, x): + >>> leaf_function(x.shape[0]) + >>> x = self.conv(x) + >>> return self.leaf_module(x) + >>> + >>> model = create_feature_extractor( + >>> MyModule(), return_nodes=['leaf_module'], + >>> tracer_kwargs={'leaf_modules': [LeafModule], + >>> 'autowrap_functions': [leaf_function]}) + + """ + tracer_kwargs = _set_default_tracer_kwargs(tracer_kwargs) + is_training = model.training + + if all(arg is None for arg in [return_nodes, train_return_nodes, eval_return_nodes]): + + raise ValueError( + "Either `return_nodes` or `train_return_nodes` and `eval_return_nodes` together, should be specified" + ) + + if (train_return_nodes is None) ^ (eval_return_nodes is None): + raise ValueError( + "If any of `train_return_nodes` and `eval_return_nodes` are specified, then both should be specified" + ) + + if not ((return_nodes is None) ^ (train_return_nodes is None)): + raise ValueError("If `train_return_nodes` and `eval_return_nodes` are specified, then both should be specified") + + # Put *_return_nodes into Dict[str, str] format + def to_strdict(n) -> dict[str, str]: + if isinstance(n, list): + return {str(i): str(i) for i in n} + return {str(k): str(v) for k, v in n.items()} + + if train_return_nodes is None: + return_nodes = to_strdict(return_nodes) + train_return_nodes = deepcopy(return_nodes) + eval_return_nodes = deepcopy(return_nodes) + else: + train_return_nodes = to_strdict(train_return_nodes) + eval_return_nodes = to_strdict(eval_return_nodes) + + # Repeat the tracing and graph rewriting for train and eval mode + tracers = {} + graphs = {} + mode_return_nodes: dict[str, dict[str, str]] = {"train": train_return_nodes, "eval": eval_return_nodes} + for mode in ["train", "eval"]: + if mode == "train": + model.train() + elif mode == "eval": + model.eval() + + # Instantiate our NodePathTracer and use that to trace the model + tracer = NodePathTracer(**tracer_kwargs) + graph = tracer.trace(model, concrete_args=concrete_args) + + name = model.__class__.__name__ if isinstance(model, nn.Module) else model.__name__ + graph_module = fx.GraphModule(tracer.root, graph, name) + + available_nodes = list(tracer.node_to_qualname.values()) + # FIXME We don't know if we should expect this to happen + if len(set(available_nodes)) != len(available_nodes): + raise ValueError( + "There are duplicate nodes! Please raise an issue https://github.com/pytorch/vision/issues" + ) + # Check that all outputs in return_nodes are present in the model + for query in mode_return_nodes[mode].keys(): + # To check if a query is available we need to check that at least + # one of the available names starts with it up to a . + if not any([re.match(rf"^{query}(\.|$)", n) is not None for n in available_nodes]): + raise ValueError( + f"node: '{query}' is not present in model. Hint: use " + "`get_graph_node_names` to make sure the " + "`return_nodes` you specified are present. It may even " + "be that you need to specify `train_return_nodes` and " + "`eval_return_nodes` separately." + ) + + # Remove existing output nodes (train mode) + orig_output_nodes = [] + for n in reversed(graph_module.graph.nodes): + if n.op == "output": + orig_output_nodes.append(n) + if not orig_output_nodes: + raise ValueError("No output nodes found in graph_module.graph.nodes") + + for n in orig_output_nodes: + graph_module.graph.erase_node(n) + + # Find nodes corresponding to return_nodes and make them into output_nodes + nodes = [n for n in graph_module.graph.nodes] + output_nodes = OrderedDict() + for n in reversed(nodes): + module_qualname = tracer.node_to_qualname.get(n) + if module_qualname is None: + # NOTE - Know cases where this happens: + # - Node representing creation of a tensor constant - probably + # not interesting as a return node + # - When packing outputs into a named tuple like in InceptionV3 + continue + for query in mode_return_nodes[mode]: + depth = query.count(".") + if ".".join(module_qualname.split(".")[: depth + 1]) == query: + output_nodes[mode_return_nodes[mode][query]] = n + mode_return_nodes[mode].pop(query) + break + output_nodes = OrderedDict(reversed(list(output_nodes.items()))) + + # And add them in the end of the graph + with graph_module.graph.inserting_after(nodes[-1]): + graph_module.graph.output(output_nodes) + + # Remove unused modules / parameters + graph_module.graph.eliminate_dead_code() + graph_module.recompile() + + # Keep track of the tracer and graph, so we can choose the main one + tracers[mode] = tracer + graphs[mode] = graph + + # Warn user if there are any discrepancies between the graphs of the + # train and eval modes + if not suppress_diff_warning: + _warn_graph_differences(tracers["train"], tracers["eval"]) + + # Build the final graph module + graph_module = DualGraphModule(model, graphs["train"], graphs["eval"], class_name=name) + + # Restore original training mode + model.train(is_training) + graph_module.train(is_training) + + return graph_module diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/googlenet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/googlenet.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb29764951531b2fbfa91ea91e367ba240f05b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/googlenet.py @@ -0,0 +1,345 @@ +import warnings +from collections import namedtuple +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["GoogLeNet", "GoogLeNetOutputs", "_GoogLeNetOutputs", "GoogLeNet_Weights", "googlenet"] + + +GoogLeNetOutputs = namedtuple("GoogLeNetOutputs", ["logits", "aux_logits2", "aux_logits1"]) +GoogLeNetOutputs.__annotations__ = {"logits": Tensor, "aux_logits2": Optional[Tensor], "aux_logits1": Optional[Tensor]} + +# Script annotations failed with _GoogleNetOutputs = namedtuple ... +# _GoogLeNetOutputs set here for backwards compat +_GoogLeNetOutputs = GoogLeNetOutputs + + +class GoogLeNet(nn.Module): + __constants__ = ["aux_logits", "transform_input"] + + def __init__( + self, + num_classes: int = 1000, + aux_logits: bool = True, + transform_input: bool = False, + init_weights: Optional[bool] = None, + blocks: Optional[list[Callable[..., nn.Module]]] = None, + dropout: float = 0.2, + dropout_aux: float = 0.7, + ) -> None: + super().__init__() + _log_api_usage_once(self) + if blocks is None: + blocks = [BasicConv2d, Inception, InceptionAux] + if init_weights is None: + warnings.warn( + "The default weight initialization of GoogleNet will be changed in future releases of " + "torchvision. If you wish to keep the old behavior (which leads to long initialization times" + " due to scipy/scipy#11299), please set init_weights=True.", + FutureWarning, + ) + init_weights = True + if len(blocks) != 3: + raise ValueError(f"blocks length should be 3 instead of {len(blocks)}") + conv_block = blocks[0] + inception_block = blocks[1] + inception_aux_block = blocks[2] + + self.aux_logits = aux_logits + self.transform_input = transform_input + + self.conv1 = conv_block(3, 64, kernel_size=7, stride=2, padding=3) + self.maxpool1 = nn.MaxPool2d(3, stride=2, ceil_mode=True) + self.conv2 = conv_block(64, 64, kernel_size=1) + self.conv3 = conv_block(64, 192, kernel_size=3, padding=1) + self.maxpool2 = nn.MaxPool2d(3, stride=2, ceil_mode=True) + + self.inception3a = inception_block(192, 64, 96, 128, 16, 32, 32) + self.inception3b = inception_block(256, 128, 128, 192, 32, 96, 64) + self.maxpool3 = nn.MaxPool2d(3, stride=2, ceil_mode=True) + + self.inception4a = inception_block(480, 192, 96, 208, 16, 48, 64) + self.inception4b = inception_block(512, 160, 112, 224, 24, 64, 64) + self.inception4c = inception_block(512, 128, 128, 256, 24, 64, 64) + self.inception4d = inception_block(512, 112, 144, 288, 32, 64, 64) + self.inception4e = inception_block(528, 256, 160, 320, 32, 128, 128) + self.maxpool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.inception5a = inception_block(832, 256, 160, 320, 32, 128, 128) + self.inception5b = inception_block(832, 384, 192, 384, 48, 128, 128) + + if aux_logits: + self.aux1 = inception_aux_block(512, num_classes, dropout=dropout_aux) + self.aux2 = inception_aux_block(528, num_classes, dropout=dropout_aux) + else: + self.aux1 = None # type: ignore[assignment] + self.aux2 = None # type: ignore[assignment] + + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.dropout = nn.Dropout(p=dropout) + self.fc = nn.Linear(1024, num_classes) + + if init_weights: + for m in self.modules(): + if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear): + torch.nn.init.trunc_normal_(m.weight, mean=0.0, std=0.01, a=-2, b=2) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def _transform_input(self, x: Tensor) -> Tensor: + if self.transform_input: + x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 + x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 + x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 + x = torch.cat((x_ch0, x_ch1, x_ch2), 1) + return x + + def _forward(self, x: Tensor) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + # N x 3 x 224 x 224 + x = self.conv1(x) + # N x 64 x 112 x 112 + x = self.maxpool1(x) + # N x 64 x 56 x 56 + x = self.conv2(x) + # N x 64 x 56 x 56 + x = self.conv3(x) + # N x 192 x 56 x 56 + x = self.maxpool2(x) + + # N x 192 x 28 x 28 + x = self.inception3a(x) + # N x 256 x 28 x 28 + x = self.inception3b(x) + # N x 480 x 28 x 28 + x = self.maxpool3(x) + # N x 480 x 14 x 14 + x = self.inception4a(x) + # N x 512 x 14 x 14 + aux1: Optional[Tensor] = None + if self.aux1 is not None: + if self.training: + aux1 = self.aux1(x) + + x = self.inception4b(x) + # N x 512 x 14 x 14 + x = self.inception4c(x) + # N x 512 x 14 x 14 + x = self.inception4d(x) + # N x 528 x 14 x 14 + aux2: Optional[Tensor] = None + if self.aux2 is not None: + if self.training: + aux2 = self.aux2(x) + + x = self.inception4e(x) + # N x 832 x 14 x 14 + x = self.maxpool4(x) + # N x 832 x 7 x 7 + x = self.inception5a(x) + # N x 832 x 7 x 7 + x = self.inception5b(x) + # N x 1024 x 7 x 7 + + x = self.avgpool(x) + # N x 1024 x 1 x 1 + x = torch.flatten(x, 1) + # N x 1024 + x = self.dropout(x) + x = self.fc(x) + # N x 1000 (num_classes) + return x, aux2, aux1 + + @torch.jit.unused + def eager_outputs(self, x: Tensor, aux2: Tensor, aux1: Optional[Tensor]) -> GoogLeNetOutputs: + if self.training and self.aux_logits: + return _GoogLeNetOutputs(x, aux2, aux1) + else: + return x # type: ignore[return-value] + + def forward(self, x: Tensor) -> GoogLeNetOutputs: + x = self._transform_input(x) + x, aux2, aux1 = self._forward(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted GoogleNet always returns GoogleNetOutputs Tuple") + return GoogLeNetOutputs(x, aux2, aux1) + else: + return self.eager_outputs(x, aux2, aux1) + + +class Inception(nn.Module): + def __init__( + self, + in_channels: int, + ch1x1: int, + ch3x3red: int, + ch3x3: int, + ch5x5red: int, + ch5x5: int, + pool_proj: int, + conv_block: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1 = conv_block(in_channels, ch1x1, kernel_size=1) + + self.branch2 = nn.Sequential( + conv_block(in_channels, ch3x3red, kernel_size=1), conv_block(ch3x3red, ch3x3, kernel_size=3, padding=1) + ) + + self.branch3 = nn.Sequential( + conv_block(in_channels, ch5x5red, kernel_size=1), + # Here, kernel_size=3 instead of kernel_size=5 is a known bug. + # Please see https://github.com/pytorch/vision/issues/906 for details. + conv_block(ch5x5red, ch5x5, kernel_size=3, padding=1), + ) + + self.branch4 = nn.Sequential( + nn.MaxPool2d(kernel_size=3, stride=1, padding=1, ceil_mode=True), + conv_block(in_channels, pool_proj, kernel_size=1), + ) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1 = self.branch1(x) + branch2 = self.branch2(x) + branch3 = self.branch3(x) + branch4 = self.branch4(x) + + outputs = [branch1, branch2, branch3, branch4] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionAux(nn.Module): + def __init__( + self, + in_channels: int, + num_classes: int, + conv_block: Optional[Callable[..., nn.Module]] = None, + dropout: float = 0.7, + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.conv = conv_block(in_channels, 128, kernel_size=1) + + self.fc1 = nn.Linear(2048, 1024) + self.fc2 = nn.Linear(1024, num_classes) + self.dropout = nn.Dropout(p=dropout) + + def forward(self, x: Tensor) -> Tensor: + # aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14 + x = F.adaptive_avg_pool2d(x, (4, 4)) + # aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4 + x = self.conv(x) + # N x 128 x 4 x 4 + x = torch.flatten(x, 1) + # N x 2048 + x = F.relu(self.fc1(x), inplace=True) + # N x 1024 + x = self.dropout(x) + # N x 1024 + x = self.fc2(x) + # N x 1000 (num_classes) + + return x + + +class BasicConv2d(nn.Module): + def __init__(self, in_channels: int, out_channels: int, **kwargs: Any) -> None: + super().__init__() + self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) + self.bn = nn.BatchNorm2d(out_channels, eps=0.001) + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + return F.relu(x, inplace=True) + + +class GoogLeNet_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/googlenet-1378be20.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 6624904, + "min_size": (15, 15), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#googlenet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.778, + "acc@5": 89.530, + } + }, + "_ops": 1.498, + "_file_size": 49.731, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", GoogLeNet_Weights.IMAGENET1K_V1)) +def googlenet(*, weights: Optional[GoogLeNet_Weights] = None, progress: bool = True, **kwargs: Any) -> GoogLeNet: + """GoogLeNet (Inception v1) model architecture from + `Going Deeper with Convolutions `_. + + Args: + weights (:class:`~torchvision.models.GoogLeNet_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.GoogLeNet_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.GoogLeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.GoogLeNet_Weights + :members: + """ + weights = GoogLeNet_Weights.verify(weights) + + original_aux_logits = kwargs.get("aux_logits", False) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "init_weights", False) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = GoogLeNet(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not original_aux_logits: + model.aux_logits = False + model.aux1 = None # type: ignore[assignment] + model.aux2 = None # type: ignore[assignment] + else: + warnings.warn( + "auxiliary heads in the pretrained googlenet model are NOT pretrained, so make sure to train them" + ) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/inception.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/inception.py new file mode 100644 index 0000000000000000000000000000000000000000..7c36ec2a0ad721c0ccfc588fe389eb9c7e810fb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/inception.py @@ -0,0 +1,478 @@ +import warnings +from collections import namedtuple +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["Inception3", "InceptionOutputs", "_InceptionOutputs", "Inception_V3_Weights", "inception_v3"] + + +InceptionOutputs = namedtuple("InceptionOutputs", ["logits", "aux_logits"]) +InceptionOutputs.__annotations__ = {"logits": Tensor, "aux_logits": Optional[Tensor]} + +# Script annotations failed with _GoogleNetOutputs = namedtuple ... +# _InceptionOutputs set here for backwards compat +_InceptionOutputs = InceptionOutputs + + +class Inception3(nn.Module): + def __init__( + self, + num_classes: int = 1000, + aux_logits: bool = True, + transform_input: bool = False, + inception_blocks: Optional[list[Callable[..., nn.Module]]] = None, + init_weights: Optional[bool] = None, + dropout: float = 0.5, + ) -> None: + super().__init__() + _log_api_usage_once(self) + if inception_blocks is None: + inception_blocks = [BasicConv2d, InceptionA, InceptionB, InceptionC, InceptionD, InceptionE, InceptionAux] + if init_weights is None: + warnings.warn( + "The default weight initialization of inception_v3 will be changed in future releases of " + "torchvision. If you wish to keep the old behavior (which leads to long initialization times" + " due to scipy/scipy#11299), please set init_weights=True.", + FutureWarning, + ) + init_weights = True + if len(inception_blocks) != 7: + raise ValueError(f"length of inception_blocks should be 7 instead of {len(inception_blocks)}") + conv_block = inception_blocks[0] + inception_a = inception_blocks[1] + inception_b = inception_blocks[2] + inception_c = inception_blocks[3] + inception_d = inception_blocks[4] + inception_e = inception_blocks[5] + inception_aux = inception_blocks[6] + + self.aux_logits = aux_logits + self.transform_input = transform_input + self.Conv2d_1a_3x3 = conv_block(3, 32, kernel_size=3, stride=2) + self.Conv2d_2a_3x3 = conv_block(32, 32, kernel_size=3) + self.Conv2d_2b_3x3 = conv_block(32, 64, kernel_size=3, padding=1) + self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2) + self.Conv2d_3b_1x1 = conv_block(64, 80, kernel_size=1) + self.Conv2d_4a_3x3 = conv_block(80, 192, kernel_size=3) + self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=2) + self.Mixed_5b = inception_a(192, pool_features=32) + self.Mixed_5c = inception_a(256, pool_features=64) + self.Mixed_5d = inception_a(288, pool_features=64) + self.Mixed_6a = inception_b(288) + self.Mixed_6b = inception_c(768, channels_7x7=128) + self.Mixed_6c = inception_c(768, channels_7x7=160) + self.Mixed_6d = inception_c(768, channels_7x7=160) + self.Mixed_6e = inception_c(768, channels_7x7=192) + self.AuxLogits: Optional[nn.Module] = None + if aux_logits: + self.AuxLogits = inception_aux(768, num_classes) + self.Mixed_7a = inception_d(768) + self.Mixed_7b = inception_e(1280) + self.Mixed_7c = inception_e(2048) + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.dropout = nn.Dropout(p=dropout) + self.fc = nn.Linear(2048, num_classes) + if init_weights: + for m in self.modules(): + if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear): + stddev = float(m.stddev) if hasattr(m, "stddev") else 0.1 # type: ignore + torch.nn.init.trunc_normal_(m.weight, mean=0.0, std=stddev, a=-2, b=2) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def _transform_input(self, x: Tensor) -> Tensor: + if self.transform_input: + x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 + x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 + x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 + x = torch.cat((x_ch0, x_ch1, x_ch2), 1) + return x + + def _forward(self, x: Tensor) -> tuple[Tensor, Optional[Tensor]]: + # N x 3 x 299 x 299 + x = self.Conv2d_1a_3x3(x) + # N x 32 x 149 x 149 + x = self.Conv2d_2a_3x3(x) + # N x 32 x 147 x 147 + x = self.Conv2d_2b_3x3(x) + # N x 64 x 147 x 147 + x = self.maxpool1(x) + # N x 64 x 73 x 73 + x = self.Conv2d_3b_1x1(x) + # N x 80 x 73 x 73 + x = self.Conv2d_4a_3x3(x) + # N x 192 x 71 x 71 + x = self.maxpool2(x) + # N x 192 x 35 x 35 + x = self.Mixed_5b(x) + # N x 256 x 35 x 35 + x = self.Mixed_5c(x) + # N x 288 x 35 x 35 + x = self.Mixed_5d(x) + # N x 288 x 35 x 35 + x = self.Mixed_6a(x) + # N x 768 x 17 x 17 + x = self.Mixed_6b(x) + # N x 768 x 17 x 17 + x = self.Mixed_6c(x) + # N x 768 x 17 x 17 + x = self.Mixed_6d(x) + # N x 768 x 17 x 17 + x = self.Mixed_6e(x) + # N x 768 x 17 x 17 + aux: Optional[Tensor] = None + if self.AuxLogits is not None: + if self.training: + aux = self.AuxLogits(x) + # N x 768 x 17 x 17 + x = self.Mixed_7a(x) + # N x 1280 x 8 x 8 + x = self.Mixed_7b(x) + # N x 2048 x 8 x 8 + x = self.Mixed_7c(x) + # N x 2048 x 8 x 8 + # Adaptive average pooling + x = self.avgpool(x) + # N x 2048 x 1 x 1 + x = self.dropout(x) + # N x 2048 x 1 x 1 + x = torch.flatten(x, 1) + # N x 2048 + x = self.fc(x) + # N x 1000 (num_classes) + return x, aux + + @torch.jit.unused + def eager_outputs(self, x: Tensor, aux: Optional[Tensor]) -> InceptionOutputs: + if self.training and self.aux_logits: + return InceptionOutputs(x, aux) + else: + return x # type: ignore[return-value] + + def forward(self, x: Tensor) -> InceptionOutputs: + x = self._transform_input(x) + x, aux = self._forward(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted Inception3 always returns Inception3 Tuple") + return InceptionOutputs(x, aux) + else: + return self.eager_outputs(x, aux) + + +class InceptionA(nn.Module): + def __init__( + self, in_channels: int, pool_features: int, conv_block: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1x1 = conv_block(in_channels, 64, kernel_size=1) + + self.branch5x5_1 = conv_block(in_channels, 48, kernel_size=1) + self.branch5x5_2 = conv_block(48, 64, kernel_size=5, padding=2) + + self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1) + self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1) + self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, padding=1) + + self.branch_pool = conv_block(in_channels, pool_features, kernel_size=1) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch5x5 = self.branch5x5_1(x) + branch5x5 = self.branch5x5_2(branch5x5) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionB(nn.Module): + def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch3x3 = conv_block(in_channels, 384, kernel_size=3, stride=2) + + self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1) + self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1) + self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, stride=2) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch3x3 = self.branch3x3(x) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) + + branch_pool = F.max_pool2d(x, kernel_size=3, stride=2) + + outputs = [branch3x3, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionC(nn.Module): + def __init__( + self, in_channels: int, channels_7x7: int, conv_block: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1x1 = conv_block(in_channels, 192, kernel_size=1) + + c7 = channels_7x7 + self.branch7x7_1 = conv_block(in_channels, c7, kernel_size=1) + self.branch7x7_2 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3)) + self.branch7x7_3 = conv_block(c7, 192, kernel_size=(7, 1), padding=(3, 0)) + + self.branch7x7dbl_1 = conv_block(in_channels, c7, kernel_size=1) + self.branch7x7dbl_2 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0)) + self.branch7x7dbl_3 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3)) + self.branch7x7dbl_4 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0)) + self.branch7x7dbl_5 = conv_block(c7, 192, kernel_size=(1, 7), padding=(0, 3)) + + self.branch_pool = conv_block(in_channels, 192, kernel_size=1) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch7x7 = self.branch7x7_1(x) + branch7x7 = self.branch7x7_2(branch7x7) + branch7x7 = self.branch7x7_3(branch7x7) + + branch7x7dbl = self.branch7x7dbl_1(x) + branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionD(nn.Module): + def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch3x3_1 = conv_block(in_channels, 192, kernel_size=1) + self.branch3x3_2 = conv_block(192, 320, kernel_size=3, stride=2) + + self.branch7x7x3_1 = conv_block(in_channels, 192, kernel_size=1) + self.branch7x7x3_2 = conv_block(192, 192, kernel_size=(1, 7), padding=(0, 3)) + self.branch7x7x3_3 = conv_block(192, 192, kernel_size=(7, 1), padding=(3, 0)) + self.branch7x7x3_4 = conv_block(192, 192, kernel_size=3, stride=2) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch3x3 = self.branch3x3_1(x) + branch3x3 = self.branch3x3_2(branch3x3) + + branch7x7x3 = self.branch7x7x3_1(x) + branch7x7x3 = self.branch7x7x3_2(branch7x7x3) + branch7x7x3 = self.branch7x7x3_3(branch7x7x3) + branch7x7x3 = self.branch7x7x3_4(branch7x7x3) + + branch_pool = F.max_pool2d(x, kernel_size=3, stride=2) + outputs = [branch3x3, branch7x7x3, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionE(nn.Module): + def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1x1 = conv_block(in_channels, 320, kernel_size=1) + + self.branch3x3_1 = conv_block(in_channels, 384, kernel_size=1) + self.branch3x3_2a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1)) + self.branch3x3_2b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0)) + + self.branch3x3dbl_1 = conv_block(in_channels, 448, kernel_size=1) + self.branch3x3dbl_2 = conv_block(448, 384, kernel_size=3, padding=1) + self.branch3x3dbl_3a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1)) + self.branch3x3dbl_3b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0)) + + self.branch_pool = conv_block(in_channels, 192, kernel_size=1) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch3x3 = self.branch3x3_1(x) + branch3x3 = [ + self.branch3x3_2a(branch3x3), + self.branch3x3_2b(branch3x3), + ] + branch3x3 = torch.cat(branch3x3, 1) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = [ + self.branch3x3dbl_3a(branch3x3dbl), + self.branch3x3dbl_3b(branch3x3dbl), + ] + branch3x3dbl = torch.cat(branch3x3dbl, 1) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionAux(nn.Module): + def __init__( + self, in_channels: int, num_classes: int, conv_block: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.conv0 = conv_block(in_channels, 128, kernel_size=1) + self.conv1 = conv_block(128, 768, kernel_size=5) + self.conv1.stddev = 0.01 # type: ignore[assignment] + self.fc = nn.Linear(768, num_classes) + self.fc.stddev = 0.001 # type: ignore[assignment] + + def forward(self, x: Tensor) -> Tensor: + # N x 768 x 17 x 17 + x = F.avg_pool2d(x, kernel_size=5, stride=3) + # N x 768 x 5 x 5 + x = self.conv0(x) + # N x 128 x 5 x 5 + x = self.conv1(x) + # N x 768 x 1 x 1 + # Adaptive average pooling + x = F.adaptive_avg_pool2d(x, (1, 1)) + # N x 768 x 1 x 1 + x = torch.flatten(x, 1) + # N x 768 + x = self.fc(x) + # N x 1000 + return x + + +class BasicConv2d(nn.Module): + def __init__(self, in_channels: int, out_channels: int, **kwargs: Any) -> None: + super().__init__() + self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) + self.bn = nn.BatchNorm2d(out_channels, eps=0.001) + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + return F.relu(x, inplace=True) + + +class Inception_V3_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/inception_v3_google-0cc3c7bd.pth", + transforms=partial(ImageClassification, crop_size=299, resize_size=342), + meta={ + "num_params": 27161264, + "min_size": (75, 75), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#inception-v3", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.294, + "acc@5": 93.450, + } + }, + "_ops": 5.713, + "_file_size": 103.903, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Inception_V3_Weights.IMAGENET1K_V1)) +def inception_v3(*, weights: Optional[Inception_V3_Weights] = None, progress: bool = True, **kwargs: Any) -> Inception3: + """ + Inception v3 model architecture from + `Rethinking the Inception Architecture for Computer Vision `_. + + .. note:: + **Important**: In contrast to the other models the inception_v3 expects tensors with a size of + N x 3 x 299 x 299, so ensure your images are sized accordingly. + + Args: + weights (:class:`~torchvision.models.Inception_V3_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.Inception_V3_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.Inception3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Inception_V3_Weights + :members: + """ + weights = Inception_V3_Weights.verify(weights) + + original_aux_logits = kwargs.get("aux_logits", True) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "init_weights", False) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = Inception3(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not original_aux_logits: + model.aux_logits = False + model.AuxLogits = None + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/maxvit.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/maxvit.py new file mode 100644 index 0000000000000000000000000000000000000000..53cc53e5ed94019e56e97bfa74d5c32312dfe389 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/maxvit.py @@ -0,0 +1,834 @@ +import math +from collections import OrderedDict +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn, Tensor +from torchvision.models._api import register_model, Weights, WeightsEnum +from torchvision.models._meta import _IMAGENET_CATEGORIES +from torchvision.models._utils import _ovewrite_named_param, handle_legacy_interface +from torchvision.ops.misc import Conv2dNormActivation, SqueezeExcitation +from torchvision.ops.stochastic_depth import StochasticDepth +from torchvision.transforms._presets import ImageClassification, InterpolationMode +from torchvision.utils import _log_api_usage_once + +__all__ = [ + "MaxVit", + "MaxVit_T_Weights", + "maxvit_t", +] + + +def _get_conv_output_shape(input_size: tuple[int, int], kernel_size: int, stride: int, padding: int) -> tuple[int, int]: + return ( + (input_size[0] - kernel_size + 2 * padding) // stride + 1, + (input_size[1] - kernel_size + 2 * padding) // stride + 1, + ) + + +def _make_block_input_shapes(input_size: tuple[int, int], n_blocks: int) -> list[tuple[int, int]]: + """Util function to check that the input size is correct for a MaxVit configuration.""" + shapes = [] + block_input_shape = _get_conv_output_shape(input_size, 3, 2, 1) + for _ in range(n_blocks): + block_input_shape = _get_conv_output_shape(block_input_shape, 3, 2, 1) + shapes.append(block_input_shape) + return shapes + + +def _get_relative_position_index(height: int, width: int) -> torch.Tensor: + coords = torch.stack(torch.meshgrid([torch.arange(height), torch.arange(width)], indexing="ij")) + coords_flat = torch.flatten(coords, 1) + relative_coords = coords_flat[:, :, None] - coords_flat[:, None, :] + relative_coords = relative_coords.permute(1, 2, 0).contiguous() + relative_coords[:, :, 0] += height - 1 + relative_coords[:, :, 1] += width - 1 + relative_coords[:, :, 0] *= 2 * width - 1 + return relative_coords.sum(-1) + + +class MBConv(nn.Module): + """MBConv: Mobile Inverted Residual Bottleneck. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + expansion_ratio (float): Expansion ratio in the bottleneck. + squeeze_ratio (float): Squeeze ratio in the SE Layer. + stride (int): Stride of the depthwise convolution. + activation_layer (Callable[..., nn.Module]): Activation function. + norm_layer (Callable[..., nn.Module]): Normalization function. + p_stochastic_dropout (float): Probability of stochastic depth. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + expansion_ratio: float, + squeeze_ratio: float, + stride: int, + activation_layer: Callable[..., nn.Module], + norm_layer: Callable[..., nn.Module], + p_stochastic_dropout: float = 0.0, + ) -> None: + super().__init__() + + proj: Sequence[nn.Module] + self.proj: nn.Module + + should_proj = stride != 1 or in_channels != out_channels + if should_proj: + proj = [nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, bias=True)] + if stride == 2: + proj = [nn.AvgPool2d(kernel_size=3, stride=stride, padding=1)] + proj # type: ignore + self.proj = nn.Sequential(*proj) + else: + self.proj = nn.Identity() # type: ignore + + mid_channels = int(out_channels * expansion_ratio) + sqz_channels = int(out_channels * squeeze_ratio) + + if p_stochastic_dropout: + self.stochastic_depth = StochasticDepth(p_stochastic_dropout, mode="row") # type: ignore + else: + self.stochastic_depth = nn.Identity() # type: ignore + + _layers = OrderedDict() + _layers["pre_norm"] = norm_layer(in_channels) + _layers["conv_a"] = Conv2dNormActivation( + in_channels, + mid_channels, + kernel_size=1, + stride=1, + padding=0, + activation_layer=activation_layer, + norm_layer=norm_layer, + inplace=None, + ) + _layers["conv_b"] = Conv2dNormActivation( + mid_channels, + mid_channels, + kernel_size=3, + stride=stride, + padding=1, + activation_layer=activation_layer, + norm_layer=norm_layer, + groups=mid_channels, + inplace=None, + ) + _layers["squeeze_excitation"] = SqueezeExcitation(mid_channels, sqz_channels, activation=nn.SiLU) + _layers["conv_c"] = nn.Conv2d(in_channels=mid_channels, out_channels=out_channels, kernel_size=1, bias=True) + + self.layers = nn.Sequential(_layers) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, C, H, W]. + Returns: + Tensor: Output tensor with expected layout of [B, C, H / stride, W / stride]. + """ + res = self.proj(x) + x = self.stochastic_depth(self.layers(x)) + return res + x + + +class RelativePositionalMultiHeadAttention(nn.Module): + """Relative Positional Multi-Head Attention. + + Args: + feat_dim (int): Number of input features. + head_dim (int): Number of features per head. + max_seq_len (int): Maximum sequence length. + """ + + def __init__( + self, + feat_dim: int, + head_dim: int, + max_seq_len: int, + ) -> None: + super().__init__() + + if feat_dim % head_dim != 0: + raise ValueError(f"feat_dim: {feat_dim} must be divisible by head_dim: {head_dim}") + + self.n_heads = feat_dim // head_dim + self.head_dim = head_dim + self.size = int(math.sqrt(max_seq_len)) + self.max_seq_len = max_seq_len + + self.to_qkv = nn.Linear(feat_dim, self.n_heads * self.head_dim * 3) + self.scale_factor = feat_dim**-0.5 + + self.merge = nn.Linear(self.head_dim * self.n_heads, feat_dim) + self.relative_position_bias_table = nn.parameter.Parameter( + torch.empty(((2 * self.size - 1) * (2 * self.size - 1), self.n_heads), dtype=torch.float32), + ) + + self.register_buffer("relative_position_index", _get_relative_position_index(self.size, self.size)) + # initialize with truncated normal the bias + torch.nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + def get_relative_positional_bias(self) -> torch.Tensor: + bias_index = self.relative_position_index.view(-1) # type: ignore + relative_bias = self.relative_position_bias_table[bias_index].view(self.max_seq_len, self.max_seq_len, -1) # type: ignore + relative_bias = relative_bias.permute(2, 0, 1).contiguous() + return relative_bias.unsqueeze(0) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, G, P, D]. + Returns: + Tensor: Output tensor with expected layout of [B, G, P, D]. + """ + B, G, P, D = x.shape + H, DH = self.n_heads, self.head_dim + + qkv = self.to_qkv(x) + q, k, v = torch.chunk(qkv, 3, dim=-1) + + q = q.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4) + k = k.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4) + v = v.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4) + + k = k * self.scale_factor + dot_prod = torch.einsum("B G H I D, B G H J D -> B G H I J", q, k) + pos_bias = self.get_relative_positional_bias() + + dot_prod = F.softmax(dot_prod + pos_bias, dim=-1) + + out = torch.einsum("B G H I J, B G H J D -> B G H I D", dot_prod, v) + out = out.permute(0, 1, 3, 2, 4).reshape(B, G, P, D) + + out = self.merge(out) + return out + + +class SwapAxes(nn.Module): + """Permute the axes of a tensor.""" + + def __init__(self, a: int, b: int) -> None: + super().__init__() + self.a = a + self.b = b + + def forward(self, x: torch.Tensor) -> torch.Tensor: + res = torch.swapaxes(x, self.a, self.b) + return res + + +class WindowPartition(nn.Module): + """ + Partition the input tensor into non-overlapping windows. + """ + + def __init__(self) -> None: + super().__init__() + + def forward(self, x: Tensor, p: int) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, C, H, W]. + p (int): Number of partitions. + Returns: + Tensor: Output tensor with expected layout of [B, H/P, W/P, P*P, C]. + """ + B, C, H, W = x.shape + P = p + # chunk up H and W dimensions + x = x.reshape(B, C, H // P, P, W // P, P) + x = x.permute(0, 2, 4, 3, 5, 1) + # colapse P * P dimension + x = x.reshape(B, (H // P) * (W // P), P * P, C) + return x + + +class WindowDepartition(nn.Module): + """ + Departition the input tensor of non-overlapping windows into a feature volume of layout [B, C, H, W]. + """ + + def __init__(self) -> None: + super().__init__() + + def forward(self, x: Tensor, p: int, h_partitions: int, w_partitions: int) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, (H/P * W/P), P*P, C]. + p (int): Number of partitions. + h_partitions (int): Number of vertical partitions. + w_partitions (int): Number of horizontal partitions. + Returns: + Tensor: Output tensor with expected layout of [B, C, H, W]. + """ + B, G, PP, C = x.shape + P = p + HP, WP = h_partitions, w_partitions + # split P * P dimension into 2 P tile dimensionsa + x = x.reshape(B, HP, WP, P, P, C) + # permute into B, C, HP, P, WP, P + x = x.permute(0, 5, 1, 3, 2, 4) + # reshape into B, C, H, W + x = x.reshape(B, C, HP * P, WP * P) + return x + + +class PartitionAttentionLayer(nn.Module): + """ + Layer for partitioning the input tensor into non-overlapping windows and applying attention to each window. + + Args: + in_channels (int): Number of input channels. + head_dim (int): Dimension of each attention head. + partition_size (int): Size of the partitions. + partition_type (str): Type of partitioning to use. Can be either "grid" or "window". + grid_size (Tuple[int, int]): Size of the grid to partition the input tensor into. + mlp_ratio (int): Ratio of the feature size expansion in the MLP layer. + activation_layer (Callable[..., nn.Module]): Activation function to use. + norm_layer (Callable[..., nn.Module]): Normalization function to use. + attention_dropout (float): Dropout probability for the attention layer. + mlp_dropout (float): Dropout probability for the MLP layer. + p_stochastic_dropout (float): Probability of dropping out a partition. + """ + + def __init__( + self, + in_channels: int, + head_dim: int, + # partitioning parameters + partition_size: int, + partition_type: str, + # grid size needs to be known at initialization time + # because we need to know hamy relative offsets there are in the grid + grid_size: tuple[int, int], + mlp_ratio: int, + activation_layer: Callable[..., nn.Module], + norm_layer: Callable[..., nn.Module], + attention_dropout: float, + mlp_dropout: float, + p_stochastic_dropout: float, + ) -> None: + super().__init__() + + self.n_heads = in_channels // head_dim + self.head_dim = head_dim + self.n_partitions = grid_size[0] // partition_size + self.partition_type = partition_type + self.grid_size = grid_size + + if partition_type not in ["grid", "window"]: + raise ValueError("partition_type must be either 'grid' or 'window'") + + if partition_type == "window": + self.p, self.g = partition_size, self.n_partitions + else: + self.p, self.g = self.n_partitions, partition_size + + self.partition_op = WindowPartition() + self.departition_op = WindowDepartition() + self.partition_swap = SwapAxes(-2, -3) if partition_type == "grid" else nn.Identity() + self.departition_swap = SwapAxes(-2, -3) if partition_type == "grid" else nn.Identity() + + self.attn_layer = nn.Sequential( + norm_layer(in_channels), + # it's always going to be partition_size ** 2 because + # of the axis swap in the case of grid partitioning + RelativePositionalMultiHeadAttention(in_channels, head_dim, partition_size**2), + nn.Dropout(attention_dropout), + ) + + # pre-normalization similar to transformer layers + self.mlp_layer = nn.Sequential( + nn.LayerNorm(in_channels), + nn.Linear(in_channels, in_channels * mlp_ratio), + activation_layer(), + nn.Linear(in_channels * mlp_ratio, in_channels), + nn.Dropout(mlp_dropout), + ) + + # layer scale factors + self.stochastic_dropout = StochasticDepth(p_stochastic_dropout, mode="row") + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, C, H, W]. + Returns: + Tensor: Output tensor with expected layout of [B, C, H, W]. + """ + + # Undefined behavior if H or W are not divisible by p + # https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L766 + gh, gw = self.grid_size[0] // self.p, self.grid_size[1] // self.p + torch._assert( + self.grid_size[0] % self.p == 0 and self.grid_size[1] % self.p == 0, + "Grid size must be divisible by partition size. Got grid size of {} and partition size of {}".format( + self.grid_size, self.p + ), + ) + + x = self.partition_op(x, self.p) + x = self.partition_swap(x) + x = x + self.stochastic_dropout(self.attn_layer(x)) + x = x + self.stochastic_dropout(self.mlp_layer(x)) + x = self.departition_swap(x) + x = self.departition_op(x, self.p, gh, gw) + + return x + + +class MaxVitLayer(nn.Module): + """ + MaxVit layer consisting of a MBConv layer followed by a PartitionAttentionLayer with `window` and a PartitionAttentionLayer with `grid`. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + expansion_ratio (float): Expansion ratio in the bottleneck. + squeeze_ratio (float): Squeeze ratio in the SE Layer. + stride (int): Stride of the depthwise convolution. + activation_layer (Callable[..., nn.Module]): Activation function. + norm_layer (Callable[..., nn.Module]): Normalization function. + head_dim (int): Dimension of the attention heads. + mlp_ratio (int): Ratio of the MLP layer. + mlp_dropout (float): Dropout probability for the MLP layer. + attention_dropout (float): Dropout probability for the attention layer. + p_stochastic_dropout (float): Probability of stochastic depth. + partition_size (int): Size of the partitions. + grid_size (Tuple[int, int]): Size of the input feature grid. + """ + + def __init__( + self, + # conv parameters + in_channels: int, + out_channels: int, + squeeze_ratio: float, + expansion_ratio: float, + stride: int, + # conv + transformer parameters + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + # transformer parameters + head_dim: int, + mlp_ratio: int, + mlp_dropout: float, + attention_dropout: float, + p_stochastic_dropout: float, + # partitioning parameters + partition_size: int, + grid_size: tuple[int, int], + ) -> None: + super().__init__() + + layers: OrderedDict = OrderedDict() + + # convolutional layer + layers["MBconv"] = MBConv( + in_channels=in_channels, + out_channels=out_channels, + expansion_ratio=expansion_ratio, + squeeze_ratio=squeeze_ratio, + stride=stride, + activation_layer=activation_layer, + norm_layer=norm_layer, + p_stochastic_dropout=p_stochastic_dropout, + ) + # attention layers, block -> grid + layers["window_attention"] = PartitionAttentionLayer( + in_channels=out_channels, + head_dim=head_dim, + partition_size=partition_size, + partition_type="window", + grid_size=grid_size, + mlp_ratio=mlp_ratio, + activation_layer=activation_layer, + norm_layer=nn.LayerNorm, + attention_dropout=attention_dropout, + mlp_dropout=mlp_dropout, + p_stochastic_dropout=p_stochastic_dropout, + ) + layers["grid_attention"] = PartitionAttentionLayer( + in_channels=out_channels, + head_dim=head_dim, + partition_size=partition_size, + partition_type="grid", + grid_size=grid_size, + mlp_ratio=mlp_ratio, + activation_layer=activation_layer, + norm_layer=nn.LayerNorm, + attention_dropout=attention_dropout, + mlp_dropout=mlp_dropout, + p_stochastic_dropout=p_stochastic_dropout, + ) + self.layers = nn.Sequential(layers) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor of shape (B, C, H, W). + Returns: + Tensor: Output tensor of shape (B, C, H, W). + """ + x = self.layers(x) + return x + + +class MaxVitBlock(nn.Module): + """ + A MaxVit block consisting of `n_layers` MaxVit layers. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + expansion_ratio (float): Expansion ratio in the bottleneck. + squeeze_ratio (float): Squeeze ratio in the SE Layer. + activation_layer (Callable[..., nn.Module]): Activation function. + norm_layer (Callable[..., nn.Module]): Normalization function. + head_dim (int): Dimension of the attention heads. + mlp_ratio (int): Ratio of the MLP layer. + mlp_dropout (float): Dropout probability for the MLP layer. + attention_dropout (float): Dropout probability for the attention layer. + p_stochastic_dropout (float): Probability of stochastic depth. + partition_size (int): Size of the partitions. + input_grid_size (Tuple[int, int]): Size of the input feature grid. + n_layers (int): Number of layers in the block. + p_stochastic (List[float]): List of probabilities for stochastic depth for each layer. + """ + + def __init__( + self, + # conv parameters + in_channels: int, + out_channels: int, + squeeze_ratio: float, + expansion_ratio: float, + # conv + transformer parameters + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + # transformer parameters + head_dim: int, + mlp_ratio: int, + mlp_dropout: float, + attention_dropout: float, + # partitioning parameters + partition_size: int, + input_grid_size: tuple[int, int], + # number of layers + n_layers: int, + p_stochastic: list[float], + ) -> None: + super().__init__() + if not len(p_stochastic) == n_layers: + raise ValueError(f"p_stochastic must have length n_layers={n_layers}, got p_stochastic={p_stochastic}.") + + self.layers = nn.ModuleList() + # account for the first stride of the first layer + self.grid_size = _get_conv_output_shape(input_grid_size, kernel_size=3, stride=2, padding=1) + + for idx, p in enumerate(p_stochastic): + stride = 2 if idx == 0 else 1 + self.layers += [ + MaxVitLayer( + in_channels=in_channels if idx == 0 else out_channels, + out_channels=out_channels, + squeeze_ratio=squeeze_ratio, + expansion_ratio=expansion_ratio, + stride=stride, + norm_layer=norm_layer, + activation_layer=activation_layer, + head_dim=head_dim, + mlp_ratio=mlp_ratio, + mlp_dropout=mlp_dropout, + attention_dropout=attention_dropout, + partition_size=partition_size, + grid_size=self.grid_size, + p_stochastic_dropout=p, + ), + ] + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor of shape (B, C, H, W). + Returns: + Tensor: Output tensor of shape (B, C, H, W). + """ + for layer in self.layers: + x = layer(x) + return x + + +class MaxVit(nn.Module): + """ + Implements MaxVit Transformer from the `MaxViT: Multi-Axis Vision Transformer `_ paper. + Args: + input_size (Tuple[int, int]): Size of the input image. + stem_channels (int): Number of channels in the stem. + partition_size (int): Size of the partitions. + block_channels (List[int]): Number of channels in each block. + block_layers (List[int]): Number of layers in each block. + stochastic_depth_prob (float): Probability of stochastic depth. Expands to a list of probabilities for each layer that scales linearly to the specified value. + squeeze_ratio (float): Squeeze ratio in the SE Layer. Default: 0.25. + expansion_ratio (float): Expansion ratio in the MBConv bottleneck. Default: 4. + norm_layer (Callable[..., nn.Module]): Normalization function. Default: None (setting to None will produce a `BatchNorm2d(eps=1e-3, momentum=0.01)`). + activation_layer (Callable[..., nn.Module]): Activation function Default: nn.GELU. + head_dim (int): Dimension of the attention heads. + mlp_ratio (int): Expansion ratio of the MLP layer. Default: 4. + mlp_dropout (float): Dropout probability for the MLP layer. Default: 0.0. + attention_dropout (float): Dropout probability for the attention layer. Default: 0.0. + num_classes (int): Number of classes. Default: 1000. + """ + + def __init__( + self, + # input size parameters + input_size: tuple[int, int], + # stem and task parameters + stem_channels: int, + # partitioning parameters + partition_size: int, + # block parameters + block_channels: list[int], + block_layers: list[int], + # attention head dimensions + head_dim: int, + stochastic_depth_prob: float, + # conv + transformer parameters + # norm_layer is applied only to the conv layers + # activation_layer is applied both to conv and transformer layers + norm_layer: Optional[Callable[..., nn.Module]] = None, + activation_layer: Callable[..., nn.Module] = nn.GELU, + # conv parameters + squeeze_ratio: float = 0.25, + expansion_ratio: float = 4, + # transformer parameters + mlp_ratio: int = 4, + mlp_dropout: float = 0.0, + attention_dropout: float = 0.0, + # task parameters + num_classes: int = 1000, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + input_channels = 3 + + # https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L1029-L1030 + # for the exact parameters used in batchnorm + if norm_layer is None: + norm_layer = partial(nn.BatchNorm2d, eps=1e-3, momentum=0.01) + + # Make sure input size will be divisible by the partition size in all blocks + # Undefined behavior if H or W are not divisible by p + # https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L766 + block_input_sizes = _make_block_input_shapes(input_size, len(block_channels)) + for idx, block_input_size in enumerate(block_input_sizes): + if block_input_size[0] % partition_size != 0 or block_input_size[1] % partition_size != 0: + raise ValueError( + f"Input size {block_input_size} of block {idx} is not divisible by partition size {partition_size}. " + f"Consider changing the partition size or the input size.\n" + f"Current configuration yields the following block input sizes: {block_input_sizes}." + ) + + # stem + self.stem = nn.Sequential( + Conv2dNormActivation( + input_channels, + stem_channels, + 3, + stride=2, + norm_layer=norm_layer, + activation_layer=activation_layer, + bias=False, + inplace=None, + ), + Conv2dNormActivation( + stem_channels, stem_channels, 3, stride=1, norm_layer=None, activation_layer=None, bias=True + ), + ) + + # account for stem stride + input_size = _get_conv_output_shape(input_size, kernel_size=3, stride=2, padding=1) + self.partition_size = partition_size + + # blocks + self.blocks = nn.ModuleList() + in_channels = [stem_channels] + block_channels[:-1] + out_channels = block_channels + + # precompute the stochastich depth probabilities from 0 to stochastic_depth_prob + # since we have N blocks with L layers, we will have N * L probabilities uniformly distributed + # over the range [0, stochastic_depth_prob] + p_stochastic = np.linspace(0, stochastic_depth_prob, sum(block_layers)).tolist() + + p_idx = 0 + for in_channel, out_channel, num_layers in zip(in_channels, out_channels, block_layers): + self.blocks.append( + MaxVitBlock( + in_channels=in_channel, + out_channels=out_channel, + squeeze_ratio=squeeze_ratio, + expansion_ratio=expansion_ratio, + norm_layer=norm_layer, + activation_layer=activation_layer, + head_dim=head_dim, + mlp_ratio=mlp_ratio, + mlp_dropout=mlp_dropout, + attention_dropout=attention_dropout, + partition_size=partition_size, + input_grid_size=input_size, + n_layers=num_layers, + p_stochastic=p_stochastic[p_idx : p_idx + num_layers], + ), + ) + input_size = self.blocks[-1].grid_size # type: ignore[assignment] + p_idx += num_layers + + # see https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L1137-L1158 + # for why there is Linear -> Tanh -> Linear + self.classifier = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + nn.Flatten(), + nn.LayerNorm(block_channels[-1]), + nn.Linear(block_channels[-1], block_channels[-1]), + nn.Tanh(), + nn.Linear(block_channels[-1], num_classes, bias=False), + ) + + self._init_weights() + + def forward(self, x: Tensor) -> Tensor: + x = self.stem(x) + for block in self.blocks: + x = block(x) + x = self.classifier(x) + return x + + def _init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + +def _maxvit( + # stem parameters + stem_channels: int, + # block parameters + block_channels: list[int], + block_layers: list[int], + stochastic_depth_prob: float, + # partitioning parameters + partition_size: int, + # transformer parameters + head_dim: int, + # Weights API + weights: Optional[WeightsEnum] = None, + progress: bool = False, + # kwargs, + **kwargs: Any, +) -> MaxVit: + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + assert weights.meta["min_size"][0] == weights.meta["min_size"][1] + _ovewrite_named_param(kwargs, "input_size", weights.meta["min_size"]) + + input_size = kwargs.pop("input_size", (224, 224)) + + model = MaxVit( + stem_channels=stem_channels, + block_channels=block_channels, + block_layers=block_layers, + stochastic_depth_prob=stochastic_depth_prob, + head_dim=head_dim, + partition_size=partition_size, + input_size=input_size, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +class MaxVit_T_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # URL empty until official release + url="https://download.pytorch.org/models/maxvit_t-bc5ab103.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + "categories": _IMAGENET_CATEGORIES, + "num_params": 30919624, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#maxvit", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.700, + "acc@5": 96.722, + } + }, + "_ops": 5.558, + "_file_size": 118.769, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe. + They were trained with a BatchNorm2D momentum of 0.99 instead of the more correct 0.01.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MaxVit_T_Weights.IMAGENET1K_V1)) +def maxvit_t(*, weights: Optional[MaxVit_T_Weights] = None, progress: bool = True, **kwargs: Any) -> MaxVit: + """ + Constructs a maxvit_t architecture from + `MaxViT: Multi-Axis Vision Transformer `_. + + Args: + weights (:class:`~torchvision.models.MaxVit_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MaxVit_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.maxvit.MaxVit`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MaxVit_T_Weights + :members: + """ + weights = MaxVit_T_Weights.verify(weights) + + return _maxvit( + stem_channels=64, + block_channels=[64, 128, 256, 512], + block_layers=[2, 2, 5, 2], + head_dim=32, + stochastic_depth_prob=0.2, + partition_size=7, + weights=weights, + progress=progress, + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mnasnet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mnasnet.py new file mode 100644 index 0000000000000000000000000000000000000000..0471b19a6d59618385df3e1ab0e9ecf65bb21dcf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mnasnet.py @@ -0,0 +1,434 @@ +import warnings +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "MNASNet", + "MNASNet0_5_Weights", + "MNASNet0_75_Weights", + "MNASNet1_0_Weights", + "MNASNet1_3_Weights", + "mnasnet0_5", + "mnasnet0_75", + "mnasnet1_0", + "mnasnet1_3", +] + + +# Paper suggests 0.9997 momentum, for TensorFlow. Equivalent PyTorch momentum is +# 1.0 - tensorflow. +_BN_MOMENTUM = 1 - 0.9997 + + +class _InvertedResidual(nn.Module): + def __init__( + self, in_ch: int, out_ch: int, kernel_size: int, stride: int, expansion_factor: int, bn_momentum: float = 0.1 + ) -> None: + super().__init__() + if stride not in [1, 2]: + raise ValueError(f"stride should be 1 or 2 instead of {stride}") + if kernel_size not in [3, 5]: + raise ValueError(f"kernel_size should be 3 or 5 instead of {kernel_size}") + mid_ch = in_ch * expansion_factor + self.apply_residual = in_ch == out_ch and stride == 1 + self.layers = nn.Sequential( + # Pointwise + nn.Conv2d(in_ch, mid_ch, 1, bias=False), + nn.BatchNorm2d(mid_ch, momentum=bn_momentum), + nn.ReLU(inplace=True), + # Depthwise + nn.Conv2d(mid_ch, mid_ch, kernel_size, padding=kernel_size // 2, stride=stride, groups=mid_ch, bias=False), + nn.BatchNorm2d(mid_ch, momentum=bn_momentum), + nn.ReLU(inplace=True), + # Linear pointwise. Note that there's no activation. + nn.Conv2d(mid_ch, out_ch, 1, bias=False), + nn.BatchNorm2d(out_ch, momentum=bn_momentum), + ) + + def forward(self, input: Tensor) -> Tensor: + if self.apply_residual: + return self.layers(input) + input + else: + return self.layers(input) + + +def _stack( + in_ch: int, out_ch: int, kernel_size: int, stride: int, exp_factor: int, repeats: int, bn_momentum: float +) -> nn.Sequential: + """Creates a stack of inverted residuals.""" + if repeats < 1: + raise ValueError(f"repeats should be >= 1, instead got {repeats}") + # First one has no skip, because feature map size changes. + first = _InvertedResidual(in_ch, out_ch, kernel_size, stride, exp_factor, bn_momentum=bn_momentum) + remaining = [] + for _ in range(1, repeats): + remaining.append(_InvertedResidual(out_ch, out_ch, kernel_size, 1, exp_factor, bn_momentum=bn_momentum)) + return nn.Sequential(first, *remaining) + + +def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float = 0.9) -> int: + """Asymmetric rounding to make `val` divisible by `divisor`. With default + bias, will round up, unless the number is no more than 10% greater than the + smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88.""" + if not 0.0 < round_up_bias < 1.0: + raise ValueError(f"round_up_bias should be greater than 0.0 and smaller than 1.0 instead of {round_up_bias}") + new_val = max(divisor, int(val + divisor / 2) // divisor * divisor) + return new_val if new_val >= round_up_bias * val else new_val + divisor + + +def _get_depths(alpha: float) -> list[int]: + """Scales tensor depths as in reference MobileNet code, prefers rounding up + rather than down.""" + depths = [32, 16, 24, 40, 80, 96, 192, 320] + return [_round_to_multiple_of(depth * alpha, 8) for depth in depths] + + +class MNASNet(torch.nn.Module): + """MNASNet, as described in https://arxiv.org/abs/1807.11626. This + implements the B1 variant of the model. + >>> model = MNASNet(1.0, num_classes=1000) + >>> x = torch.rand(1, 3, 224, 224) + >>> y = model(x) + >>> y.dim() + 2 + >>> y.nelement() + 1000 + """ + + # Version 2 adds depth scaling in the initial stages of the network. + _version = 2 + + def __init__(self, alpha: float, num_classes: int = 1000, dropout: float = 0.2) -> None: + super().__init__() + _log_api_usage_once(self) + if alpha <= 0.0: + raise ValueError(f"alpha should be greater than 0.0 instead of {alpha}") + self.alpha = alpha + self.num_classes = num_classes + depths = _get_depths(alpha) + layers = [ + # First layer: regular conv. + nn.Conv2d(3, depths[0], 3, padding=1, stride=2, bias=False), + nn.BatchNorm2d(depths[0], momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + # Depthwise separable, no skip. + nn.Conv2d(depths[0], depths[0], 3, padding=1, stride=1, groups=depths[0], bias=False), + nn.BatchNorm2d(depths[0], momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + nn.Conv2d(depths[0], depths[1], 1, padding=0, stride=1, bias=False), + nn.BatchNorm2d(depths[1], momentum=_BN_MOMENTUM), + # MNASNet blocks: stacks of inverted residuals. + _stack(depths[1], depths[2], 3, 2, 3, 3, _BN_MOMENTUM), + _stack(depths[2], depths[3], 5, 2, 3, 3, _BN_MOMENTUM), + _stack(depths[3], depths[4], 5, 2, 6, 3, _BN_MOMENTUM), + _stack(depths[4], depths[5], 3, 1, 6, 2, _BN_MOMENTUM), + _stack(depths[5], depths[6], 5, 2, 6, 4, _BN_MOMENTUM), + _stack(depths[6], depths[7], 3, 1, 6, 1, _BN_MOMENTUM), + # Final mapping to classifier input. + nn.Conv2d(depths[7], 1280, 1, padding=0, stride=1, bias=False), + nn.BatchNorm2d(1280, momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + ] + self.layers = nn.Sequential(*layers) + self.classifier = nn.Sequential(nn.Dropout(p=dropout, inplace=True), nn.Linear(1280, num_classes)) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.kaiming_uniform_(m.weight, mode="fan_out", nonlinearity="sigmoid") + nn.init.zeros_(m.bias) + + def forward(self, x: Tensor) -> Tensor: + x = self.layers(x) + # Equivalent to global avgpool and removing H and W dimensions. + x = x.mean([2, 3]) + return self.classifier(x) + + def _load_from_state_dict( + self, + state_dict: dict, + prefix: str, + local_metadata: dict, + strict: bool, + missing_keys: list[str], + unexpected_keys: list[str], + error_msgs: list[str], + ) -> None: + version = local_metadata.get("version", None) + if version not in [1, 2]: + raise ValueError(f"version should be set to 1 or 2 instead of {version}") + + if version == 1 and not self.alpha == 1.0: + # In the initial version of the model (v1), stem was fixed-size. + # All other layer configurations were the same. This will patch + # the model so that it's identical to v1. Model with alpha 1.0 is + # unaffected. + depths = _get_depths(self.alpha) + v1_stem = [ + nn.Conv2d(3, 32, 3, padding=1, stride=2, bias=False), + nn.BatchNorm2d(32, momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + nn.Conv2d(32, 32, 3, padding=1, stride=1, groups=32, bias=False), + nn.BatchNorm2d(32, momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + nn.Conv2d(32, 16, 1, padding=0, stride=1, bias=False), + nn.BatchNorm2d(16, momentum=_BN_MOMENTUM), + _stack(16, depths[2], 3, 2, 3, 3, _BN_MOMENTUM), + ] + for idx, layer in enumerate(v1_stem): + self.layers[idx] = layer + + # The model is now identical to v1, and must be saved as such. + self._version = 1 + warnings.warn( + "A new version of MNASNet model has been implemented. " + "Your checkpoint was saved using the previous version. " + "This checkpoint will load and work as before, but " + "you may want to upgrade by training a newer model or " + "transfer learning from an updated ImageNet checkpoint.", + UserWarning, + ) + + super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/1e100/mnasnet_trainer", +} + + +class MNASNet0_5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet0.5_top1_67.823-3ffadce67e.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2218512, + "_metrics": { + "ImageNet-1K": { + "acc@1": 67.734, + "acc@5": 87.490, + } + }, + "_ops": 0.104, + "_file_size": 8.591, + "_docs": """These weights reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class MNASNet0_75_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet0_75-7090bc5f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/6019", + "num_params": 3170208, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.180, + "acc@5": 90.496, + } + }, + "_ops": 0.215, + "_file_size": 12.303, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class MNASNet1_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet1.0_top1_73.512-f206786ef8.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 4383312, + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.456, + "acc@5": 91.510, + } + }, + "_ops": 0.314, + "_file_size": 16.915, + "_docs": """These weights reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class MNASNet1_3_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet1_3-a4c69d6f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/6019", + "num_params": 6282256, + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.506, + "acc@5": 93.522, + } + }, + "_ops": 0.526, + "_file_size": 24.246, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +def _mnasnet(alpha: float, weights: Optional[WeightsEnum], progress: bool, **kwargs: Any) -> MNASNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = MNASNet(alpha, **kwargs) + + if weights: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet0_5_Weights.IMAGENET1K_V1)) +def mnasnet0_5(*, weights: Optional[MNASNet0_5_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 0.5 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet0_5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet0_5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet0_5_Weights + :members: + """ + weights = MNASNet0_5_Weights.verify(weights) + + return _mnasnet(0.5, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet0_75_Weights.IMAGENET1K_V1)) +def mnasnet0_75(*, weights: Optional[MNASNet0_75_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 0.75 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet0_75_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet0_75_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet0_75_Weights + :members: + """ + weights = MNASNet0_75_Weights.verify(weights) + + return _mnasnet(0.75, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet1_0_Weights.IMAGENET1K_V1)) +def mnasnet1_0(*, weights: Optional[MNASNet1_0_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 1.0 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet1_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet1_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet1_0_Weights + :members: + """ + weights = MNASNet1_0_Weights.verify(weights) + + return _mnasnet(1.0, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet1_3_Weights.IMAGENET1K_V1)) +def mnasnet1_3(*, weights: Optional[MNASNet1_3_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 1.3 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet1_3_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet1_3_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet1_3_Weights + :members: + """ + weights = MNASNet1_3_Weights.verify(weights) + + return _mnasnet(1.3, weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenet.py new file mode 100644 index 0000000000000000000000000000000000000000..0a270d14d3a4ad9eda62b68c2c01e9fdb710ef38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenet.py @@ -0,0 +1,6 @@ +from .mobilenetv2 import * # noqa: F401, F403 +from .mobilenetv3 import * # noqa: F401, F403 +from .mobilenetv2 import __all__ as mv2_all +from .mobilenetv3 import __all__ as mv3_all + +__all__ = mv2_all + mv3_all diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenetv2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..97f62e398a3207f59b33ad8609590888364148af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenetv2.py @@ -0,0 +1,260 @@ +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["MobileNetV2", "MobileNet_V2_Weights", "mobilenet_v2"] + + +# necessary for backwards compatibility +class InvertedResidual(nn.Module): + def __init__( + self, inp: int, oup: int, stride: int, expand_ratio: int, norm_layer: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + self.stride = stride + if stride not in [1, 2]: + raise ValueError(f"stride should be 1 or 2 instead of {stride}") + + if norm_layer is None: + norm_layer = nn.BatchNorm2d + + hidden_dim = int(round(inp * expand_ratio)) + self.use_res_connect = self.stride == 1 and inp == oup + + layers: list[nn.Module] = [] + if expand_ratio != 1: + # pw + layers.append( + Conv2dNormActivation(inp, hidden_dim, kernel_size=1, norm_layer=norm_layer, activation_layer=nn.ReLU6) + ) + layers.extend( + [ + # dw + Conv2dNormActivation( + hidden_dim, + hidden_dim, + stride=stride, + groups=hidden_dim, + norm_layer=norm_layer, + activation_layer=nn.ReLU6, + ), + # pw-linear + nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), + norm_layer(oup), + ] + ) + self.conv = nn.Sequential(*layers) + self.out_channels = oup + self._is_cn = stride > 1 + + def forward(self, x: Tensor) -> Tensor: + if self.use_res_connect: + return x + self.conv(x) + else: + return self.conv(x) + + +class MobileNetV2(nn.Module): + def __init__( + self, + num_classes: int = 1000, + width_mult: float = 1.0, + inverted_residual_setting: Optional[list[list[int]]] = None, + round_nearest: int = 8, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + dropout: float = 0.2, + ) -> None: + """ + MobileNet V2 main class + + Args: + num_classes (int): Number of classes + width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount + inverted_residual_setting: Network structure + round_nearest (int): Round the number of channels in each layer to be a multiple of this number + Set to 1 to turn off rounding + block: Module specifying inverted residual building block for mobilenet + norm_layer: Module specifying the normalization layer to use + dropout (float): The droupout probability + + """ + super().__init__() + _log_api_usage_once(self) + + if block is None: + block = InvertedResidual + + if norm_layer is None: + norm_layer = nn.BatchNorm2d + + input_channel = 32 + last_channel = 1280 + + if inverted_residual_setting is None: + inverted_residual_setting = [ + # t, c, n, s + [1, 16, 1, 1], + [6, 24, 2, 2], + [6, 32, 3, 2], + [6, 64, 4, 2], + [6, 96, 3, 1], + [6, 160, 3, 2], + [6, 320, 1, 1], + ] + + # only check the first element, assuming user knows t,c,n,s are required + if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4: + raise ValueError( + f"inverted_residual_setting should be non-empty or a 4-element list, got {inverted_residual_setting}" + ) + + # building first layer + input_channel = _make_divisible(input_channel * width_mult, round_nearest) + self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest) + features: list[nn.Module] = [ + Conv2dNormActivation(3, input_channel, stride=2, norm_layer=norm_layer, activation_layer=nn.ReLU6) + ] + # building inverted residual blocks + for t, c, n, s in inverted_residual_setting: + output_channel = _make_divisible(c * width_mult, round_nearest) + for i in range(n): + stride = s if i == 0 else 1 + features.append(block(input_channel, output_channel, stride, expand_ratio=t, norm_layer=norm_layer)) + input_channel = output_channel + # building last several layers + features.append( + Conv2dNormActivation( + input_channel, self.last_channel, kernel_size=1, norm_layer=norm_layer, activation_layer=nn.ReLU6 + ) + ) + # make it nn.Sequential + self.features = nn.Sequential(*features) + + # building classifier + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), + nn.Linear(self.last_channel, num_classes), + ) + + # weight initialization + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + # This exists since TorchScript doesn't support inheritance, so the superclass method + # (this one) needs to have a name other than `forward` that can be accessed in a subclass + x = self.features(x) + # Cannot use "squeeze" as batch-size can be 1 + x = nn.functional.adaptive_avg_pool2d(x, (1, 1)) + x = torch.flatten(x, 1) + x = self.classifier(x) + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +_COMMON_META = { + "num_params": 3504872, + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + + +class MobileNet_V2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mobilenet_v2-b0353104.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.878, + "acc@5": 90.286, + } + }, + "_ops": 0.301, + "_file_size": 13.555, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/mobilenet_v2-7ebf99e0.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-reg-tuning", + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.154, + "acc@5": 90.822, + } + }, + "_ops": 0.301, + "_file_size": 13.598, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MobileNet_V2_Weights.IMAGENET1K_V1)) +def mobilenet_v2( + *, weights: Optional[MobileNet_V2_Weights] = None, progress: bool = True, **kwargs: Any +) -> MobileNetV2: + """MobileNetV2 architecture from the `MobileNetV2: Inverted Residuals and Linear + Bottlenecks `_ paper. + + Args: + weights (:class:`~torchvision.models.MobileNet_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MobileNet_V2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mobilenetv2.MobileNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MobileNet_V2_Weights + :members: + """ + weights = MobileNet_V2_Weights.verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = MobileNetV2(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenetv3.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenetv3.py new file mode 100644 index 0000000000000000000000000000000000000000..e6239d095ba2a0bb4d85a929540de95be4667d67 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/mobilenetv3.py @@ -0,0 +1,424 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation, SqueezeExcitation as SElayer +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "MobileNetV3", + "MobileNet_V3_Large_Weights", + "MobileNet_V3_Small_Weights", + "mobilenet_v3_large", + "mobilenet_v3_small", +] + + +class InvertedResidualConfig: + # Stores information listed at Tables 1 and 2 of the MobileNetV3 paper + def __init__( + self, + input_channels: int, + kernel: int, + expanded_channels: int, + out_channels: int, + use_se: bool, + activation: str, + stride: int, + dilation: int, + width_mult: float, + ): + self.input_channels = self.adjust_channels(input_channels, width_mult) + self.kernel = kernel + self.expanded_channels = self.adjust_channels(expanded_channels, width_mult) + self.out_channels = self.adjust_channels(out_channels, width_mult) + self.use_se = use_se + self.use_hs = activation == "HS" + self.stride = stride + self.dilation = dilation + + @staticmethod + def adjust_channels(channels: int, width_mult: float): + return _make_divisible(channels * width_mult, 8) + + +class InvertedResidual(nn.Module): + # Implemented as described at section 5 of MobileNetV3 paper + def __init__( + self, + cnf: InvertedResidualConfig, + norm_layer: Callable[..., nn.Module], + se_layer: Callable[..., nn.Module] = partial(SElayer, scale_activation=nn.Hardsigmoid), + ): + super().__init__() + if not (1 <= cnf.stride <= 2): + raise ValueError("illegal stride value") + + self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels + + layers: list[nn.Module] = [] + activation_layer = nn.Hardswish if cnf.use_hs else nn.ReLU + + # expand + if cnf.expanded_channels != cnf.input_channels: + layers.append( + Conv2dNormActivation( + cnf.input_channels, + cnf.expanded_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # depthwise + stride = 1 if cnf.dilation > 1 else cnf.stride + layers.append( + Conv2dNormActivation( + cnf.expanded_channels, + cnf.expanded_channels, + kernel_size=cnf.kernel, + stride=stride, + dilation=cnf.dilation, + groups=cnf.expanded_channels, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + if cnf.use_se: + squeeze_channels = _make_divisible(cnf.expanded_channels // 4, 8) + layers.append(se_layer(cnf.expanded_channels, squeeze_channels)) + + # project + layers.append( + Conv2dNormActivation( + cnf.expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None + ) + ) + + self.block = nn.Sequential(*layers) + self.out_channels = cnf.out_channels + self._is_cn = cnf.stride > 1 + + def forward(self, input: Tensor) -> Tensor: + result = self.block(input) + if self.use_res_connect: + result += input + return result + + +class MobileNetV3(nn.Module): + def __init__( + self, + inverted_residual_setting: list[InvertedResidualConfig], + last_channel: int, + num_classes: int = 1000, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + dropout: float = 0.2, + **kwargs: Any, + ) -> None: + """ + MobileNet V3 main class + + Args: + inverted_residual_setting (List[InvertedResidualConfig]): Network structure + last_channel (int): The number of channels on the penultimate layer + num_classes (int): Number of classes + block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet + norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use + dropout (float): The droupout probability + """ + super().__init__() + _log_api_usage_once(self) + + if not inverted_residual_setting: + raise ValueError("The inverted_residual_setting should not be empty") + elif not ( + isinstance(inverted_residual_setting, Sequence) + and all([isinstance(s, InvertedResidualConfig) for s in inverted_residual_setting]) + ): + raise TypeError("The inverted_residual_setting should be List[InvertedResidualConfig]") + + if block is None: + block = InvertedResidual + + if norm_layer is None: + norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.01) + + layers: list[nn.Module] = [] + + # building first layer + firstconv_output_channels = inverted_residual_setting[0].input_channels + layers.append( + Conv2dNormActivation( + 3, + firstconv_output_channels, + kernel_size=3, + stride=2, + norm_layer=norm_layer, + activation_layer=nn.Hardswish, + ) + ) + + # building inverted residual blocks + for cnf in inverted_residual_setting: + layers.append(block(cnf, norm_layer)) + + # building last several layers + lastconv_input_channels = inverted_residual_setting[-1].out_channels + lastconv_output_channels = 6 * lastconv_input_channels + layers.append( + Conv2dNormActivation( + lastconv_input_channels, + lastconv_output_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=nn.Hardswish, + ) + ) + + self.features = nn.Sequential(*layers) + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Sequential( + nn.Linear(lastconv_output_channels, last_channel), + nn.Hardswish(inplace=True), + nn.Dropout(p=dropout, inplace=True), + nn.Linear(last_channel, num_classes), + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + x = self.features(x) + + x = self.avgpool(x) + x = torch.flatten(x, 1) + + x = self.classifier(x) + + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _mobilenet_v3_conf( + arch: str, width_mult: float = 1.0, reduced_tail: bool = False, dilated: bool = False, **kwargs: Any +): + reduce_divider = 2 if reduced_tail else 1 + dilation = 2 if dilated else 1 + + bneck_conf = partial(InvertedResidualConfig, width_mult=width_mult) + adjust_channels = partial(InvertedResidualConfig.adjust_channels, width_mult=width_mult) + + if arch == "mobilenet_v3_large": + inverted_residual_setting = [ + bneck_conf(16, 3, 16, 16, False, "RE", 1, 1), + bneck_conf(16, 3, 64, 24, False, "RE", 2, 1), # C1 + bneck_conf(24, 3, 72, 24, False, "RE", 1, 1), + bneck_conf(24, 5, 72, 40, True, "RE", 2, 1), # C2 + bneck_conf(40, 5, 120, 40, True, "RE", 1, 1), + bneck_conf(40, 5, 120, 40, True, "RE", 1, 1), + bneck_conf(40, 3, 240, 80, False, "HS", 2, 1), # C3 + bneck_conf(80, 3, 200, 80, False, "HS", 1, 1), + bneck_conf(80, 3, 184, 80, False, "HS", 1, 1), + bneck_conf(80, 3, 184, 80, False, "HS", 1, 1), + bneck_conf(80, 3, 480, 112, True, "HS", 1, 1), + bneck_conf(112, 3, 672, 112, True, "HS", 1, 1), + bneck_conf(112, 5, 672, 160 // reduce_divider, True, "HS", 2, dilation), # C4 + bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation), + bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation), + ] + last_channel = adjust_channels(1280 // reduce_divider) # C5 + elif arch == "mobilenet_v3_small": + inverted_residual_setting = [ + bneck_conf(16, 3, 16, 16, True, "RE", 2, 1), # C1 + bneck_conf(16, 3, 72, 24, False, "RE", 2, 1), # C2 + bneck_conf(24, 3, 88, 24, False, "RE", 1, 1), + bneck_conf(24, 5, 96, 40, True, "HS", 2, 1), # C3 + bneck_conf(40, 5, 240, 40, True, "HS", 1, 1), + bneck_conf(40, 5, 240, 40, True, "HS", 1, 1), + bneck_conf(40, 5, 120, 48, True, "HS", 1, 1), + bneck_conf(48, 5, 144, 48, True, "HS", 1, 1), + bneck_conf(48, 5, 288, 96 // reduce_divider, True, "HS", 2, dilation), # C4 + bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation), + bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation), + ] + last_channel = adjust_channels(1024 // reduce_divider) # C5 + else: + raise ValueError(f"Unsupported model type {arch}") + + return inverted_residual_setting, last_channel + + +def _mobilenet_v3( + inverted_residual_setting: list[InvertedResidualConfig], + last_channel: int, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> MobileNetV3: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = MobileNetV3(inverted_residual_setting, last_channel, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + + +class MobileNet_V3_Large_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 5483032, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small", + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.042, + "acc@5": 91.340, + } + }, + "_ops": 0.217, + "_file_size": 21.114, + "_docs": """These weights were trained from scratch by using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/mobilenet_v3_large-5c1a4163.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 5483032, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-reg-tuning", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.274, + "acc@5": 92.566, + } + }, + "_ops": 0.217, + "_file_size": 21.107, + "_docs": """ + These weights improve marginally upon the results of the original paper by using a modified version of + TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class MobileNet_V3_Small_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2542856, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small", + "_metrics": { + "ImageNet-1K": { + "acc@1": 67.668, + "acc@5": 87.402, + } + }, + "_ops": 0.057, + "_file_size": 9.829, + "_docs": """ + These weights improve upon the results of the original paper by using a simple training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MobileNet_V3_Large_Weights.IMAGENET1K_V1)) +def mobilenet_v3_large( + *, weights: Optional[MobileNet_V3_Large_Weights] = None, progress: bool = True, **kwargs: Any +) -> MobileNetV3: + """ + Constructs a large MobileNetV3 architecture from + `Searching for MobileNetV3 `__. + + Args: + weights (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mobilenet.MobileNetV3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights + :members: + """ + weights = MobileNet_V3_Large_Weights.verify(weights) + + inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_large", **kwargs) + return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MobileNet_V3_Small_Weights.IMAGENET1K_V1)) +def mobilenet_v3_small( + *, weights: Optional[MobileNet_V3_Small_Weights] = None, progress: bool = True, **kwargs: Any +) -> MobileNetV3: + """ + Constructs a small MobileNetV3 architecture from + `Searching for MobileNetV3 `__. + + Args: + weights (:class:`~torchvision.models.MobileNet_V3_Small_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MobileNet_V3_Small_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mobilenet.MobileNetV3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MobileNet_V3_Small_Weights + :members: + """ + weights = MobileNet_V3_Small_Weights.verify(weights) + + inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_small", **kwargs) + return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89d2302f825ff0dbe25d02f6dc7c84d3c0790ad0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/__init__.py @@ -0,0 +1 @@ +from .raft import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa2454a27315d6e560dccb6ea2ce6083da03e256 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/_utils.py @@ -0,0 +1,48 @@ +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import Tensor + + +def grid_sample(img: Tensor, absolute_grid: Tensor, mode: str = "bilinear", align_corners: Optional[bool] = None): + """Same as torch's grid_sample, with absolute pixel coordinates instead of normalized coordinates.""" + h, w = img.shape[-2:] + + xgrid, ygrid = absolute_grid.split([1, 1], dim=-1) + xgrid = 2 * xgrid / (w - 1) - 1 + # Adding condition if h > 1 to enable this function be reused in raft-stereo + if h > 1: + ygrid = 2 * ygrid / (h - 1) - 1 + normalized_grid = torch.cat([xgrid, ygrid], dim=-1) + + return F.grid_sample(img, normalized_grid, mode=mode, align_corners=align_corners) + + +def make_coords_grid(batch_size: int, h: int, w: int, device: str = "cpu"): + device = torch.device(device) + coords = torch.meshgrid(torch.arange(h, device=device), torch.arange(w, device=device), indexing="ij") + coords = torch.stack(coords[::-1], dim=0).float() + return coords[None].repeat(batch_size, 1, 1, 1) + + +def upsample_flow(flow, up_mask: Optional[Tensor] = None, factor: int = 8): + """Upsample flow by the input factor (default 8). + + If up_mask is None we just interpolate. + If up_mask is specified, we upsample using a convex combination of its weights. See paper page 8 and appendix B. + Note that in appendix B the picture assumes a downsample factor of 4 instead of 8. + """ + batch_size, num_channels, h, w = flow.shape + new_h, new_w = h * factor, w * factor + + if up_mask is None: + return factor * F.interpolate(flow, size=(new_h, new_w), mode="bilinear", align_corners=True) + + up_mask = up_mask.view(batch_size, 1, 9, factor, factor, h, w) + up_mask = torch.softmax(up_mask, dim=2) # "convex" == weights sum to 1 + + upsampled_flow = F.unfold(factor * flow, kernel_size=3, padding=1).view(batch_size, num_channels, 9, 1, 1, h, w) + upsampled_flow = torch.sum(up_mask * upsampled_flow, dim=2) + + return upsampled_flow.permute(0, 1, 4, 2, 5, 3).reshape(batch_size, num_channels, new_h, new_w) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/raft.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/raft.py new file mode 100644 index 0000000000000000000000000000000000000000..644adc2dc5c67c3517b697e2c0a3f0e273ea7277 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/optical_flow/raft.py @@ -0,0 +1,947 @@ +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torch.nn.modules.batchnorm import BatchNorm2d +from torch.nn.modules.instancenorm import InstanceNorm2d +from torchvision.ops import Conv2dNormActivation + +from ...transforms._presets import OpticalFlow +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._utils import handle_legacy_interface +from ._utils import grid_sample, make_coords_grid, upsample_flow + + +__all__ = ( + "RAFT", + "raft_large", + "raft_small", + "Raft_Large_Weights", + "Raft_Small_Weights", +) + + +class ResidualBlock(nn.Module): + """Slightly modified Residual block with extra relu and biases.""" + + def __init__(self, in_channels, out_channels, *, norm_layer, stride=1, always_project: bool = False): + super().__init__() + + # Note regarding bias=True: + # Usually we can pass bias=False in conv layers followed by a norm layer. + # But in the RAFT training reference, the BatchNorm2d layers are only activated for the first dataset, + # and frozen for the rest of the training process (i.e. set as eval()). The bias term is thus still useful + # for the rest of the datasets. Technically, we could remove the bias for other norm layers like Instance norm + # because these aren't frozen, but we don't bother (also, we wouldn't be able to load the original weights). + self.convnormrelu1 = Conv2dNormActivation( + in_channels, out_channels, norm_layer=norm_layer, kernel_size=3, stride=stride, bias=True + ) + self.convnormrelu2 = Conv2dNormActivation( + out_channels, out_channels, norm_layer=norm_layer, kernel_size=3, bias=True + ) + + # make mypy happy + self.downsample: nn.Module + + if stride == 1 and not always_project: + self.downsample = nn.Identity() + else: + self.downsample = Conv2dNormActivation( + in_channels, + out_channels, + norm_layer=norm_layer, + kernel_size=1, + stride=stride, + bias=True, + activation_layer=None, + ) + + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + y = x + y = self.convnormrelu1(y) + y = self.convnormrelu2(y) + + x = self.downsample(x) + + return self.relu(x + y) + + +class BottleneckBlock(nn.Module): + """Slightly modified BottleNeck block (extra relu and biases)""" + + def __init__(self, in_channels, out_channels, *, norm_layer, stride=1): + super().__init__() + + # See note in ResidualBlock for the reason behind bias=True + self.convnormrelu1 = Conv2dNormActivation( + in_channels, out_channels // 4, norm_layer=norm_layer, kernel_size=1, bias=True + ) + self.convnormrelu2 = Conv2dNormActivation( + out_channels // 4, out_channels // 4, norm_layer=norm_layer, kernel_size=3, stride=stride, bias=True + ) + self.convnormrelu3 = Conv2dNormActivation( + out_channels // 4, out_channels, norm_layer=norm_layer, kernel_size=1, bias=True + ) + self.relu = nn.ReLU(inplace=True) + + if stride == 1: + self.downsample = nn.Identity() + else: + self.downsample = Conv2dNormActivation( + in_channels, + out_channels, + norm_layer=norm_layer, + kernel_size=1, + stride=stride, + bias=True, + activation_layer=None, + ) + + def forward(self, x): + y = x + y = self.convnormrelu1(y) + y = self.convnormrelu2(y) + y = self.convnormrelu3(y) + + x = self.downsample(x) + + return self.relu(x + y) + + +class FeatureEncoder(nn.Module): + """The feature encoder, used both as the actual feature encoder, and as the context encoder. + + It must downsample its input by 8. + """ + + def __init__( + self, *, block=ResidualBlock, layers=(64, 64, 96, 128, 256), strides=(2, 1, 2, 2), norm_layer=nn.BatchNorm2d + ): + super().__init__() + + if len(layers) != 5: + raise ValueError(f"The expected number of layers is 5, instead got {len(layers)}") + + # See note in ResidualBlock for the reason behind bias=True + self.convnormrelu = Conv2dNormActivation( + 3, layers[0], norm_layer=norm_layer, kernel_size=7, stride=strides[0], bias=True + ) + + self.layer1 = self._make_2_blocks(block, layers[0], layers[1], norm_layer=norm_layer, first_stride=strides[1]) + self.layer2 = self._make_2_blocks(block, layers[1], layers[2], norm_layer=norm_layer, first_stride=strides[2]) + self.layer3 = self._make_2_blocks(block, layers[2], layers[3], norm_layer=norm_layer, first_stride=strides[3]) + + self.conv = nn.Conv2d(layers[3], layers[4], kernel_size=1) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + num_downsamples = len(list(filter(lambda s: s == 2, strides))) + self.output_dim = layers[-1] + self.downsample_factor = 2**num_downsamples + + def _make_2_blocks(self, block, in_channels, out_channels, norm_layer, first_stride): + block1 = block(in_channels, out_channels, norm_layer=norm_layer, stride=first_stride) + block2 = block(out_channels, out_channels, norm_layer=norm_layer, stride=1) + return nn.Sequential(block1, block2) + + def forward(self, x): + x = self.convnormrelu(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + + x = self.conv(x) + + return x + + +class MotionEncoder(nn.Module): + """The motion encoder, part of the update block. + + Takes the current predicted flow and the correlation features as input and returns an encoded version of these. + """ + + def __init__(self, *, in_channels_corr, corr_layers=(256, 192), flow_layers=(128, 64), out_channels=128): + super().__init__() + + if len(flow_layers) != 2: + raise ValueError(f"The expected number of flow_layers is 2, instead got {len(flow_layers)}") + if len(corr_layers) not in (1, 2): + raise ValueError(f"The number of corr_layers should be 1 or 2, instead got {len(corr_layers)}") + + self.convcorr1 = Conv2dNormActivation(in_channels_corr, corr_layers[0], norm_layer=None, kernel_size=1) + if len(corr_layers) == 2: + self.convcorr2 = Conv2dNormActivation(corr_layers[0], corr_layers[1], norm_layer=None, kernel_size=3) + else: + self.convcorr2 = nn.Identity() + + self.convflow1 = Conv2dNormActivation(2, flow_layers[0], norm_layer=None, kernel_size=7) + self.convflow2 = Conv2dNormActivation(flow_layers[0], flow_layers[1], norm_layer=None, kernel_size=3) + + # out_channels - 2 because we cat the flow (2 channels) at the end + self.conv = Conv2dNormActivation( + corr_layers[-1] + flow_layers[-1], out_channels - 2, norm_layer=None, kernel_size=3 + ) + + self.out_channels = out_channels + + def forward(self, flow, corr_features): + corr = self.convcorr1(corr_features) + corr = self.convcorr2(corr) + + flow_orig = flow + flow = self.convflow1(flow) + flow = self.convflow2(flow) + + corr_flow = torch.cat([corr, flow], dim=1) + corr_flow = self.conv(corr_flow) + return torch.cat([corr_flow, flow_orig], dim=1) + + +class ConvGRU(nn.Module): + """Convolutional Gru unit.""" + + def __init__(self, *, input_size, hidden_size, kernel_size, padding): + super().__init__() + self.convz = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding) + self.convr = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding) + self.convq = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding) + + def forward(self, h, x): + hx = torch.cat([h, x], dim=1) + z = torch.sigmoid(self.convz(hx)) + r = torch.sigmoid(self.convr(hx)) + q = torch.tanh(self.convq(torch.cat([r * h, x], dim=1))) + h = (1 - z) * h + z * q + return h + + +def _pass_through_h(h, _): + # Declared here for torchscript + return h + + +class RecurrentBlock(nn.Module): + """Recurrent block, part of the update block. + + Takes the current hidden state and the concatenation of (motion encoder output, context) as input. + Returns an updated hidden state. + """ + + def __init__(self, *, input_size, hidden_size, kernel_size=((1, 5), (5, 1)), padding=((0, 2), (2, 0))): + super().__init__() + + if len(kernel_size) != len(padding): + raise ValueError( + f"kernel_size should have the same length as padding, instead got len(kernel_size) = {len(kernel_size)} and len(padding) = {len(padding)}" + ) + if len(kernel_size) not in (1, 2): + raise ValueError(f"kernel_size should either 1 or 2, instead got {len(kernel_size)}") + + self.convgru1 = ConvGRU( + input_size=input_size, hidden_size=hidden_size, kernel_size=kernel_size[0], padding=padding[0] + ) + if len(kernel_size) == 2: + self.convgru2 = ConvGRU( + input_size=input_size, hidden_size=hidden_size, kernel_size=kernel_size[1], padding=padding[1] + ) + else: + self.convgru2 = _pass_through_h + + self.hidden_size = hidden_size + + def forward(self, h, x): + h = self.convgru1(h, x) + h = self.convgru2(h, x) + return h + + +class FlowHead(nn.Module): + """Flow head, part of the update block. + + Takes the hidden state of the recurrent unit as input, and outputs the predicted "delta flow". + """ + + def __init__(self, *, in_channels, hidden_size): + super().__init__() + self.conv1 = nn.Conv2d(in_channels, hidden_size, 3, padding=1) + self.conv2 = nn.Conv2d(hidden_size, 2, 3, padding=1) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + return self.conv2(self.relu(self.conv1(x))) + + +class UpdateBlock(nn.Module): + """The update block which contains the motion encoder, the recurrent block, and the flow head. + + It must expose a ``hidden_state_size`` attribute which is the hidden state size of its recurrent block. + """ + + def __init__(self, *, motion_encoder, recurrent_block, flow_head): + super().__init__() + self.motion_encoder = motion_encoder + self.recurrent_block = recurrent_block + self.flow_head = flow_head + + self.hidden_state_size = recurrent_block.hidden_size + + def forward(self, hidden_state, context, corr_features, flow): + motion_features = self.motion_encoder(flow, corr_features) + x = torch.cat([context, motion_features], dim=1) + + hidden_state = self.recurrent_block(hidden_state, x) + delta_flow = self.flow_head(hidden_state) + return hidden_state, delta_flow + + +class MaskPredictor(nn.Module): + """Mask predictor to be used when upsampling the predicted flow. + + It takes the hidden state of the recurrent unit as input and outputs the mask. + This is not used in the raft-small model. + """ + + def __init__(self, *, in_channels, hidden_size, multiplier=0.25): + super().__init__() + self.convrelu = Conv2dNormActivation(in_channels, hidden_size, norm_layer=None, kernel_size=3) + # 8 * 8 * 9 because the predicted flow is downsampled by 8, from the downsampling of the initial FeatureEncoder, + # and we interpolate with all 9 surrounding neighbors. See paper and appendix B. + self.conv = nn.Conv2d(hidden_size, 8 * 8 * 9, 1, padding=0) + + # In the original code, they use a factor of 0.25 to "downweight the gradients" of that branch. + # See e.g. https://github.com/princeton-vl/RAFT/issues/119#issuecomment-953950419 + # or https://github.com/princeton-vl/RAFT/issues/24. + # It doesn't seem to affect epe significantly and can likely be set to 1. + self.multiplier = multiplier + + def forward(self, x): + x = self.convrelu(x) + x = self.conv(x) + return self.multiplier * x + + +class CorrBlock(nn.Module): + """The correlation block. + + Creates a correlation pyramid with ``num_levels`` levels from the outputs of the feature encoder, + and then indexes from this pyramid to create correlation features. + The "indexing" of a given centroid pixel x' is done by concatenating its surrounding neighbors that + are within a ``radius``, according to the infinity norm (see paper section 3.2). + Note: typo in the paper, it should be infinity norm, not 1-norm. + """ + + def __init__(self, *, num_levels: int = 4, radius: int = 4): + super().__init__() + self.num_levels = num_levels + self.radius = radius + + self.corr_pyramid: list[Tensor] = [torch.tensor(0)] # useless, but torchscript is otherwise confused :') + + # The neighborhood of a centroid pixel x' is {x' + delta, ||delta||_inf <= radius} + # so it's a square surrounding x', and its sides have a length of 2 * radius + 1 + # The paper claims that it's ||.||_1 instead of ||.||_inf but it's a typo: + # https://github.com/princeton-vl/RAFT/issues/122 + self.out_channels = num_levels * (2 * radius + 1) ** 2 + + def build_pyramid(self, fmap1, fmap2): + """Build the correlation pyramid from two feature maps. + + The correlation volume is first computed as the dot product of each pair (pixel_in_fmap1, pixel_in_fmap2) + The last 2 dimensions of the correlation volume are then pooled num_levels times at different resolutions + to build the correlation pyramid. + """ + + if fmap1.shape != fmap2.shape: + raise ValueError( + f"Input feature maps should have the same shape, instead got {fmap1.shape} (fmap1.shape) != {fmap2.shape} (fmap2.shape)" + ) + + # Explaining min_fmap_size below: the fmaps are down-sampled (num_levels - 1) times by a factor of 2. + # The last corr_volume most have at least 2 values (hence the 2* factor), otherwise grid_sample() would + # produce nans in its output. + min_fmap_size = 2 * (2 ** (self.num_levels - 1)) + if any(fmap_size < min_fmap_size for fmap_size in fmap1.shape[-2:]): + raise ValueError( + "Feature maps are too small to be down-sampled by the correlation pyramid. " + f"H and W of feature maps should be at least {min_fmap_size}; got: {fmap1.shape[-2:]}. " + "Remember that input images to the model are downsampled by 8, so that means their " + f"dimensions should be at least 8 * {min_fmap_size} = {8 * min_fmap_size}." + ) + + corr_volume = self._compute_corr_volume(fmap1, fmap2) + + batch_size, h, w, num_channels, _, _ = corr_volume.shape # _, _ = h, w + corr_volume = corr_volume.reshape(batch_size * h * w, num_channels, h, w) + self.corr_pyramid = [corr_volume] + for _ in range(self.num_levels - 1): + corr_volume = F.avg_pool2d(corr_volume, kernel_size=2, stride=2) + self.corr_pyramid.append(corr_volume) + + def index_pyramid(self, centroids_coords): + """Return correlation features by indexing from the pyramid.""" + neighborhood_side_len = 2 * self.radius + 1 # see note in __init__ about out_channels + di = torch.linspace(-self.radius, self.radius, neighborhood_side_len) + dj = torch.linspace(-self.radius, self.radius, neighborhood_side_len) + delta = torch.stack(torch.meshgrid(di, dj, indexing="ij"), dim=-1).to(centroids_coords.device) + delta = delta.view(1, neighborhood_side_len, neighborhood_side_len, 2) + + batch_size, _, h, w = centroids_coords.shape # _ = 2 + centroids_coords = centroids_coords.permute(0, 2, 3, 1).reshape(batch_size * h * w, 1, 1, 2) + + indexed_pyramid = [] + for corr_volume in self.corr_pyramid: + sampling_coords = centroids_coords + delta # end shape is (batch_size * h * w, side_len, side_len, 2) + indexed_corr_volume = grid_sample(corr_volume, sampling_coords, align_corners=True, mode="bilinear").view( + batch_size, h, w, -1 + ) + indexed_pyramid.append(indexed_corr_volume) + centroids_coords = centroids_coords / 2 + + corr_features = torch.cat(indexed_pyramid, dim=-1).permute(0, 3, 1, 2).contiguous() + + expected_output_shape = (batch_size, self.out_channels, h, w) + if corr_features.shape != expected_output_shape: + raise ValueError( + f"Output shape of index pyramid is incorrect. Should be {expected_output_shape}, got {corr_features.shape}" + ) + + return corr_features + + def _compute_corr_volume(self, fmap1, fmap2): + batch_size, num_channels, h, w = fmap1.shape + fmap1 = fmap1.view(batch_size, num_channels, h * w) + fmap2 = fmap2.view(batch_size, num_channels, h * w) + + corr = torch.matmul(fmap1.transpose(1, 2), fmap2) + corr = corr.view(batch_size, h, w, 1, h, w) + return corr / torch.sqrt(torch.tensor(num_channels)) + + +class RAFT(nn.Module): + def __init__(self, *, feature_encoder, context_encoder, corr_block, update_block, mask_predictor=None): + """RAFT model from + `RAFT: Recurrent All Pairs Field Transforms for Optical Flow `_. + + args: + feature_encoder (nn.Module): The feature encoder. It must downsample the input by 8. + Its input is the concatenation of ``image1`` and ``image2``. + context_encoder (nn.Module): The context encoder. It must downsample the input by 8. + Its input is ``image1``. As in the original implementation, its output will be split into 2 parts: + + - one part will be used as the actual "context", passed to the recurrent unit of the ``update_block`` + - one part will be used to initialize the hidden state of the recurrent unit of + the ``update_block`` + + These 2 parts are split according to the ``hidden_state_size`` of the ``update_block``, so the output + of the ``context_encoder`` must be strictly greater than ``hidden_state_size``. + + corr_block (nn.Module): The correlation block, which creates a correlation pyramid from the output of the + ``feature_encoder``, and then indexes from this pyramid to create correlation features. It must expose + 2 methods: + + - a ``build_pyramid`` method that takes ``feature_map_1`` and ``feature_map_2`` as input (these are the + output of the ``feature_encoder``). + - a ``index_pyramid`` method that takes the coordinates of the centroid pixels as input, and returns + the correlation features. See paper section 3.2. + + It must expose an ``out_channels`` attribute. + + update_block (nn.Module): The update block, which contains the motion encoder, the recurrent unit, and the + flow head. It takes as input the hidden state of its recurrent unit, the context, the correlation + features, and the current predicted flow. It outputs an updated hidden state, and the ``delta_flow`` + prediction (see paper appendix A). It must expose a ``hidden_state_size`` attribute. + mask_predictor (nn.Module, optional): Predicts the mask that will be used to upsample the predicted flow. + The output channel must be 8 * 8 * 9 - see paper section 3.3, and Appendix B. + If ``None`` (default), the flow is upsampled using interpolation. + """ + super().__init__() + _log_api_usage_once(self) + + self.feature_encoder = feature_encoder + self.context_encoder = context_encoder + self.corr_block = corr_block + self.update_block = update_block + + self.mask_predictor = mask_predictor + + if not hasattr(self.update_block, "hidden_state_size"): + raise ValueError("The update_block parameter should expose a 'hidden_state_size' attribute.") + + def forward(self, image1, image2, num_flow_updates: int = 12): + + batch_size, _, h, w = image1.shape + if (h, w) != image2.shape[-2:]: + raise ValueError(f"input images should have the same shape, instead got ({h}, {w}) != {image2.shape[-2:]}") + if not ((h % 8 == 0) and (w % 8 == 0)): + raise ValueError(f"input image H and W should be divisible by 8, instead got {h} (h) and {w} (w)") + + fmaps = self.feature_encoder(torch.cat([image1, image2], dim=0)) + fmap1, fmap2 = torch.chunk(fmaps, chunks=2, dim=0) + if fmap1.shape[-2:] != (h // 8, w // 8): + raise ValueError("The feature encoder should downsample H and W by 8") + + self.corr_block.build_pyramid(fmap1, fmap2) + + context_out = self.context_encoder(image1) + if context_out.shape[-2:] != (h // 8, w // 8): + raise ValueError("The context encoder should downsample H and W by 8") + + # As in the original paper, the actual output of the context encoder is split in 2 parts: + # - one part is used to initialize the hidden state of the recurent units of the update block + # - the rest is the "actual" context. + hidden_state_size = self.update_block.hidden_state_size + out_channels_context = context_out.shape[1] - hidden_state_size + if out_channels_context <= 0: + raise ValueError( + f"The context encoder outputs {context_out.shape[1]} channels, but it should have at strictly more than hidden_state={hidden_state_size} channels" + ) + hidden_state, context = torch.split(context_out, [hidden_state_size, out_channels_context], dim=1) + hidden_state = torch.tanh(hidden_state) + context = F.relu(context) + + coords0 = make_coords_grid(batch_size, h // 8, w // 8).to(fmap1.device) + coords1 = make_coords_grid(batch_size, h // 8, w // 8).to(fmap1.device) + + flow_predictions = [] + for _ in range(num_flow_updates): + coords1 = coords1.detach() # Don't backpropagate gradients through this branch, see paper + corr_features = self.corr_block.index_pyramid(centroids_coords=coords1) + + flow = coords1 - coords0 + hidden_state, delta_flow = self.update_block(hidden_state, context, corr_features, flow) + + coords1 = coords1 + delta_flow + + up_mask = None if self.mask_predictor is None else self.mask_predictor(hidden_state) + upsampled_flow = upsample_flow(flow=(coords1 - coords0), up_mask=up_mask) + flow_predictions.append(upsampled_flow) + + return flow_predictions + + +_COMMON_META = { + "min_size": (128, 128), +} + + +class Raft_Large_Weights(WeightsEnum): + """The metrics reported here are as follows. + + ``epe`` is the "end-point-error" and indicates how far (in pixels) the + predicted flow is from its true value. This is averaged over all pixels + of all images. ``per_image_epe`` is similar, but the average is different: + the epe is first computed on each image independently, and then averaged + over all images. This corresponds to "Fl-epe" (sometimes written "F1-epe") + in the original paper, and it's only used on Kitti. ``fl-all`` is also a + Kitti-specific metric, defined by the author of the dataset and used for the + Kitti leaderboard. It corresponds to the average of pixels whose epe is + either <3px, or <5% of flow's 2-norm. + """ + + C_T_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_large_C_T_V1-22a6c225.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 1.4411}, + "Sintel-Train-Finalpass": {"epe": 2.7894}, + "Kitti-Train": {"per_image_epe": 5.0172, "fl_all": 17.4506}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """These weights were ported from the original paper. They + are trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + + C_T_V2 = Weights( + url="https://download.pytorch.org/models/raft_large_C_T_V2-1bb1363a.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 1.3822}, + "Sintel-Train-Finalpass": {"epe": 2.7161}, + "Kitti-Train": {"per_image_epe": 4.5118, "fl_all": 16.0679}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """These weights were trained from scratch on + :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + + C_T_SKHT_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_V1-0b8c9e55.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Sintel-Test-Cleanpass": {"epe": 1.94}, + "Sintel-Test-Finalpass": {"epe": 3.18}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were ported from the original paper. They are + trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D` and fine-tuned on + Sintel. The Sintel fine-tuning step is a combination of + :class:`~torchvision.datasets.Sintel`, + :class:`~torchvision.datasets.KittiFlow`, + :class:`~torchvision.datasets.HD1K`, and + :class:`~torchvision.datasets.FlyingThings3D` (clean pass). + """, + }, + ) + + C_T_SKHT_V2 = Weights( + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_V2-ff5fadd5.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Sintel-Test-Cleanpass": {"epe": 1.819}, + "Sintel-Test-Finalpass": {"epe": 3.067}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were trained from scratch. They are + pre-trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D` and then + fine-tuned on Sintel. The Sintel fine-tuning step is a + combination of :class:`~torchvision.datasets.Sintel`, + :class:`~torchvision.datasets.KittiFlow`, + :class:`~torchvision.datasets.HD1K`, and + :class:`~torchvision.datasets.FlyingThings3D` (clean pass). + """, + }, + ) + + C_T_SKHT_K_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_K_V1-4a6a5039.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Kitti-Test": {"fl_all": 5.10}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were ported from the original paper. They are + pre-trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`, + fine-tuned on Sintel, and then fine-tuned on + :class:`~torchvision.datasets.KittiFlow`. The Sintel fine-tuning + step was described above. + """, + }, + ) + + C_T_SKHT_K_V2 = Weights( + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_K_V2-b5c70766.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Kitti-Test": {"fl_all": 5.19}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were trained from scratch. They are + pre-trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`, + fine-tuned on Sintel, and then fine-tuned on + :class:`~torchvision.datasets.KittiFlow`. The Sintel fine-tuning + step was described above. + """, + }, + ) + + DEFAULT = C_T_SKHT_V2 + + +class Raft_Small_Weights(WeightsEnum): + """The metrics reported here are as follows. + + ``epe`` is the "end-point-error" and indicates how far (in pixels) the + predicted flow is from its true value. This is averaged over all pixels + of all images. ``per_image_epe`` is similar, but the average is different: + the epe is first computed on each image independently, and then averaged + over all images. This corresponds to "Fl-epe" (sometimes written "F1-epe") + in the original paper, and it's only used on Kitti. ``fl-all`` is also a + Kitti-specific metric, defined by the author of the dataset and used for the + Kitti leaderboard. It corresponds to the average of pixels whose epe is + either <3px, or <5% of flow's 2-norm. + """ + + C_T_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_small_C_T_V1-ad48884c.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 990162, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 2.1231}, + "Sintel-Train-Finalpass": {"epe": 3.2790}, + "Kitti-Train": {"per_image_epe": 7.6557, "fl_all": 25.2801}, + }, + "_ops": 47.655, + "_file_size": 3.821, + "_docs": """These weights were ported from the original paper. They + are trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + C_T_V2 = Weights( + url="https://download.pytorch.org/models/raft_small_C_T_V2-01064c6d.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 990162, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 1.9901}, + "Sintel-Train-Finalpass": {"epe": 3.2831}, + "Kitti-Train": {"per_image_epe": 7.5978, "fl_all": 25.2369}, + }, + "_ops": 47.655, + "_file_size": 3.821, + "_docs": """These weights were trained from scratch on + :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + + DEFAULT = C_T_V2 + + +def _raft( + *, + weights=None, + progress=False, + # Feature encoder + feature_encoder_layers, + feature_encoder_block, + feature_encoder_norm_layer, + # Context encoder + context_encoder_layers, + context_encoder_block, + context_encoder_norm_layer, + # Correlation block + corr_block_num_levels, + corr_block_radius, + # Motion encoder + motion_encoder_corr_layers, + motion_encoder_flow_layers, + motion_encoder_out_channels, + # Recurrent block + recurrent_block_hidden_state_size, + recurrent_block_kernel_size, + recurrent_block_padding, + # Flow Head + flow_head_hidden_size, + # Mask predictor + use_mask_predictor, + **kwargs, +): + feature_encoder = kwargs.pop("feature_encoder", None) or FeatureEncoder( + block=feature_encoder_block, layers=feature_encoder_layers, norm_layer=feature_encoder_norm_layer + ) + context_encoder = kwargs.pop("context_encoder", None) or FeatureEncoder( + block=context_encoder_block, layers=context_encoder_layers, norm_layer=context_encoder_norm_layer + ) + + corr_block = kwargs.pop("corr_block", None) or CorrBlock(num_levels=corr_block_num_levels, radius=corr_block_radius) + + update_block = kwargs.pop("update_block", None) + if update_block is None: + motion_encoder = MotionEncoder( + in_channels_corr=corr_block.out_channels, + corr_layers=motion_encoder_corr_layers, + flow_layers=motion_encoder_flow_layers, + out_channels=motion_encoder_out_channels, + ) + + # See comments in forward pass of RAFT class about why we split the output of the context encoder + out_channels_context = context_encoder_layers[-1] - recurrent_block_hidden_state_size + recurrent_block = RecurrentBlock( + input_size=motion_encoder.out_channels + out_channels_context, + hidden_size=recurrent_block_hidden_state_size, + kernel_size=recurrent_block_kernel_size, + padding=recurrent_block_padding, + ) + + flow_head = FlowHead(in_channels=recurrent_block_hidden_state_size, hidden_size=flow_head_hidden_size) + + update_block = UpdateBlock(motion_encoder=motion_encoder, recurrent_block=recurrent_block, flow_head=flow_head) + + mask_predictor = kwargs.pop("mask_predictor", None) + if mask_predictor is None and use_mask_predictor: + mask_predictor = MaskPredictor( + in_channels=recurrent_block_hidden_state_size, + hidden_size=256, + multiplier=0.25, # See comment in MaskPredictor about this + ) + + model = RAFT( + feature_encoder=feature_encoder, + context_encoder=context_encoder, + corr_block=corr_block, + update_block=update_block, + mask_predictor=mask_predictor, + **kwargs, # not really needed, all params should be consumed by now + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Raft_Large_Weights.C_T_SKHT_V2)) +def raft_large(*, weights: Optional[Raft_Large_Weights] = None, progress=True, **kwargs) -> RAFT: + """RAFT model from + `RAFT: Recurrent All Pairs Field Transforms for Optical Flow `_. + + Please see the example below for a tutorial on how to use this model. + + Args: + weights(:class:`~torchvision.models.optical_flow.Raft_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.optical_flow.Raft_Large_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.optical_flow.RAFT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.optical_flow.Raft_Large_Weights + :members: + """ + + weights = Raft_Large_Weights.verify(weights) + + return _raft( + weights=weights, + progress=progress, + # Feature encoder + feature_encoder_layers=(64, 64, 96, 128, 256), + feature_encoder_block=ResidualBlock, + feature_encoder_norm_layer=InstanceNorm2d, + # Context encoder + context_encoder_layers=(64, 64, 96, 128, 256), + context_encoder_block=ResidualBlock, + context_encoder_norm_layer=BatchNorm2d, + # Correlation block + corr_block_num_levels=4, + corr_block_radius=4, + # Motion encoder + motion_encoder_corr_layers=(256, 192), + motion_encoder_flow_layers=(128, 64), + motion_encoder_out_channels=128, + # Recurrent block + recurrent_block_hidden_state_size=128, + recurrent_block_kernel_size=((1, 5), (5, 1)), + recurrent_block_padding=((0, 2), (2, 0)), + # Flow head + flow_head_hidden_size=256, + # Mask predictor + use_mask_predictor=True, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Raft_Small_Weights.C_T_V2)) +def raft_small(*, weights: Optional[Raft_Small_Weights] = None, progress=True, **kwargs) -> RAFT: + """RAFT "small" model from + `RAFT: Recurrent All Pairs Field Transforms for Optical Flow `__. + + Please see the example below for a tutorial on how to use this model. + + Args: + weights(:class:`~torchvision.models.optical_flow.Raft_Small_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.optical_flow.Raft_Small_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.optical_flow.RAFT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.optical_flow.Raft_Small_Weights + :members: + """ + weights = Raft_Small_Weights.verify(weights) + + return _raft( + weights=weights, + progress=progress, + # Feature encoder + feature_encoder_layers=(32, 32, 64, 96, 128), + feature_encoder_block=BottleneckBlock, + feature_encoder_norm_layer=InstanceNorm2d, + # Context encoder + context_encoder_layers=(32, 32, 64, 96, 160), + context_encoder_block=BottleneckBlock, + context_encoder_norm_layer=None, + # Correlation block + corr_block_num_levels=4, + corr_block_radius=3, + # Motion encoder + motion_encoder_corr_layers=(96,), + motion_encoder_flow_layers=(64, 32), + motion_encoder_out_channels=82, + # Recurrent block + recurrent_block_hidden_state_size=96, + recurrent_block_kernel_size=(3,), + recurrent_block_padding=(1,), + # Flow head + flow_head_hidden_size=128, + # Mask predictor + use_mask_predictor=False, + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da8bbba3567b0b9110429354d89b65ec679a2fd5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/__init__.py @@ -0,0 +1,5 @@ +from .googlenet import * +from .inception import * +from .mobilenet import * +from .resnet import * +from .shufflenetv2 import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/googlenet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/googlenet.py new file mode 100644 index 0000000000000000000000000000000000000000..49ec1a340dd70cf0a03f101e6b4efa6229c5431b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/googlenet.py @@ -0,0 +1,212 @@ +import warnings +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor +from torch.nn import functional as F + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..googlenet import BasicConv2d, GoogLeNet, GoogLeNet_Weights, GoogLeNetOutputs, Inception, InceptionAux +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableGoogLeNet", + "GoogLeNet_QuantizedWeights", + "googlenet", +] + + +class QuantizableBasicConv2d(BasicConv2d): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.relu = nn.ReLU() + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, ["conv", "bn", "relu"], is_qat, inplace=True) + + +class QuantizableInception(Inception): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.cat = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.cat.cat(outputs, 1) + + +class QuantizableInceptionAux(InceptionAux): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.relu = nn.ReLU() + + def forward(self, x: Tensor) -> Tensor: + # aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14 + x = F.adaptive_avg_pool2d(x, (4, 4)) + # aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4 + x = self.conv(x) + # N x 128 x 4 x 4 + x = torch.flatten(x, 1) + # N x 2048 + x = self.relu(self.fc1(x)) + # N x 1024 + x = self.dropout(x) + # N x 1024 + x = self.fc2(x) + # N x 1000 (num_classes) + + return x + + +class QuantizableGoogLeNet(GoogLeNet): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__( # type: ignore[misc] + *args, blocks=[QuantizableBasicConv2d, QuantizableInception, QuantizableInceptionAux], **kwargs + ) + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> GoogLeNetOutputs: + x = self._transform_input(x) + x = self.quant(x) + x, aux1, aux2 = self._forward(x) + x = self.dequant(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted QuantizableGoogleNet always returns GoogleNetOutputs Tuple") + return GoogLeNetOutputs(x, aux2, aux1) + else: + return self.eager_outputs(x, aux2, aux1) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in googlenet model + + Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. + Model is modified in place. Note that this operation does not change numerics + and the model after modification is in floating point + """ + + for m in self.modules(): + if type(m) is QuantizableBasicConv2d: + m.fuse_model(is_qat) + + +class GoogLeNet_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/googlenet_fbgemm-c81f6644.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 6624904, + "min_size": (15, 15), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "unquantized": GoogLeNet_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.826, + "acc@5": 89.404, + } + }, + "_ops": 1.498, + "_file_size": 12.618, + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_googlenet") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + GoogLeNet_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else GoogLeNet_Weights.IMAGENET1K_V1 + ), + ) +) +def googlenet( + *, + weights: Optional[Union[GoogLeNet_QuantizedWeights, GoogLeNet_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableGoogLeNet: + """GoogLeNet (Inception v1) model architecture from `Going Deeper with Convolutions `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.GoogLeNet_QuantizedWeights` or :class:`~torchvision.models.GoogLeNet_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.GoogLeNet_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableGoogLeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.GoogLeNet_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.GoogLeNet_Weights + :members: + :noindex: + """ + weights = (GoogLeNet_QuantizedWeights if quantize else GoogLeNet_Weights).verify(weights) + + original_aux_logits = kwargs.get("aux_logits", False) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "init_weights", False) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableGoogLeNet(**kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not original_aux_logits: + model.aux_logits = False + model.aux1 = None # type: ignore[assignment] + model.aux2 = None # type: ignore[assignment] + else: + warnings.warn( + "auxiliary heads in the pretrained googlenet model are NOT pretrained, so make sure to train them" + ) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/inception.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/inception.py new file mode 100644 index 0000000000000000000000000000000000000000..a6eb9370d0d6a178f63f76b2acf4266a6ac4556d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/inception.py @@ -0,0 +1,275 @@ +import warnings +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torchvision.models import inception as inception_module +from torchvision.models.inception import Inception_V3_Weights, InceptionOutputs + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableInception3", + "Inception_V3_QuantizedWeights", + "inception_v3", +] + + +class QuantizableBasicConv2d(inception_module.BasicConv2d): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.relu = nn.ReLU() + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, ["conv", "bn", "relu"], is_qat, inplace=True) + + +class QuantizableInceptionA(inception_module.InceptionA): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionB(inception_module.InceptionB): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionC(inception_module.InceptionC): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionD(inception_module.InceptionD): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionE(inception_module.InceptionE): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop1 = nn.quantized.FloatFunctional() + self.myop2 = nn.quantized.FloatFunctional() + self.myop3 = nn.quantized.FloatFunctional() + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch3x3 = self.branch3x3_1(x) + branch3x3 = [self.branch3x3_2a(branch3x3), self.branch3x3_2b(branch3x3)] + branch3x3 = self.myop1.cat(branch3x3, 1) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = [ + self.branch3x3dbl_3a(branch3x3dbl), + self.branch3x3dbl_3b(branch3x3dbl), + ] + branch3x3dbl = self.myop2.cat(branch3x3dbl, 1) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop3.cat(outputs, 1) + + +class QuantizableInceptionAux(inception_module.InceptionAux): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + + +class QuantizableInception3(inception_module.Inception3): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__( # type: ignore[misc] + *args, + inception_blocks=[ + QuantizableBasicConv2d, + QuantizableInceptionA, + QuantizableInceptionB, + QuantizableInceptionC, + QuantizableInceptionD, + QuantizableInceptionE, + QuantizableInceptionAux, + ], + **kwargs, + ) + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> InceptionOutputs: + x = self._transform_input(x) + x = self.quant(x) + x, aux = self._forward(x) + x = self.dequant(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted QuantizableInception3 always returns QuantizableInception3 Tuple") + return InceptionOutputs(x, aux) + else: + return self.eager_outputs(x, aux) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in inception model + + Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. + Model is modified in place. Note that this operation does not change numerics + and the model after modification is in floating point + """ + + for m in self.modules(): + if type(m) is QuantizableBasicConv2d: + m.fuse_model(is_qat) + + +class Inception_V3_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/inception_v3_google_fbgemm-a2837893.pth", + transforms=partial(ImageClassification, crop_size=299, resize_size=342), + meta={ + "num_params": 27161264, + "min_size": (75, 75), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "unquantized": Inception_V3_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.176, + "acc@5": 93.354, + } + }, + "_ops": 5.713, + "_file_size": 23.146, + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_inception_v3") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + Inception_V3_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else Inception_V3_Weights.IMAGENET1K_V1 + ), + ) +) +def inception_v3( + *, + weights: Optional[Union[Inception_V3_QuantizedWeights, Inception_V3_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableInception3: + r"""Inception v3 model architecture from + `Rethinking the Inception Architecture for Computer Vision `__. + + .. note:: + **Important**: In contrast to the other models the inception_v3 expects tensors with a size of + N x 3 x 299 x 299, so ensure your images are sized accordingly. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` or :class:`~torchvision.models.Inception_V3_Weights`, optional): The pretrained + weights for the model. See + :class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableInception3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.Inception_V3_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.Inception_V3_Weights + :members: + :noindex: + """ + weights = (Inception_V3_QuantizedWeights if quantize else Inception_V3_Weights).verify(weights) + + original_aux_logits = kwargs.get("aux_logits", False) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableInception3(**kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + if quantize and not original_aux_logits: + model.aux_logits = False + model.AuxLogits = None + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not quantize and not original_aux_logits: + model.aux_logits = False + model.AuxLogits = None + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenet.py new file mode 100644 index 0000000000000000000000000000000000000000..0a270d14d3a4ad9eda62b68c2c01e9fdb710ef38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenet.py @@ -0,0 +1,6 @@ +from .mobilenetv2 import * # noqa: F401, F403 +from .mobilenetv3 import * # noqa: F401, F403 +from .mobilenetv2 import __all__ as mv2_all +from .mobilenetv3 import __all__ as mv3_all + +__all__ = mv2_all + mv3_all diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenetv2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..d1cef2d94136eecae20cd33d9b1de7f34eece1bc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenetv2.py @@ -0,0 +1,156 @@ +from functools import partial +from typing import Any, Optional, Union + +from torch import nn, Tensor +from torch.ao.quantization import DeQuantStub, QuantStub +from torchvision.models.mobilenetv2 import InvertedResidual, MobileNet_V2_Weights, MobileNetV2 + +from ...ops.misc import Conv2dNormActivation +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableMobileNetV2", + "MobileNet_V2_QuantizedWeights", + "mobilenet_v2", +] + + +class QuantizableInvertedResidual(InvertedResidual): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + if self.use_res_connect: + return self.skip_add.add(x, self.conv(x)) + else: + return self.conv(x) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + for idx in range(len(self.conv)): + if type(self.conv[idx]) is nn.Conv2d: + _fuse_modules(self.conv, [str(idx), str(idx + 1)], is_qat, inplace=True) + + +class QuantizableMobileNetV2(MobileNetV2): + def __init__(self, *args: Any, **kwargs: Any) -> None: + """ + MobileNet V2 main class + + Args: + Inherits args from floating point MobileNetV2 + """ + super().__init__(*args, **kwargs) + self.quant = QuantStub() + self.dequant = DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + for m in self.modules(): + if type(m) is Conv2dNormActivation: + _fuse_modules(m, ["0", "1", "2"], is_qat, inplace=True) + if type(m) is QuantizableInvertedResidual: + m.fuse_model(is_qat) + + +class MobileNet_V2_QuantizedWeights(WeightsEnum): + IMAGENET1K_QNNPACK_V1 = Weights( + url="https://download.pytorch.org/models/quantized/mobilenet_v2_qnnpack_37f702c5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 3504872, + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "qnnpack", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#qat-mobilenetv2", + "unquantized": MobileNet_V2_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.658, + "acc@5": 90.150, + } + }, + "_ops": 0.301, + "_file_size": 3.423, + "_docs": """ + These weights were produced by doing Quantization Aware Training (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_QNNPACK_V1 + + +@register_model(name="quantized_mobilenet_v2") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + MobileNet_V2_QuantizedWeights.IMAGENET1K_QNNPACK_V1 + if kwargs.get("quantize", False) + else MobileNet_V2_Weights.IMAGENET1K_V1 + ), + ) +) +def mobilenet_v2( + *, + weights: Optional[Union[MobileNet_V2_QuantizedWeights, MobileNet_V2_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableMobileNetV2: + """ + Constructs a MobileNetV2 architecture from + `MobileNetV2: Inverted Residuals and Linear Bottlenecks + `_. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` or :class:`~torchvision.models.MobileNet_V2_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + quantize (bool, optional): If True, returns a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableMobileNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.quantization.MobileNet_V2_QuantizedWeights + :members: + .. autoclass:: torchvision.models.MobileNet_V2_Weights + :members: + :noindex: + """ + weights = (MobileNet_V2_QuantizedWeights if quantize else MobileNet_V2_Weights).verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "qnnpack") + + model = QuantizableMobileNetV2(block=QuantizableInvertedResidual, **kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenetv3.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenetv3.py new file mode 100644 index 0000000000000000000000000000000000000000..7431b07df85d930c411979691c865b160316bd7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/mobilenetv3.py @@ -0,0 +1,239 @@ +from functools import partial +from typing import Any, Optional, Union + +import torch +from torch import nn, Tensor +from torch.ao.quantization import DeQuantStub, QuantStub + +from ...ops.misc import Conv2dNormActivation, SqueezeExcitation +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..mobilenetv3 import ( + _mobilenet_v3_conf, + InvertedResidual, + InvertedResidualConfig, + MobileNet_V3_Large_Weights, + MobileNetV3, +) +from .utils import _fuse_modules, _replace_relu + + +__all__ = [ + "QuantizableMobileNetV3", + "MobileNet_V3_Large_QuantizedWeights", + "mobilenet_v3_large", +] + + +class QuantizableSqueezeExcitation(SqueezeExcitation): + _version = 2 + + def __init__(self, *args: Any, **kwargs: Any) -> None: + kwargs["scale_activation"] = nn.Hardsigmoid + super().__init__(*args, **kwargs) + self.skip_mul = nn.quantized.FloatFunctional() + + def forward(self, input: Tensor) -> Tensor: + return self.skip_mul.mul(self._scale(input), input) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, ["fc1", "activation"], is_qat, inplace=True) + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if hasattr(self, "qconfig") and (version is None or version < 2): + default_state_dict = { + "scale_activation.activation_post_process.scale": torch.tensor([1.0]), + "scale_activation.activation_post_process.activation_post_process.scale": torch.tensor([1.0]), + "scale_activation.activation_post_process.zero_point": torch.tensor([0], dtype=torch.int32), + "scale_activation.activation_post_process.activation_post_process.zero_point": torch.tensor( + [0], dtype=torch.int32 + ), + "scale_activation.activation_post_process.fake_quant_enabled": torch.tensor([1]), + "scale_activation.activation_post_process.observer_enabled": torch.tensor([1]), + } + for k, v in default_state_dict.items(): + full_key = prefix + k + if full_key not in state_dict: + state_dict[full_key] = v + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + +class QuantizableInvertedResidual(InvertedResidual): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, se_layer=QuantizableSqueezeExcitation, **kwargs) # type: ignore[misc] + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + if self.use_res_connect: + return self.skip_add.add(x, self.block(x)) + else: + return self.block(x) + + +class QuantizableMobileNetV3(MobileNetV3): + def __init__(self, *args: Any, **kwargs: Any) -> None: + """ + MobileNet V3 main class + + Args: + Inherits args from floating point MobileNetV3 + """ + super().__init__(*args, **kwargs) + self.quant = QuantStub() + self.dequant = DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + for m in self.modules(): + if type(m) is Conv2dNormActivation: + modules_to_fuse = ["0", "1"] + if len(m) == 3 and type(m[2]) is nn.ReLU: + modules_to_fuse.append("2") + _fuse_modules(m, modules_to_fuse, is_qat, inplace=True) + elif type(m) is QuantizableSqueezeExcitation: + m.fuse_model(is_qat) + + +def _mobilenet_v3_model( + inverted_residual_setting: list[InvertedResidualConfig], + last_channel: int, + weights: Optional[WeightsEnum], + progress: bool, + quantize: bool, + **kwargs: Any, +) -> QuantizableMobileNetV3: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "qnnpack") + + model = QuantizableMobileNetV3(inverted_residual_setting, last_channel, block=QuantizableInvertedResidual, **kwargs) + _replace_relu(model) + + if quantize: + # Instead of quantizing the model and then loading the quantized weights we take a different approach. + # We prepare the QAT model, load the QAT weights from training and then convert it. + # This is done to avoid extremely low accuracies observed on the specific model. This is rather a workaround + # for an unresolved bug on the eager quantization API detailed at: https://github.com/pytorch/vision/issues/5890 + model.fuse_model(is_qat=True) + model.qconfig = torch.ao.quantization.get_default_qat_qconfig(backend) + torch.ao.quantization.prepare_qat(model, inplace=True) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + if quantize: + torch.ao.quantization.convert(model, inplace=True) + model.eval() + + return model + + +class MobileNet_V3_Large_QuantizedWeights(WeightsEnum): + IMAGENET1K_QNNPACK_V1 = Weights( + url="https://download.pytorch.org/models/quantized/mobilenet_v3_large_qnnpack-5bcacf28.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 5483032, + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "qnnpack", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#qat-mobilenetv3", + "unquantized": MobileNet_V3_Large_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.004, + "acc@5": 90.858, + } + }, + "_ops": 0.217, + "_file_size": 21.554, + "_docs": """ + These weights were produced by doing Quantization Aware Training (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_QNNPACK_V1 + + +@register_model(name="quantized_mobilenet_v3_large") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + MobileNet_V3_Large_QuantizedWeights.IMAGENET1K_QNNPACK_V1 + if kwargs.get("quantize", False) + else MobileNet_V3_Large_Weights.IMAGENET1K_V1 + ), + ) +) +def mobilenet_v3_large( + *, + weights: Optional[Union[MobileNet_V3_Large_QuantizedWeights, MobileNet_V3_Large_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableMobileNetV3: + """ + MobileNetV3 (Large) model from + `Searching for MobileNetV3 `_. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights` or :class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights + :members: + .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights + :members: + :noindex: + """ + weights = (MobileNet_V3_Large_QuantizedWeights if quantize else MobileNet_V3_Large_Weights).verify(weights) + + inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_large", **kwargs) + return _mobilenet_v3_model(inverted_residual_setting, last_channel, weights, progress, quantize, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/resnet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4ba003b6a3cba1e3f2efd9c3f070d439b1f7dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/resnet.py @@ -0,0 +1,492 @@ +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor +from torchvision.models.resnet import ( + BasicBlock, + Bottleneck, + ResNet, + ResNet18_Weights, + ResNet50_Weights, + ResNeXt101_32X8D_Weights, + ResNeXt101_64X4D_Weights, +) + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableResNet", + "ResNet18_QuantizedWeights", + "ResNet50_QuantizedWeights", + "ResNeXt101_32X8D_QuantizedWeights", + "ResNeXt101_64X4D_QuantizedWeights", + "resnet18", + "resnet50", + "resnext101_32x8d", + "resnext101_64x4d", +] + + +class QuantizableBasicBlock(BasicBlock): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.add_relu = torch.nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out = self.add_relu.add_relu(out, identity) + + return out + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, [["conv1", "bn1", "relu"], ["conv2", "bn2"]], is_qat, inplace=True) + if self.downsample: + _fuse_modules(self.downsample, ["0", "1"], is_qat, inplace=True) + + +class QuantizableBottleneck(Bottleneck): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.skip_add_relu = nn.quantized.FloatFunctional() + self.relu1 = nn.ReLU(inplace=False) + self.relu2 = nn.ReLU(inplace=False) + + def forward(self, x: Tensor) -> Tensor: + identity = x + out = self.conv1(x) + out = self.bn1(out) + out = self.relu1(out) + out = self.conv2(out) + out = self.bn2(out) + out = self.relu2(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + identity = self.downsample(x) + out = self.skip_add_relu.add_relu(out, identity) + + return out + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules( + self, [["conv1", "bn1", "relu1"], ["conv2", "bn2", "relu2"], ["conv3", "bn3"]], is_qat, inplace=True + ) + if self.downsample: + _fuse_modules(self.downsample, ["0", "1"], is_qat, inplace=True) + + +class QuantizableResNet(ResNet): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + # Ensure scriptability + # super(QuantizableResNet,self).forward(x) + # is not scriptable + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in resnet models + + Fuse conv+bn+relu/ Conv+relu/conv+Bn modules to prepare for quantization. + Model is modified in place. Note that this operation does not change numerics + and the model after modification is in floating point + """ + _fuse_modules(self, ["conv1", "bn1", "relu"], is_qat, inplace=True) + for m in self.modules(): + if type(m) is QuantizableBottleneck or type(m) is QuantizableBasicBlock: + m.fuse_model(is_qat) + + +def _resnet( + block: type[Union[QuantizableBasicBlock, QuantizableBottleneck]], + layers: list[int], + weights: Optional[WeightsEnum], + progress: bool, + quantize: bool, + **kwargs: Any, +) -> QuantizableResNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableResNet(block, layers, **kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, +} + + +class ResNet18_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnet18_fbgemm_16fa66dd.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 11689512, + "unquantized": ResNet18_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.494, + "acc@5": 88.882, + } + }, + "_ops": 1.814, + "_file_size": 11.238, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ResNet50_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnet50_fbgemm_bf931d71.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 25557032, + "unquantized": ResNet50_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.920, + "acc@5": 92.814, + } + }, + "_ops": 4.089, + "_file_size": 24.759, + }, + ) + IMAGENET1K_FBGEMM_V2 = Weights( + url="https://download.pytorch.org/models/quantized/resnet50_fbgemm-23753f79.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 25557032, + "unquantized": ResNet50_Weights.IMAGENET1K_V2, + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.282, + "acc@5": 94.976, + } + }, + "_ops": 4.089, + "_file_size": 24.953, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V2 + + +class ResNeXt101_32X8D_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnext101_32x8_fbgemm_09835ccf.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 88791336, + "unquantized": ResNeXt101_32X8D_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.986, + "acc@5": 94.480, + } + }, + "_ops": 16.414, + "_file_size": 86.034, + }, + ) + IMAGENET1K_FBGEMM_V2 = Weights( + url="https://download.pytorch.org/models/quantized/resnext101_32x8_fbgemm-ee16d00c.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 88791336, + "unquantized": ResNeXt101_32X8D_Weights.IMAGENET1K_V2, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.574, + "acc@5": 96.132, + } + }, + "_ops": 16.414, + "_file_size": 86.645, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V2 + + +class ResNeXt101_64X4D_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnext101_64x4d_fbgemm-605a1cb3.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 83455272, + "recipe": "https://github.com/pytorch/vision/pull/5935", + "unquantized": ResNeXt101_64X4D_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.898, + "acc@5": 96.326, + } + }, + "_ops": 15.46, + "_file_size": 81.556, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_resnet18") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNet18_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNet18_Weights.IMAGENET1K_V1 + ), + ) +) +def resnet18( + *, + weights: Optional[Union[ResNet18_QuantizedWeights, ResNet18_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNet-18 model from + `Deep Residual Learning for Image Recognition `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNet18_QuantizedWeights` or :class:`~torchvision.models.ResNet18_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet18_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNet18_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNet18_Weights + :members: + :noindex: + """ + weights = (ResNet18_QuantizedWeights if quantize else ResNet18_Weights).verify(weights) + + return _resnet(QuantizableBasicBlock, [2, 2, 2, 2], weights, progress, quantize, **kwargs) + + +@register_model(name="quantized_resnet50") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNet50_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNet50_Weights.IMAGENET1K_V1 + ), + ) +) +def resnet50( + *, + weights: Optional[Union[ResNet50_QuantizedWeights, ResNet50_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNet-50 model from + `Deep Residual Learning for Image Recognition `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNet50_QuantizedWeights` or :class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet50_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNet50_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNet50_Weights + :members: + :noindex: + """ + weights = (ResNet50_QuantizedWeights if quantize else ResNet50_Weights).verify(weights) + + return _resnet(QuantizableBottleneck, [3, 4, 6, 3], weights, progress, quantize, **kwargs) + + +@register_model(name="quantized_resnext101_32x8d") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNeXt101_32X8D_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNeXt101_32X8D_Weights.IMAGENET1K_V1 + ), + ) +) +def resnext101_32x8d( + *, + weights: Optional[Union[ResNeXt101_32X8D_QuantizedWeights, ResNeXt101_32X8D_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNeXt-101 32x8d model from + `Aggregated Residual Transformation for Deep Neural Networks `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNeXt101_32X8D_QuantizedWeights` or :class:`~torchvision.models.ResNeXt101_32X8D_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet101_32X8D_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNeXt101_32X8D_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNeXt101_32X8D_Weights + :members: + :noindex: + """ + weights = (ResNeXt101_32X8D_QuantizedWeights if quantize else ResNeXt101_32X8D_Weights).verify(weights) + + _ovewrite_named_param(kwargs, "groups", 32) + _ovewrite_named_param(kwargs, "width_per_group", 8) + return _resnet(QuantizableBottleneck, [3, 4, 23, 3], weights, progress, quantize, **kwargs) + + +@register_model(name="quantized_resnext101_64x4d") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNeXt101_64X4D_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNeXt101_64X4D_Weights.IMAGENET1K_V1 + ), + ) +) +def resnext101_64x4d( + *, + weights: Optional[Union[ResNeXt101_64X4D_QuantizedWeights, ResNeXt101_64X4D_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNeXt-101 64x4d model from + `Aggregated Residual Transformation for Deep Neural Networks `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNeXt101_64X4D_QuantizedWeights` or :class:`~torchvision.models.ResNeXt101_64X4D_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet101_64X4D_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNeXt101_64X4D_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNeXt101_64X4D_Weights + :members: + :noindex: + """ + weights = (ResNeXt101_64X4D_QuantizedWeights if quantize else ResNeXt101_64X4D_Weights).verify(weights) + + _ovewrite_named_param(kwargs, "groups", 64) + _ovewrite_named_param(kwargs, "width_per_group", 4) + return _resnet(QuantizableBottleneck, [3, 4, 23, 3], weights, progress, quantize, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/shufflenetv2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/shufflenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a2eb8eb1b5ecfcac78729c53f2501688c17a01 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/shufflenetv2.py @@ -0,0 +1,435 @@ +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor +from torchvision.models import shufflenetv2 + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..shufflenetv2 import ( + ShuffleNet_V2_X0_5_Weights, + ShuffleNet_V2_X1_0_Weights, + ShuffleNet_V2_X1_5_Weights, + ShuffleNet_V2_X2_0_Weights, +) +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableShuffleNetV2", + "ShuffleNet_V2_X0_5_QuantizedWeights", + "ShuffleNet_V2_X1_0_QuantizedWeights", + "ShuffleNet_V2_X1_5_QuantizedWeights", + "ShuffleNet_V2_X2_0_QuantizedWeights", + "shufflenet_v2_x0_5", + "shufflenet_v2_x1_0", + "shufflenet_v2_x1_5", + "shufflenet_v2_x2_0", +] + + +class QuantizableInvertedResidual(shufflenetv2.InvertedResidual): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.cat = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + if self.stride == 1: + x1, x2 = x.chunk(2, dim=1) + out = self.cat.cat([x1, self.branch2(x2)], dim=1) + else: + out = self.cat.cat([self.branch1(x), self.branch2(x)], dim=1) + + out = shufflenetv2.channel_shuffle(out, 2) + + return out + + +class QuantizableShuffleNetV2(shufflenetv2.ShuffleNetV2): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, inverted_residual=QuantizableInvertedResidual, **kwargs) # type: ignore[misc] + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in shufflenetv2 model + + Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. + Model is modified in place. + + .. note:: + Note that this operation does not change numerics + and the model after modification is in floating point + """ + for name, m in self._modules.items(): + if name in ["conv1", "conv5"] and m is not None: + _fuse_modules(m, [["0", "1", "2"]], is_qat, inplace=True) + for m in self.modules(): + if type(m) is QuantizableInvertedResidual: + if len(m.branch1._modules.items()) > 0: + _fuse_modules(m.branch1, [["0", "1"], ["2", "3", "4"]], is_qat, inplace=True) + _fuse_modules( + m.branch2, + [["0", "1", "2"], ["3", "4"], ["5", "6", "7"]], + is_qat, + inplace=True, + ) + + +def _shufflenetv2( + stages_repeats: list[int], + stages_out_channels: list[int], + *, + weights: Optional[WeightsEnum], + progress: bool, + quantize: bool, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableShuffleNetV2(stages_repeats, stages_out_channels, **kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, +} + + +class ShuffleNet_V2_X0_5_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x0.5_fbgemm-00845098.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 1366792, + "unquantized": ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 57.972, + "acc@5": 79.780, + } + }, + "_ops": 0.04, + "_file_size": 1.501, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X1_0_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_fbgemm-1e62bb32.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2278604, + "unquantized": ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 68.360, + "acc@5": 87.582, + } + }, + "_ops": 0.145, + "_file_size": 2.334, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X1_5_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_5_fbgemm-d7401f05.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 3503624, + "unquantized": ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.052, + "acc@5": 90.700, + } + }, + "_ops": 0.296, + "_file_size": 3.672, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X2_0_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x2_0_fbgemm-5cac526c.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 7393996, + "unquantized": ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.354, + "acc@5": 92.488, + } + }, + "_ops": 0.583, + "_file_size": 7.467, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_shufflenet_v2_x0_5") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x0_5( + *, + weights: Optional[Union[ShuffleNet_V2_X0_5_QuantizedWeights, ShuffleNet_V2_X0_5_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 0.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X0_5_QuantizedWeights if quantize else ShuffleNet_V2_X0_5_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 48, 96, 192, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x1_0") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x1_0( + *, + weights: Optional[Union[ShuffleNet_V2_X1_0_QuantizedWeights, ShuffleNet_V2_X1_0_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 1.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X1_0_QuantizedWeights if quantize else ShuffleNet_V2_X1_0_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 116, 232, 464, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x1_5") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X1_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x1_5( + *, + weights: Optional[Union[ShuffleNet_V2_X1_5_QuantizedWeights, ShuffleNet_V2_X1_5_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 1.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X1_5_QuantizedWeights if quantize else ShuffleNet_V2_X1_5_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 176, 352, 704, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x2_0") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X2_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x2_0( + *, + weights: Optional[Union[ShuffleNet_V2_X2_0_QuantizedWeights, ShuffleNet_V2_X2_0_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 2.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X2_0_QuantizedWeights if quantize else ShuffleNet_V2_X2_0_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 244, 488, 976, 2048], weights=weights, progress=progress, quantize=quantize, **kwargs + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..71d50bb9b480afef6467a5ae18ed92b167861f99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/quantization/utils.py @@ -0,0 +1,51 @@ +from typing import Any, Optional, Union + +import torch +from torch import nn + + +def _replace_relu(module: nn.Module) -> None: + reassign = {} + for name, mod in module.named_children(): + _replace_relu(mod) + # Checking for explicit type instead of instance + # as we only want to replace modules of the exact type + # not inherited classes + if type(mod) is nn.ReLU or type(mod) is nn.ReLU6: + reassign[name] = nn.ReLU(inplace=False) + + for key, value in reassign.items(): + module._modules[key] = value + + +def quantize_model(model: nn.Module, backend: str) -> None: + _dummy_input_data = torch.rand(1, 3, 299, 299) + if backend not in torch.backends.quantized.supported_engines: + raise RuntimeError("Quantized backend not supported ") + torch.backends.quantized.engine = backend + model.eval() + # Make sure that weight qconfig matches that of the serialized models + if backend == "fbgemm": + model.qconfig = torch.ao.quantization.QConfig( # type: ignore[assignment] + activation=torch.ao.quantization.default_observer, + weight=torch.ao.quantization.default_per_channel_weight_observer, + ) + elif backend == "qnnpack": + model.qconfig = torch.ao.quantization.QConfig( # type: ignore[assignment] + activation=torch.ao.quantization.default_observer, weight=torch.ao.quantization.default_weight_observer + ) + + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + model.fuse_model() # type: ignore[operator] + torch.ao.quantization.prepare(model, inplace=True) + model(_dummy_input_data) + torch.ao.quantization.convert(model, inplace=True) + + +def _fuse_modules( + model: nn.Module, modules_to_fuse: Union[list[str], list[list[str]]], is_qat: Optional[bool], **kwargs: Any +): + if is_qat is None: + is_qat = model.training + method = torch.ao.quantization.fuse_modules_qat if is_qat else torch.ao.quantization.fuse_modules + return method(model, modules_to_fuse, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/regnet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/regnet.py new file mode 100644 index 0000000000000000000000000000000000000000..915ef22bf33f1b00d5544b7d04c31a24006ac9df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/regnet.py @@ -0,0 +1,1571 @@ +import math +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation, SqueezeExcitation +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "RegNet", + "RegNet_Y_400MF_Weights", + "RegNet_Y_800MF_Weights", + "RegNet_Y_1_6GF_Weights", + "RegNet_Y_3_2GF_Weights", + "RegNet_Y_8GF_Weights", + "RegNet_Y_16GF_Weights", + "RegNet_Y_32GF_Weights", + "RegNet_Y_128GF_Weights", + "RegNet_X_400MF_Weights", + "RegNet_X_800MF_Weights", + "RegNet_X_1_6GF_Weights", + "RegNet_X_3_2GF_Weights", + "RegNet_X_8GF_Weights", + "RegNet_X_16GF_Weights", + "RegNet_X_32GF_Weights", + "regnet_y_400mf", + "regnet_y_800mf", + "regnet_y_1_6gf", + "regnet_y_3_2gf", + "regnet_y_8gf", + "regnet_y_16gf", + "regnet_y_32gf", + "regnet_y_128gf", + "regnet_x_400mf", + "regnet_x_800mf", + "regnet_x_1_6gf", + "regnet_x_3_2gf", + "regnet_x_8gf", + "regnet_x_16gf", + "regnet_x_32gf", +] + + +class SimpleStemIN(Conv2dNormActivation): + """Simple stem for ImageNet: 3x3, BN, ReLU.""" + + def __init__( + self, + width_in: int, + width_out: int, + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + ) -> None: + super().__init__( + width_in, width_out, kernel_size=3, stride=2, norm_layer=norm_layer, activation_layer=activation_layer + ) + + +class BottleneckTransform(nn.Sequential): + """Bottleneck transformation: 1x1, 3x3 [+SE], 1x1.""" + + def __init__( + self, + width_in: int, + width_out: int, + stride: int, + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + group_width: int, + bottleneck_multiplier: float, + se_ratio: Optional[float], + ) -> None: + layers: OrderedDict[str, nn.Module] = OrderedDict() + w_b = int(round(width_out * bottleneck_multiplier)) + g = w_b // group_width + + layers["a"] = Conv2dNormActivation( + width_in, w_b, kernel_size=1, stride=1, norm_layer=norm_layer, activation_layer=activation_layer + ) + layers["b"] = Conv2dNormActivation( + w_b, w_b, kernel_size=3, stride=stride, groups=g, norm_layer=norm_layer, activation_layer=activation_layer + ) + + if se_ratio: + # The SE reduction ratio is defined with respect to the + # beginning of the block + width_se_out = int(round(se_ratio * width_in)) + layers["se"] = SqueezeExcitation( + input_channels=w_b, + squeeze_channels=width_se_out, + activation=activation_layer, + ) + + layers["c"] = Conv2dNormActivation( + w_b, width_out, kernel_size=1, stride=1, norm_layer=norm_layer, activation_layer=None + ) + super().__init__(layers) + + +class ResBottleneckBlock(nn.Module): + """Residual bottleneck block: x + F(x), F = bottleneck transform.""" + + def __init__( + self, + width_in: int, + width_out: int, + stride: int, + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + group_width: int = 1, + bottleneck_multiplier: float = 1.0, + se_ratio: Optional[float] = None, + ) -> None: + super().__init__() + + # Use skip connection with projection if shape changes + self.proj = None + should_proj = (width_in != width_out) or (stride != 1) + if should_proj: + self.proj = Conv2dNormActivation( + width_in, width_out, kernel_size=1, stride=stride, norm_layer=norm_layer, activation_layer=None + ) + self.f = BottleneckTransform( + width_in, + width_out, + stride, + norm_layer, + activation_layer, + group_width, + bottleneck_multiplier, + se_ratio, + ) + self.activation = activation_layer(inplace=True) + + def forward(self, x: Tensor) -> Tensor: + if self.proj is not None: + x = self.proj(x) + self.f(x) + else: + x = x + self.f(x) + return self.activation(x) + + +class AnyStage(nn.Sequential): + """AnyNet stage (sequence of blocks w/ the same output shape).""" + + def __init__( + self, + width_in: int, + width_out: int, + stride: int, + depth: int, + block_constructor: Callable[..., nn.Module], + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + group_width: int, + bottleneck_multiplier: float, + se_ratio: Optional[float] = None, + stage_index: int = 0, + ) -> None: + super().__init__() + + for i in range(depth): + block = block_constructor( + width_in if i == 0 else width_out, + width_out, + stride if i == 0 else 1, + norm_layer, + activation_layer, + group_width, + bottleneck_multiplier, + se_ratio, + ) + + self.add_module(f"block{stage_index}-{i}", block) + + +class BlockParams: + def __init__( + self, + depths: list[int], + widths: list[int], + group_widths: list[int], + bottleneck_multipliers: list[float], + strides: list[int], + se_ratio: Optional[float] = None, + ) -> None: + self.depths = depths + self.widths = widths + self.group_widths = group_widths + self.bottleneck_multipliers = bottleneck_multipliers + self.strides = strides + self.se_ratio = se_ratio + + @classmethod + def from_init_params( + cls, + depth: int, + w_0: int, + w_a: float, + w_m: float, + group_width: int, + bottleneck_multiplier: float = 1.0, + se_ratio: Optional[float] = None, + **kwargs: Any, + ) -> "BlockParams": + """ + Programmatically compute all the per-block settings, + given the RegNet parameters. + + The first step is to compute the quantized linear block parameters, + in log space. Key parameters are: + - `w_a` is the width progression slope + - `w_0` is the initial width + - `w_m` is the width stepping in the log space + + In other terms + `log(block_width) = log(w_0) + w_m * block_capacity`, + with `bock_capacity` ramping up following the w_0 and w_a params. + This block width is finally quantized to multiples of 8. + + The second step is to compute the parameters per stage, + taking into account the skip connection and the final 1x1 convolutions. + We use the fact that the output width is constant within a stage. + """ + + QUANT = 8 + STRIDE = 2 + + if w_a < 0 or w_0 <= 0 or w_m <= 1 or w_0 % 8 != 0: + raise ValueError("Invalid RegNet settings") + # Compute the block widths. Each stage has one unique block width + widths_cont = torch.arange(depth) * w_a + w_0 + block_capacity = torch.round(torch.log(widths_cont / w_0) / math.log(w_m)) + block_widths = (torch.round(torch.divide(w_0 * torch.pow(w_m, block_capacity), QUANT)) * QUANT).int().tolist() + num_stages = len(set(block_widths)) + + # Convert to per stage parameters + split_helper = zip( + block_widths + [0], + [0] + block_widths, + block_widths + [0], + [0] + block_widths, + ) + splits = [w != wp or r != rp for w, wp, r, rp in split_helper] + + stage_widths = [w for w, t in zip(block_widths, splits[:-1]) if t] + stage_depths = torch.diff(torch.tensor([d for d, t in enumerate(splits) if t])).int().tolist() + + strides = [STRIDE] * num_stages + bottleneck_multipliers = [bottleneck_multiplier] * num_stages + group_widths = [group_width] * num_stages + + # Adjust the compatibility of stage widths and group widths + stage_widths, group_widths = cls._adjust_widths_groups_compatibilty( + stage_widths, bottleneck_multipliers, group_widths + ) + + return cls( + depths=stage_depths, + widths=stage_widths, + group_widths=group_widths, + bottleneck_multipliers=bottleneck_multipliers, + strides=strides, + se_ratio=se_ratio, + ) + + def _get_expanded_params(self): + return zip(self.widths, self.strides, self.depths, self.group_widths, self.bottleneck_multipliers) + + @staticmethod + def _adjust_widths_groups_compatibilty( + stage_widths: list[int], bottleneck_ratios: list[float], group_widths: list[int] + ) -> tuple[list[int], list[int]]: + """ + Adjusts the compatibility of widths and groups, + depending on the bottleneck ratio. + """ + # Compute all widths for the current settings + widths = [int(w * b) for w, b in zip(stage_widths, bottleneck_ratios)] + group_widths_min = [min(g, w_bot) for g, w_bot in zip(group_widths, widths)] + + # Compute the adjusted widths so that stage and group widths fit + ws_bot = [_make_divisible(w_bot, g) for w_bot, g in zip(widths, group_widths_min)] + stage_widths = [int(w_bot / b) for w_bot, b in zip(ws_bot, bottleneck_ratios)] + return stage_widths, group_widths_min + + +class RegNet(nn.Module): + def __init__( + self, + block_params: BlockParams, + num_classes: int = 1000, + stem_width: int = 32, + stem_type: Optional[Callable[..., nn.Module]] = None, + block_type: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + activation: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if stem_type is None: + stem_type = SimpleStemIN + if norm_layer is None: + norm_layer = nn.BatchNorm2d + if block_type is None: + block_type = ResBottleneckBlock + if activation is None: + activation = nn.ReLU + + # Ad hoc stem + self.stem = stem_type( + 3, # width_in + stem_width, + norm_layer, + activation, + ) + + current_width = stem_width + + blocks = [] + for i, ( + width_out, + stride, + depth, + group_width, + bottleneck_multiplier, + ) in enumerate(block_params._get_expanded_params()): + blocks.append( + ( + f"block{i+1}", + AnyStage( + current_width, + width_out, + stride, + depth, + block_type, + norm_layer, + activation, + group_width, + bottleneck_multiplier, + block_params.se_ratio, + stage_index=i + 1, + ), + ) + ) + + current_width = width_out + + self.trunk_output = nn.Sequential(OrderedDict(blocks)) + + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = nn.Linear(in_features=current_width, out_features=num_classes) + + # Performs ResNet-style weight initialization + for m in self.modules(): + if isinstance(m, nn.Conv2d): + # Note that there is no bias due to BN + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + nn.init.normal_(m.weight, mean=0.0, std=math.sqrt(2.0 / fan_out)) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, mean=0.0, std=0.01) + nn.init.zeros_(m.bias) + + def forward(self, x: Tensor) -> Tensor: + x = self.stem(x) + x = self.trunk_output(x) + + x = self.avgpool(x) + x = x.flatten(start_dim=1) + x = self.fc(x) + + return x + + +def _regnet( + block_params: BlockParams, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> RegNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + norm_layer = kwargs.pop("norm_layer", partial(nn.BatchNorm2d, eps=1e-05, momentum=0.1)) + model = RegNet(block_params, norm_layer=norm_layer, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META: dict[str, Any] = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + +_COMMON_SWAG_META = { + **_COMMON_META, + "recipe": "https://github.com/facebookresearch/SWAG", + "license": "https://github.com/facebookresearch/SWAG/blob/main/LICENSE", +} + + +class RegNet_Y_400MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_400mf-c65dace8.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 4344144, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.046, + "acc@5": 91.716, + } + }, + "_ops": 0.402, + "_file_size": 16.806, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_400mf-e6988f5f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 4344144, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.804, + "acc@5": 92.742, + } + }, + "_ops": 0.402, + "_file_size": 16.806, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_800MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_800mf-1b27b58c.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 6432512, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.420, + "acc@5": 93.136, + } + }, + "_ops": 0.834, + "_file_size": 24.774, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_800mf-58fc7688.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 6432512, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.828, + "acc@5": 94.502, + } + }, + "_ops": 0.834, + "_file_size": 24.774, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_1_6GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_1_6gf-b11a554e.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 11202430, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.950, + "acc@5": 93.966, + } + }, + "_ops": 1.612, + "_file_size": 43.152, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_1_6gf-0d7bc02a.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 11202430, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.876, + "acc@5": 95.444, + } + }, + "_ops": 1.612, + "_file_size": 43.152, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_3_2GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_3_2gf-b5a9779c.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 19436338, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.948, + "acc@5": 94.576, + } + }, + "_ops": 3.176, + "_file_size": 74.567, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_3_2gf-9180c971.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 19436338, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.982, + "acc@5": 95.972, + } + }, + "_ops": 3.176, + "_file_size": 74.567, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_8GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_8gf-d0d0e4a8.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 39381472, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.032, + "acc@5": 95.048, + } + }, + "_ops": 8.473, + "_file_size": 150.701, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_8gf-dc2b1b54.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 39381472, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.828, + "acc@5": 96.330, + } + }, + "_ops": 8.473, + "_file_size": 150.701, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_16GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf-9e6ed7dd.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 83590140, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#large-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.424, + "acc@5": 95.240, + } + }, + "_ops": 15.912, + "_file_size": 319.49, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf-3e4a00f9.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 83590140, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.886, + "acc@5": 96.328, + } + }, + "_ops": 15.912, + "_file_size": 319.49, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf_swag-43afe44d.pth", + transforms=partial( + ImageClassification, crop_size=384, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 83590140, + "_metrics": { + "ImageNet-1K": { + "acc@1": 86.012, + "acc@5": 98.054, + } + }, + "_ops": 46.735, + "_file_size": 319.49, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf_lc_swag-f3ec0043.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 83590140, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.976, + "acc@5": 97.244, + } + }, + "_ops": 15.912, + "_file_size": 319.49, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_32GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf-4dee3f7a.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 145046770, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#large-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.878, + "acc@5": 95.340, + } + }, + "_ops": 32.28, + "_file_size": 554.076, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf-8db6d4b5.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 145046770, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.368, + "acc@5": 96.498, + } + }, + "_ops": 32.28, + "_file_size": 554.076, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf_swag-04fdfa75.pth", + transforms=partial( + ImageClassification, crop_size=384, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 145046770, + "_metrics": { + "ImageNet-1K": { + "acc@1": 86.838, + "acc@5": 98.362, + } + }, + "_ops": 94.826, + "_file_size": 554.076, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf_lc_swag-e1583746.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 145046770, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.622, + "acc@5": 97.480, + } + }, + "_ops": 32.28, + "_file_size": 554.076, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_128GF_Weights(WeightsEnum): + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_128gf_swag-c8ce3e52.pth", + transforms=partial( + ImageClassification, crop_size=384, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 644812894, + "_metrics": { + "ImageNet-1K": { + "acc@1": 88.228, + "acc@5": 98.682, + } + }, + "_ops": 374.57, + "_file_size": 2461.564, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_128gf_lc_swag-cbe8ce12.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 644812894, + "_metrics": { + "ImageNet-1K": { + "acc@1": 86.068, + "acc@5": 97.844, + } + }, + "_ops": 127.518, + "_file_size": 2461.564, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_SWAG_E2E_V1 + + +class RegNet_X_400MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_400mf-adf1edd5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 5495976, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.834, + "acc@5": 90.950, + } + }, + "_ops": 0.414, + "_file_size": 21.258, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_400mf-62229a5f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 5495976, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.864, + "acc@5": 92.322, + } + }, + "_ops": 0.414, + "_file_size": 21.257, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_800MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_800mf-ad17e45c.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 7259656, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.212, + "acc@5": 92.348, + } + }, + "_ops": 0.8, + "_file_size": 27.945, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_800mf-94a99ebd.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 7259656, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.522, + "acc@5": 93.826, + } + }, + "_ops": 0.8, + "_file_size": 27.945, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_1_6GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_1_6gf-e3633e7f.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 9190136, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.040, + "acc@5": 93.440, + } + }, + "_ops": 1.603, + "_file_size": 35.339, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_1_6gf-a12f2b72.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 9190136, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.668, + "acc@5": 94.922, + } + }, + "_ops": 1.603, + "_file_size": 35.339, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_3_2GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_3_2gf-f342aeae.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 15296552, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.364, + "acc@5": 93.992, + } + }, + "_ops": 3.177, + "_file_size": 58.756, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_3_2gf-7071aa85.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 15296552, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.196, + "acc@5": 95.430, + } + }, + "_ops": 3.177, + "_file_size": 58.756, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_8GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_8gf-03ceed89.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 39572648, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.344, + "acc@5": 94.686, + } + }, + "_ops": 7.995, + "_file_size": 151.456, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_8gf-2b70d774.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 39572648, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.682, + "acc@5": 95.678, + } + }, + "_ops": 7.995, + "_file_size": 151.456, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_16GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_16gf-2007eb11.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 54278536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.058, + "acc@5": 94.944, + } + }, + "_ops": 15.941, + "_file_size": 207.627, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_16gf-ba3796d7.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 54278536, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.716, + "acc@5": 96.196, + } + }, + "_ops": 15.941, + "_file_size": 207.627, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_32GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_32gf-9d47f8d0.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 107811560, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#large-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.622, + "acc@5": 95.248, + } + }, + "_ops": 31.736, + "_file_size": 412.039, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_32gf-6eb8fdc6.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 107811560, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.014, + "acc@5": 96.288, + } + }, + "_ops": 31.736, + "_file_size": 412.039, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_400MF_Weights.IMAGENET1K_V1)) +def regnet_y_400mf(*, weights: Optional[RegNet_Y_400MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_400MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_400MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_400MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_400MF_Weights + :members: + """ + weights = RegNet_Y_400MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=16, w_0=48, w_a=27.89, w_m=2.09, group_width=8, se_ratio=0.25, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_800MF_Weights.IMAGENET1K_V1)) +def regnet_y_800mf(*, weights: Optional[RegNet_Y_800MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_800MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_800MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_800MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_800MF_Weights + :members: + """ + weights = RegNet_Y_800MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=14, w_0=56, w_a=38.84, w_m=2.4, group_width=16, se_ratio=0.25, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_1_6GF_Weights.IMAGENET1K_V1)) +def regnet_y_1_6gf(*, weights: Optional[RegNet_Y_1_6GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_1.6GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_1_6GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_1_6GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_1_6GF_Weights + :members: + """ + weights = RegNet_Y_1_6GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=27, w_0=48, w_a=20.71, w_m=2.65, group_width=24, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_3_2GF_Weights.IMAGENET1K_V1)) +def regnet_y_3_2gf(*, weights: Optional[RegNet_Y_3_2GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_3.2GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_3_2GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_3_2GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_3_2GF_Weights + :members: + """ + weights = RegNet_Y_3_2GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=21, w_0=80, w_a=42.63, w_m=2.66, group_width=24, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_8GF_Weights.IMAGENET1K_V1)) +def regnet_y_8gf(*, weights: Optional[RegNet_Y_8GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_8GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_8GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_8GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_8GF_Weights + :members: + """ + weights = RegNet_Y_8GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=17, w_0=192, w_a=76.82, w_m=2.19, group_width=56, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_16GF_Weights.IMAGENET1K_V1)) +def regnet_y_16gf(*, weights: Optional[RegNet_Y_16GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_16GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_16GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_16GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_16GF_Weights + :members: + """ + weights = RegNet_Y_16GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=18, w_0=200, w_a=106.23, w_m=2.48, group_width=112, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_32GF_Weights.IMAGENET1K_V1)) +def regnet_y_32gf(*, weights: Optional[RegNet_Y_32GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_32GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_32GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_32GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_32GF_Weights + :members: + """ + weights = RegNet_Y_32GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=20, w_0=232, w_a=115.89, w_m=2.53, group_width=232, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", None)) +def regnet_y_128gf(*, weights: Optional[RegNet_Y_128GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_128GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_128GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_128GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_128GF_Weights + :members: + """ + weights = RegNet_Y_128GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=27, w_0=456, w_a=160.83, w_m=2.52, group_width=264, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_400MF_Weights.IMAGENET1K_V1)) +def regnet_x_400mf(*, weights: Optional[RegNet_X_400MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_400MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_400MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_400MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_400MF_Weights + :members: + """ + weights = RegNet_X_400MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=22, w_0=24, w_a=24.48, w_m=2.54, group_width=16, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_800MF_Weights.IMAGENET1K_V1)) +def regnet_x_800mf(*, weights: Optional[RegNet_X_800MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_800MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_800MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_800MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_800MF_Weights + :members: + """ + weights = RegNet_X_800MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=16, w_0=56, w_a=35.73, w_m=2.28, group_width=16, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_1_6GF_Weights.IMAGENET1K_V1)) +def regnet_x_1_6gf(*, weights: Optional[RegNet_X_1_6GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_1.6GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_1_6GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_1_6GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_1_6GF_Weights + :members: + """ + weights = RegNet_X_1_6GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=18, w_0=80, w_a=34.01, w_m=2.25, group_width=24, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_3_2GF_Weights.IMAGENET1K_V1)) +def regnet_x_3_2gf(*, weights: Optional[RegNet_X_3_2GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_3.2GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_3_2GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_3_2GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_3_2GF_Weights + :members: + """ + weights = RegNet_X_3_2GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=25, w_0=88, w_a=26.31, w_m=2.25, group_width=48, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_8GF_Weights.IMAGENET1K_V1)) +def regnet_x_8gf(*, weights: Optional[RegNet_X_8GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_8GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_8GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_8GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_8GF_Weights + :members: + """ + weights = RegNet_X_8GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=23, w_0=80, w_a=49.56, w_m=2.88, group_width=120, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_16GF_Weights.IMAGENET1K_V1)) +def regnet_x_16gf(*, weights: Optional[RegNet_X_16GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_16GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_16GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_16GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_16GF_Weights + :members: + """ + weights = RegNet_X_16GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=22, w_0=216, w_a=55.59, w_m=2.1, group_width=128, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_32GF_Weights.IMAGENET1K_V1)) +def regnet_x_32gf(*, weights: Optional[RegNet_X_32GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_32GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_32GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_32GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_32GF_Weights + :members: + """ + weights = RegNet_X_32GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=23, w_0=320, w_a=69.86, w_m=2.0, group_width=168, **kwargs) + return _regnet(params, weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/resnet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..47067ec83175a97cc6f6a8721b342128a434d440 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/resnet.py @@ -0,0 +1,985 @@ +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "ResNet", + "ResNet18_Weights", + "ResNet34_Weights", + "ResNet50_Weights", + "ResNet101_Weights", + "ResNet152_Weights", + "ResNeXt50_32X4D_Weights", + "ResNeXt101_32X8D_Weights", + "ResNeXt101_64X4D_Weights", + "Wide_ResNet50_2_Weights", + "Wide_ResNet101_2_Weights", + "resnet18", + "resnet34", + "resnet50", + "resnet101", + "resnet152", + "resnext50_32x4d", + "resnext101_32x8d", + "resnext101_64x4d", + "wide_resnet50_2", + "wide_resnet101_2", +] + + +def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d: + """3x3 convolution with padding""" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=dilation, + groups=groups, + bias=False, + dilation=dilation, + ) + + +def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d: + """1x1 convolution""" + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) + + +class BasicBlock(nn.Module): + expansion: int = 1 + + def __init__( + self, + inplanes: int, + planes: int, + stride: int = 1, + downsample: Optional[nn.Module] = None, + groups: int = 1, + base_width: int = 64, + dilation: int = 1, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + if groups != 1 or base_width != 64: + raise ValueError("BasicBlock only supports groups=1 and base_width=64") + if dilation > 1: + raise NotImplementedError("Dilation > 1 not supported in BasicBlock") + # Both self.conv1 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = norm_layer(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = norm_layer(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) + # while original implementation places the stride at the first 1x1 convolution(self.conv1) + # according to "Deep residual learning for image recognition" https://arxiv.org/abs/1512.03385. + # This variant is also known as ResNet V1.5 and improves accuracy according to + # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. + + expansion: int = 4 + + def __init__( + self, + inplanes: int, + planes: int, + stride: int = 1, + downsample: Optional[nn.Module] = None, + groups: int = 1, + base_width: int = 64, + dilation: int = 1, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + width = int(planes * (base_width / 64.0)) * groups + # Both self.conv2 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv1x1(inplanes, width) + self.bn1 = norm_layer(width) + self.conv2 = conv3x3(width, width, stride, groups, dilation) + self.bn2 = norm_layer(width) + self.conv3 = conv1x1(width, planes * self.expansion) + self.bn3 = norm_layer(planes * self.expansion) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class ResNet(nn.Module): + def __init__( + self, + block: type[Union[BasicBlock, Bottleneck]], + layers: list[int], + num_classes: int = 1000, + zero_init_residual: bool = False, + groups: int = 1, + width_per_group: int = 64, + replace_stride_with_dilation: Optional[list[bool]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + if norm_layer is None: + norm_layer = nn.BatchNorm2d + self._norm_layer = norm_layer + + self.inplanes = 64 + self.dilation = 1 + if replace_stride_with_dilation is None: + # each element in the tuple indicates if we should replace + # the 2x2 stride with a dilated convolution instead + replace_stride_with_dilation = [False, False, False] + if len(replace_stride_with_dilation) != 3: + raise ValueError( + "replace_stride_with_dilation should be None " + f"or a 3-element tuple, got {replace_stride_with_dilation}" + ) + self.groups = groups + self.base_width = width_per_group + self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) + self.bn1 = norm_layer(self.inplanes) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) + self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]) + self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]) + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = nn.Linear(512 * block.expansion, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + # Zero-initialize the last BN in each residual branch, + # so that the residual branch starts with zeros, and each residual block behaves like an identity. + # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 + if zero_init_residual: + for m in self.modules(): + if isinstance(m, Bottleneck) and m.bn3.weight is not None: + nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type] + elif isinstance(m, BasicBlock) and m.bn2.weight is not None: + nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type] + + def _make_layer( + self, + block: type[Union[BasicBlock, Bottleneck]], + planes: int, + blocks: int, + stride: int = 1, + dilate: bool = False, + ) -> nn.Sequential: + norm_layer = self._norm_layer + downsample = None + previous_dilation = self.dilation + if dilate: + self.dilation *= stride + stride = 1 + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + conv1x1(self.inplanes, planes * block.expansion, stride), + norm_layer(planes * block.expansion), + ) + + layers = [] + layers.append( + block( + self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer + ) + ) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append( + block( + self.inplanes, + planes, + groups=self.groups, + base_width=self.base_width, + dilation=self.dilation, + norm_layer=norm_layer, + ) + ) + + return nn.Sequential(*layers) + + def _forward_impl(self, x: Tensor) -> Tensor: + # See note [TorchScript super()] + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.fc(x) + + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _resnet( + block: type[Union[BasicBlock, Bottleneck]], + layers: list[int], + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> ResNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = ResNet(block, layers, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + + +class ResNet18_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet18-f37072fd.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 11689512, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.758, + "acc@5": 89.078, + } + }, + "_ops": 1.814, + "_file_size": 44.661, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ResNet34_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet34-b627a593.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 21797672, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.314, + "acc@5": 91.420, + } + }, + "_ops": 3.664, + "_file_size": 83.275, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ResNet50_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet50-0676ba61.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 25557032, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.130, + "acc@5": 92.862, + } + }, + "_ops": 4.089, + "_file_size": 97.781, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnet50-11ad3fa6.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 25557032, + "recipe": "https://github.com/pytorch/vision/issues/3995#issuecomment-1013906621", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.858, + "acc@5": 95.434, + } + }, + "_ops": 4.089, + "_file_size": 97.79, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNet101_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet101-63fe2227.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 44549160, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.374, + "acc@5": 93.546, + } + }, + "_ops": 7.801, + "_file_size": 170.511, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnet101-cd907fc2.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 44549160, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.886, + "acc@5": 95.780, + } + }, + "_ops": 7.801, + "_file_size": 170.53, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNet152_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet152-394f9c45.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 60192808, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.312, + "acc@5": 94.046, + } + }, + "_ops": 11.514, + "_file_size": 230.434, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnet152-f82ba261.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 60192808, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.284, + "acc@5": 96.002, + } + }, + "_ops": 11.514, + "_file_size": 230.474, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNeXt50_32X4D_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 25028904, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnext", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.618, + "acc@5": 93.698, + } + }, + "_ops": 4.23, + "_file_size": 95.789, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnext50_32x4d-1a0047aa.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 25028904, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.198, + "acc@5": 95.340, + } + }, + "_ops": 4.23, + "_file_size": 95.833, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNeXt101_32X8D_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 88791336, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnext", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.312, + "acc@5": 94.526, + } + }, + "_ops": 16.414, + "_file_size": 339.586, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnext101_32x8d-110c445d.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 88791336, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.834, + "acc@5": 96.228, + } + }, + "_ops": 16.414, + "_file_size": 339.673, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNeXt101_64X4D_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnext101_64x4d-173b62eb.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 83455272, + "recipe": "https://github.com/pytorch/vision/pull/5935", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.246, + "acc@5": 96.454, + } + }, + "_ops": 15.46, + "_file_size": 319.318, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Wide_ResNet50_2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 68883240, + "recipe": "https://github.com/pytorch/vision/pull/912#issue-445437439", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.468, + "acc@5": 94.086, + } + }, + "_ops": 11.398, + "_file_size": 131.82, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/wide_resnet50_2-9ba9bcbe.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 68883240, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.602, + "acc@5": 95.758, + } + }, + "_ops": 11.398, + "_file_size": 263.124, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class Wide_ResNet101_2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 126886696, + "recipe": "https://github.com/pytorch/vision/pull/912#issue-445437439", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.848, + "acc@5": 94.284, + } + }, + "_ops": 22.753, + "_file_size": 242.896, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/wide_resnet101_2-d733dc28.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 126886696, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.510, + "acc@5": 96.020, + } + }, + "_ops": 22.753, + "_file_size": 484.747, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet18_Weights.IMAGENET1K_V1)) +def resnet18(*, weights: Optional[ResNet18_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-18 from `Deep Residual Learning for Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.ResNet18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet18_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet18_Weights + :members: + """ + weights = ResNet18_Weights.verify(weights) + + return _resnet(BasicBlock, [2, 2, 2, 2], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet34_Weights.IMAGENET1K_V1)) +def resnet34(*, weights: Optional[ResNet34_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-34 from `Deep Residual Learning for Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.ResNet34_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet34_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet34_Weights + :members: + """ + weights = ResNet34_Weights.verify(weights) + + return _resnet(BasicBlock, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet50_Weights.IMAGENET1K_V1)) +def resnet50(*, weights: Optional[ResNet50_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-50 from `Deep Residual Learning for Image Recognition `__. + + .. note:: + The bottleneck of TorchVision places the stride for downsampling to the second 3x3 + convolution while the original paper places it to the first 1x1 convolution. + This variant improves the accuracy and is known as `ResNet V1.5 + `_. + + Args: + weights (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet50_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet50_Weights + :members: + """ + weights = ResNet50_Weights.verify(weights) + + return _resnet(Bottleneck, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet101_Weights.IMAGENET1K_V1)) +def resnet101(*, weights: Optional[ResNet101_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-101 from `Deep Residual Learning for Image Recognition `__. + + .. note:: + The bottleneck of TorchVision places the stride for downsampling to the second 3x3 + convolution while the original paper places it to the first 1x1 convolution. + This variant improves the accuracy and is known as `ResNet V1.5 + `_. + + Args: + weights (:class:`~torchvision.models.ResNet101_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet101_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet101_Weights + :members: + """ + weights = ResNet101_Weights.verify(weights) + + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet152_Weights.IMAGENET1K_V1)) +def resnet152(*, weights: Optional[ResNet152_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-152 from `Deep Residual Learning for Image Recognition `__. + + .. note:: + The bottleneck of TorchVision places the stride for downsampling to the second 3x3 + convolution while the original paper places it to the first 1x1 convolution. + This variant improves the accuracy and is known as `ResNet V1.5 + `_. + + Args: + weights (:class:`~torchvision.models.ResNet152_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet152_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet152_Weights + :members: + """ + weights = ResNet152_Weights.verify(weights) + + return _resnet(Bottleneck, [3, 8, 36, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNeXt50_32X4D_Weights.IMAGENET1K_V1)) +def resnext50_32x4d( + *, weights: Optional[ResNeXt50_32X4D_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """ResNeXt-50 32x4d model from + `Aggregated Residual Transformation for Deep Neural Networks `_. + + Args: + weights (:class:`~torchvision.models.ResNeXt50_32X4D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNext50_32X4D_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.ResNeXt50_32X4D_Weights + :members: + """ + weights = ResNeXt50_32X4D_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "groups", 32) + _ovewrite_named_param(kwargs, "width_per_group", 4) + return _resnet(Bottleneck, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNeXt101_32X8D_Weights.IMAGENET1K_V1)) +def resnext101_32x8d( + *, weights: Optional[ResNeXt101_32X8D_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """ResNeXt-101 32x8d model from + `Aggregated Residual Transformation for Deep Neural Networks `_. + + Args: + weights (:class:`~torchvision.models.ResNeXt101_32X8D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNeXt101_32X8D_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.ResNeXt101_32X8D_Weights + :members: + """ + weights = ResNeXt101_32X8D_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "groups", 32) + _ovewrite_named_param(kwargs, "width_per_group", 8) + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNeXt101_64X4D_Weights.IMAGENET1K_V1)) +def resnext101_64x4d( + *, weights: Optional[ResNeXt101_64X4D_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """ResNeXt-101 64x4d model from + `Aggregated Residual Transformation for Deep Neural Networks `_. + + Args: + weights (:class:`~torchvision.models.ResNeXt101_64X4D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNeXt101_64X4D_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.ResNeXt101_64X4D_Weights + :members: + """ + weights = ResNeXt101_64X4D_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "groups", 64) + _ovewrite_named_param(kwargs, "width_per_group", 4) + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Wide_ResNet50_2_Weights.IMAGENET1K_V1)) +def wide_resnet50_2( + *, weights: Optional[Wide_ResNet50_2_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """Wide ResNet-50-2 model from + `Wide Residual Networks `_. + + The model is the same as ResNet except for the bottleneck number of channels + which is twice larger in every block. The number of channels in outer 1x1 + convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 + channels, and in Wide ResNet-50-2 has 2048-1024-2048. + + Args: + weights (:class:`~torchvision.models.Wide_ResNet50_2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Wide_ResNet50_2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.Wide_ResNet50_2_Weights + :members: + """ + weights = Wide_ResNet50_2_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "width_per_group", 64 * 2) + return _resnet(Bottleneck, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Wide_ResNet101_2_Weights.IMAGENET1K_V1)) +def wide_resnet101_2( + *, weights: Optional[Wide_ResNet101_2_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """Wide ResNet-101-2 model from + `Wide Residual Networks `_. + + The model is the same as ResNet except for the bottleneck number of channels + which is twice larger in every block. The number of channels in outer 1x1 + convolutions is the same, e.g. last block in ResNet-101 has 2048-512-2048 + channels, and in Wide ResNet-101-2 has 2048-1024-2048. + + Args: + weights (:class:`~torchvision.models.Wide_ResNet101_2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Wide_ResNet101_2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.Wide_ResNet101_2_Weights + :members: + """ + weights = Wide_ResNet101_2_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "width_per_group", 64 * 2) + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6f37f958a131b76ce80306718b77d78bc3f045 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/__init__.py @@ -0,0 +1,3 @@ +from .deeplabv3 import * +from .fcn import * +from .lraspp import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..45bc2e7c43563ad5603f4c53cfee3064cce5e4c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/_utils.py @@ -0,0 +1,37 @@ +from collections import OrderedDict +from typing import Optional + +from torch import nn, Tensor +from torch.nn import functional as F + +from ...utils import _log_api_usage_once + + +class _SimpleSegmentationModel(nn.Module): + __constants__ = ["aux_classifier"] + + def __init__(self, backbone: nn.Module, classifier: nn.Module, aux_classifier: Optional[nn.Module] = None) -> None: + super().__init__() + _log_api_usage_once(self) + self.backbone = backbone + self.classifier = classifier + self.aux_classifier = aux_classifier + + def forward(self, x: Tensor) -> dict[str, Tensor]: + input_shape = x.shape[-2:] + # contract: features is a dict of tensors + features = self.backbone(x) + + result = OrderedDict() + x = features["out"] + x = self.classifier(x) + x = F.interpolate(x, size=input_shape, mode="bilinear", align_corners=False) + result["out"] = x + + if self.aux_classifier is not None: + x = features["aux"] + x = self.aux_classifier(x) + x = F.interpolate(x, size=input_shape, mode="bilinear", align_corners=False) + result["aux"] = x + + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/deeplabv3.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/deeplabv3.py new file mode 100644 index 0000000000000000000000000000000000000000..62790ecb4ddcb05753cf4e7d2004154ad1159e94 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/deeplabv3.py @@ -0,0 +1,391 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Optional + +import torch +from torch import nn +from torch.nn import functional as F + +from ...transforms._presets import SemanticSegmentation +from .._api import register_model, Weights, WeightsEnum +from .._meta import _VOC_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights, MobileNetV3 +from ..resnet import ResNet, resnet101, ResNet101_Weights, resnet50, ResNet50_Weights +from ._utils import _SimpleSegmentationModel +from .fcn import FCNHead + + +__all__ = [ + "DeepLabV3", + "DeepLabV3_ResNet50_Weights", + "DeepLabV3_ResNet101_Weights", + "DeepLabV3_MobileNet_V3_Large_Weights", + "deeplabv3_mobilenet_v3_large", + "deeplabv3_resnet50", + "deeplabv3_resnet101", +] + + +class DeepLabV3(_SimpleSegmentationModel): + """ + Implements DeepLabV3 model from + `"Rethinking Atrous Convolution for Semantic Image Segmentation" + `_. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + The backbone should return an OrderedDict[Tensor], with the key being + "out" for the last feature map used, and "aux" if an auxiliary classifier + is used. + classifier (nn.Module): module that takes the "out" element returned from + the backbone and returns a dense prediction. + aux_classifier (nn.Module, optional): auxiliary classifier used during training + """ + + pass + + +class DeepLabHead(nn.Sequential): + def __init__(self, in_channels: int, num_classes: int, atrous_rates: Sequence[int] = (12, 24, 36)) -> None: + super().__init__( + ASPP(in_channels, atrous_rates), + nn.Conv2d(256, 256, 3, padding=1, bias=False), + nn.BatchNorm2d(256), + nn.ReLU(), + nn.Conv2d(256, num_classes, 1), + ) + + +class ASPPConv(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, dilation: int) -> None: + modules = [ + nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ] + super().__init__(*modules) + + +class ASPPPooling(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int) -> None: + super().__init__( + nn.AdaptiveAvgPool2d(1), + nn.Conv2d(in_channels, out_channels, 1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + size = x.shape[-2:] + for mod in self: + x = mod(x) + return F.interpolate(x, size=size, mode="bilinear", align_corners=False) + + +class ASPP(nn.Module): + def __init__(self, in_channels: int, atrous_rates: Sequence[int], out_channels: int = 256) -> None: + super().__init__() + modules = [] + modules.append( + nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU()) + ) + + rates = tuple(atrous_rates) + for rate in rates: + modules.append(ASPPConv(in_channels, out_channels, rate)) + + modules.append(ASPPPooling(in_channels, out_channels)) + + self.convs = nn.ModuleList(modules) + + self.project = nn.Sequential( + nn.Conv2d(len(self.convs) * out_channels, out_channels, 1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + nn.Dropout(0.5), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + _res = [] + for conv in self.convs: + _res.append(conv(x)) + res = torch.cat(_res, dim=1) + return self.project(res) + + +def _deeplabv3_resnet( + backbone: ResNet, + num_classes: int, + aux: Optional[bool], +) -> DeepLabV3: + return_layers = {"layer4": "out"} + if aux: + return_layers["layer3"] = "aux" + backbone = IntermediateLayerGetter(backbone, return_layers=return_layers) + + aux_classifier = FCNHead(1024, num_classes) if aux else None + classifier = DeepLabHead(2048, num_classes) + return DeepLabV3(backbone, classifier, aux_classifier) + + +_COMMON_META = { + "categories": _VOC_CATEGORIES, + "min_size": (1, 1), + "_docs": """ + These weights were trained on a subset of COCO, using only the 20 categories that are present in the Pascal VOC + dataset. + """, +} + + +class DeepLabV3_ResNet50_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/deeplabv3_resnet50_coco-cd0a2569.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 42004074, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_resnet50", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 66.4, + "pixel_acc": 92.4, + } + }, + "_ops": 178.722, + "_file_size": 160.515, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +class DeepLabV3_ResNet101_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/deeplabv3_resnet101_coco-586e9e4e.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 60996202, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#fcn_resnet101", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 67.4, + "pixel_acc": 92.4, + } + }, + "_ops": 258.743, + "_file_size": 233.217, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +class DeepLabV3_MobileNet_V3_Large_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/deeplabv3_mobilenet_v3_large-fc3c493d.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 11029328, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_mobilenet_v3_large", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 60.3, + "pixel_acc": 91.2, + } + }, + "_ops": 10.452, + "_file_size": 42.301, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +def _deeplabv3_mobilenetv3( + backbone: MobileNetV3, + num_classes: int, + aux: Optional[bool], +) -> DeepLabV3: + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + out_pos = stage_indices[-1] # use C5 which has output_stride = 16 + out_inplanes = backbone[out_pos].out_channels + aux_pos = stage_indices[-4] # use C2 here which has output_stride = 8 + aux_inplanes = backbone[aux_pos].out_channels + return_layers = {str(out_pos): "out"} + if aux: + return_layers[str(aux_pos)] = "aux" + backbone = IntermediateLayerGetter(backbone, return_layers=return_layers) + + aux_classifier = FCNHead(aux_inplanes, num_classes) if aux else None + classifier = DeepLabHead(out_inplanes, num_classes) + return DeepLabV3(backbone, classifier, aux_classifier) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", DeepLabV3_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def deeplabv3_resnet50( + *, + weights: Optional[DeepLabV3_ResNet50_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> DeepLabV3: + """Constructs a DeepLabV3 model with a ResNet-50 backbone. + + .. betastatus:: segmentation module + + Reference: `Rethinking Atrous Convolution for Semantic Image Segmentation `__. + + Args: + weights (:class:`~torchvision.models.segmentation.DeepLabV3_ResNet50_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.DeepLabV3_ResNet50_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + aux_loss (bool, optional): If True, it uses an auxiliary loss + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for the + backbone + **kwargs: unused + + .. autoclass:: torchvision.models.segmentation.DeepLabV3_ResNet50_Weights + :members: + """ + weights = DeepLabV3_ResNet50_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet50(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _deeplabv3_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", DeepLabV3_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet101_Weights.IMAGENET1K_V1), +) +def deeplabv3_resnet101( + *, + weights: Optional[DeepLabV3_ResNet101_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet101_Weights] = ResNet101_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> DeepLabV3: + """Constructs a DeepLabV3 model with a ResNet-101 backbone. + + .. betastatus:: segmentation module + + Reference: `Rethinking Atrous Convolution for Semantic Image Segmentation `__. + + Args: + weights (:class:`~torchvision.models.segmentation.DeepLabV3_ResNet101_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.DeepLabV3_ResNet101_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + aux_loss (bool, optional): If True, it uses an auxiliary loss + weights_backbone (:class:`~torchvision.models.ResNet101_Weights`, optional): The pretrained weights for the + backbone + **kwargs: unused + + .. autoclass:: torchvision.models.segmentation.DeepLabV3_ResNet101_Weights + :members: + """ + weights = DeepLabV3_ResNet101_Weights.verify(weights) + weights_backbone = ResNet101_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet101(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _deeplabv3_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", DeepLabV3_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def deeplabv3_mobilenet_v3_large( + *, + weights: Optional[DeepLabV3_MobileNet_V3_Large_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> DeepLabV3: + """Constructs a DeepLabV3 model with a MobileNetV3-Large backbone. + + Reference: `Rethinking Atrous Convolution for Semantic Image Segmentation `__. + + Args: + weights (:class:`~torchvision.models.segmentation.DeepLabV3_MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.DeepLabV3_MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + aux_loss (bool, optional): If True, it uses an auxiliary loss + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained weights + for the backbone + **kwargs: unused + + .. autoclass:: torchvision.models.segmentation.DeepLabV3_MobileNet_V3_Large_Weights + :members: + """ + weights = DeepLabV3_MobileNet_V3_Large_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = mobilenet_v3_large(weights=weights_backbone, dilated=True) + model = _deeplabv3_mobilenetv3(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/fcn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/fcn.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2e242adac0e7430bab6155ae0347770e29fee9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/fcn.py @@ -0,0 +1,232 @@ +from functools import partial +from typing import Any, Optional + +from torch import nn + +from ...transforms._presets import SemanticSegmentation +from .._api import register_model, Weights, WeightsEnum +from .._meta import _VOC_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter +from ..resnet import ResNet, resnet101, ResNet101_Weights, resnet50, ResNet50_Weights +from ._utils import _SimpleSegmentationModel + + +__all__ = ["FCN", "FCN_ResNet50_Weights", "FCN_ResNet101_Weights", "fcn_resnet50", "fcn_resnet101"] + + +class FCN(_SimpleSegmentationModel): + """ + Implements FCN model from + `"Fully Convolutional Networks for Semantic Segmentation" + `_. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + The backbone should return an OrderedDict[Tensor], with the key being + "out" for the last feature map used, and "aux" if an auxiliary classifier + is used. + classifier (nn.Module): module that takes the "out" element returned from + the backbone and returns a dense prediction. + aux_classifier (nn.Module, optional): auxiliary classifier used during training + """ + + pass + + +class FCNHead(nn.Sequential): + def __init__(self, in_channels: int, channels: int) -> None: + inter_channels = in_channels // 4 + layers = [ + nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU(), + nn.Dropout(0.1), + nn.Conv2d(inter_channels, channels, 1), + ] + + super().__init__(*layers) + + +_COMMON_META = { + "categories": _VOC_CATEGORIES, + "min_size": (1, 1), + "_docs": """ + These weights were trained on a subset of COCO, using only the 20 categories that are present in the Pascal VOC + dataset. + """, +} + + +class FCN_ResNet50_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/fcn_resnet50_coco-1167a1af.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 35322218, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#fcn_resnet50", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 60.5, + "pixel_acc": 91.4, + } + }, + "_ops": 152.717, + "_file_size": 135.009, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +class FCN_ResNet101_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/fcn_resnet101_coco-7ecb50ca.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 54314346, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_resnet101", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 63.7, + "pixel_acc": 91.9, + } + }, + "_ops": 232.738, + "_file_size": 207.711, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +def _fcn_resnet( + backbone: ResNet, + num_classes: int, + aux: Optional[bool], +) -> FCN: + return_layers = {"layer4": "out"} + if aux: + return_layers["layer3"] = "aux" + backbone = IntermediateLayerGetter(backbone, return_layers=return_layers) + + aux_classifier = FCNHead(1024, num_classes) if aux else None + classifier = FCNHead(2048, num_classes) + return FCN(backbone, classifier, aux_classifier) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fcn_resnet50( + *, + weights: Optional[FCN_ResNet50_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> FCN: + """Fully-Convolutional Network model with a ResNet-50 backbone from the `Fully Convolutional + Networks for Semantic Segmentation `_ paper. + + .. betastatus:: segmentation module + + Args: + weights (:class:`~torchvision.models.segmentation.FCN_ResNet50_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.FCN_ResNet50_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background). + aux_loss (bool, optional): If True, it uses an auxiliary loss. + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained + weights for the backbone. + **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.segmentation.FCN_ResNet50_Weights + :members: + """ + + weights = FCN_ResNet50_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet50(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _fcn_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FCN_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet101_Weights.IMAGENET1K_V1), +) +def fcn_resnet101( + *, + weights: Optional[FCN_ResNet101_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet101_Weights] = ResNet101_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> FCN: + """Fully-Convolutional Network model with a ResNet-101 backbone from the `Fully Convolutional + Networks for Semantic Segmentation `_ paper. + + .. betastatus:: segmentation module + + Args: + weights (:class:`~torchvision.models.segmentation.FCN_ResNet101_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.FCN_ResNet101_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background). + aux_loss (bool, optional): If True, it uses an auxiliary loss. + weights_backbone (:class:`~torchvision.models.ResNet101_Weights`, optional): The pretrained + weights for the backbone. + **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.segmentation.FCN_ResNet101_Weights + :members: + """ + + weights = FCN_ResNet101_Weights.verify(weights) + weights_backbone = ResNet101_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet101(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _fcn_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/lraspp.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/lraspp.py new file mode 100644 index 0000000000000000000000000000000000000000..e49b06d5b9facef807acc8fc9516a53d56ef01c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/segmentation/lraspp.py @@ -0,0 +1,178 @@ +from collections import OrderedDict +from functools import partial +from typing import Any, Optional + +from torch import nn, Tensor +from torch.nn import functional as F + +from ...transforms._presets import SemanticSegmentation +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _VOC_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights, MobileNetV3 + + +__all__ = ["LRASPP", "LRASPP_MobileNet_V3_Large_Weights", "lraspp_mobilenet_v3_large"] + + +class LRASPP(nn.Module): + """ + Implements a Lite R-ASPP Network for semantic segmentation from + `"Searching for MobileNetV3" + `_. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + The backbone should return an OrderedDict[Tensor], with the key being + "high" for the high level feature map and "low" for the low level feature map. + low_channels (int): the number of channels of the low level features. + high_channels (int): the number of channels of the high level features. + num_classes (int, optional): number of output classes of the model (including the background). + inter_channels (int, optional): the number of channels for intermediate computations. + """ + + def __init__( + self, backbone: nn.Module, low_channels: int, high_channels: int, num_classes: int, inter_channels: int = 128 + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.backbone = backbone + self.classifier = LRASPPHead(low_channels, high_channels, num_classes, inter_channels) + + def forward(self, input: Tensor) -> dict[str, Tensor]: + features = self.backbone(input) + out = self.classifier(features) + out = F.interpolate(out, size=input.shape[-2:], mode="bilinear", align_corners=False) + + result = OrderedDict() + result["out"] = out + + return result + + +class LRASPPHead(nn.Module): + def __init__(self, low_channels: int, high_channels: int, num_classes: int, inter_channels: int) -> None: + super().__init__() + self.cbr = nn.Sequential( + nn.Conv2d(high_channels, inter_channels, 1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU(inplace=True), + ) + self.scale = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + nn.Conv2d(high_channels, inter_channels, 1, bias=False), + nn.Sigmoid(), + ) + self.low_classifier = nn.Conv2d(low_channels, num_classes, 1) + self.high_classifier = nn.Conv2d(inter_channels, num_classes, 1) + + def forward(self, input: dict[str, Tensor]) -> Tensor: + low = input["low"] + high = input["high"] + + x = self.cbr(high) + s = self.scale(high) + x = x * s + x = F.interpolate(x, size=low.shape[-2:], mode="bilinear", align_corners=False) + + return self.low_classifier(low) + self.high_classifier(x) + + +def _lraspp_mobilenetv3(backbone: MobileNetV3, num_classes: int) -> LRASPP: + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + low_pos = stage_indices[-4] # use C2 here which has output_stride = 8 + high_pos = stage_indices[-1] # use C5 which has output_stride = 16 + low_channels = backbone[low_pos].out_channels + high_channels = backbone[high_pos].out_channels + backbone = IntermediateLayerGetter(backbone, return_layers={str(low_pos): "low", str(high_pos): "high"}) + + return LRASPP(backbone, low_channels, high_channels, num_classes) + + +class LRASPP_MobileNet_V3_Large_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/lraspp_mobilenet_v3_large-d234d4ea.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + "num_params": 3221538, + "categories": _VOC_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#lraspp_mobilenet_v3_large", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 57.9, + "pixel_acc": 91.2, + } + }, + "_ops": 2.086, + "_file_size": 12.49, + "_docs": """ + These weights were trained on a subset of COCO, using only the 20 categories that are present in the + Pascal VOC dataset. + """, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", LRASPP_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def lraspp_mobilenet_v3_large( + *, + weights: Optional[LRASPP_MobileNet_V3_Large_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> LRASPP: + """Constructs a Lite R-ASPP Network model with a MobileNetV3-Large backbone from + `Searching for MobileNetV3 `_ paper. + + .. betastatus:: segmentation module + + Args: + weights (:class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background). + aux_loss (bool, optional): If True, it uses an auxiliary loss. + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained + weights for the backbone. + **kwargs: parameters passed to the ``torchvision.models.segmentation.LRASPP`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights + :members: + """ + if kwargs.pop("aux_loss", False): + raise NotImplementedError("This model does not use auxiliary loss") + + weights = LRASPP_MobileNet_V3_Large_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 21 + + backbone = mobilenet_v3_large(weights=weights_backbone, dilated=True) + model = _lraspp_mobilenetv3(backbone, num_classes) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/shufflenetv2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/shufflenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..96736f6a7ac289102ef7a57cb4cbb960c02c625e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/shufflenetv2.py @@ -0,0 +1,408 @@ +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn as nn +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "ShuffleNetV2", + "ShuffleNet_V2_X0_5_Weights", + "ShuffleNet_V2_X1_0_Weights", + "ShuffleNet_V2_X1_5_Weights", + "ShuffleNet_V2_X2_0_Weights", + "shufflenet_v2_x0_5", + "shufflenet_v2_x1_0", + "shufflenet_v2_x1_5", + "shufflenet_v2_x2_0", +] + + +def channel_shuffle(x: Tensor, groups: int) -> Tensor: + batchsize, num_channels, height, width = x.size() + channels_per_group = num_channels // groups + + # reshape + x = x.view(batchsize, groups, channels_per_group, height, width) + + x = torch.transpose(x, 1, 2).contiguous() + + # flatten + x = x.view(batchsize, num_channels, height, width) + + return x + + +class InvertedResidual(nn.Module): + def __init__(self, inp: int, oup: int, stride: int) -> None: + super().__init__() + + if not (1 <= stride <= 3): + raise ValueError("illegal stride value") + self.stride = stride + + branch_features = oup // 2 + if (self.stride == 1) and (inp != branch_features << 1): + raise ValueError( + f"Invalid combination of stride {stride}, inp {inp} and oup {oup} values. If stride == 1 then inp should be equal to oup // 2 << 1." + ) + + if self.stride > 1: + self.branch1 = nn.Sequential( + self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1), + nn.BatchNorm2d(inp), + nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + ) + else: + self.branch1 = nn.Sequential() + + self.branch2 = nn.Sequential( + nn.Conv2d( + inp if (self.stride > 1) else branch_features, + branch_features, + kernel_size=1, + stride=1, + padding=0, + bias=False, + ), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1), + nn.BatchNorm2d(branch_features), + nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + ) + + @staticmethod + def depthwise_conv( + i: int, o: int, kernel_size: int, stride: int = 1, padding: int = 0, bias: bool = False + ) -> nn.Conv2d: + return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i) + + def forward(self, x: Tensor) -> Tensor: + if self.stride == 1: + x1, x2 = x.chunk(2, dim=1) + out = torch.cat((x1, self.branch2(x2)), dim=1) + else: + out = torch.cat((self.branch1(x), self.branch2(x)), dim=1) + + out = channel_shuffle(out, 2) + + return out + + +class ShuffleNetV2(nn.Module): + def __init__( + self, + stages_repeats: list[int], + stages_out_channels: list[int], + num_classes: int = 1000, + inverted_residual: Callable[..., nn.Module] = InvertedResidual, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if len(stages_repeats) != 3: + raise ValueError("expected stages_repeats as list of 3 positive ints") + if len(stages_out_channels) != 5: + raise ValueError("expected stages_out_channels as list of 5 positive ints") + self._stage_out_channels = stages_out_channels + + input_channels = 3 + output_channels = self._stage_out_channels[0] + self.conv1 = nn.Sequential( + nn.Conv2d(input_channels, output_channels, 3, 2, 1, bias=False), + nn.BatchNorm2d(output_channels), + nn.ReLU(inplace=True), + ) + input_channels = output_channels + + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + + # Static annotations for mypy + self.stage2: nn.Sequential + self.stage3: nn.Sequential + self.stage4: nn.Sequential + stage_names = [f"stage{i}" for i in [2, 3, 4]] + for name, repeats, output_channels in zip(stage_names, stages_repeats, self._stage_out_channels[1:]): + seq = [inverted_residual(input_channels, output_channels, 2)] + for i in range(repeats - 1): + seq.append(inverted_residual(output_channels, output_channels, 1)) + setattr(self, name, nn.Sequential(*seq)) + input_channels = output_channels + + output_channels = self._stage_out_channels[-1] + self.conv5 = nn.Sequential( + nn.Conv2d(input_channels, output_channels, 1, 1, 0, bias=False), + nn.BatchNorm2d(output_channels), + nn.ReLU(inplace=True), + ) + + self.fc = nn.Linear(output_channels, num_classes) + + def _forward_impl(self, x: Tensor) -> Tensor: + # See note [TorchScript super()] + x = self.conv1(x) + x = self.maxpool(x) + x = self.stage2(x) + x = self.stage3(x) + x = self.stage4(x) + x = self.conv5(x) + x = x.mean([2, 3]) # globalpool + x = self.fc(x) + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _shufflenetv2( + weights: Optional[WeightsEnum], + progress: bool, + *args: Any, + **kwargs: Any, +) -> ShuffleNetV2: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = ShuffleNetV2(*args, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/ericsun99/Shufflenet-v2-Pytorch", +} + + +class ShuffleNet_V2_X0_5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/ericsun99/Shufflenet-v2-Pytorch + url="https://download.pytorch.org/models/shufflenetv2_x0.5-f707e7126e.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 1366792, + "_metrics": { + "ImageNet-1K": { + "acc@1": 60.552, + "acc@5": 81.746, + } + }, + "_ops": 0.04, + "_file_size": 5.282, + "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ShuffleNet_V2_X1_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/ericsun99/Shufflenet-v2-Pytorch + url="https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2278604, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.362, + "acc@5": 88.316, + } + }, + "_ops": 0.145, + "_file_size": 8.791, + "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ShuffleNet_V2_X1_5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/shufflenetv2_x1_5-3c479a10.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 3503624, + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.996, + "acc@5": 91.086, + } + }, + "_ops": 0.296, + "_file_size": 13.557, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ShuffleNet_V2_X2_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/shufflenetv2_x2_0-8be3c8ee.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 7393996, + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.230, + "acc@5": 93.006, + } + }, + "_ops": 0.583, + "_file_size": 28.433, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x0_5( + *, weights: Optional[ShuffleNet_V2_X0_5_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 0.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights + :members: + """ + weights = ShuffleNet_V2_X0_5_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x1_0( + *, weights: Optional[ShuffleNet_V2_X1_0_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 1.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights + :members: + """ + weights = ShuffleNet_V2_X1_0_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x1_5( + *, weights: Optional[ShuffleNet_V2_X1_5_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 1.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights + :members: + """ + weights = ShuffleNet_V2_X1_5_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 176, 352, 704, 1024], **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x2_0( + *, weights: Optional[ShuffleNet_V2_X2_0_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 2.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights + :members: + """ + weights = ShuffleNet_V2_X2_0_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/squeezenet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/squeezenet.py new file mode 100644 index 0000000000000000000000000000000000000000..982b32107b09c280b4c7caa61e6b80be0cbf041e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/squeezenet.py @@ -0,0 +1,223 @@ +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.init as init + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["SqueezeNet", "SqueezeNet1_0_Weights", "SqueezeNet1_1_Weights", "squeezenet1_0", "squeezenet1_1"] + + +class Fire(nn.Module): + def __init__(self, inplanes: int, squeeze_planes: int, expand1x1_planes: int, expand3x3_planes: int) -> None: + super().__init__() + self.inplanes = inplanes + self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1) + self.squeeze_activation = nn.ReLU(inplace=True) + self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes, kernel_size=1) + self.expand1x1_activation = nn.ReLU(inplace=True) + self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes, kernel_size=3, padding=1) + self.expand3x3_activation = nn.ReLU(inplace=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.squeeze_activation(self.squeeze(x)) + return torch.cat( + [self.expand1x1_activation(self.expand1x1(x)), self.expand3x3_activation(self.expand3x3(x))], 1 + ) + + +class SqueezeNet(nn.Module): + def __init__(self, version: str = "1_0", num_classes: int = 1000, dropout: float = 0.5) -> None: + super().__init__() + _log_api_usage_once(self) + self.num_classes = num_classes + if version == "1_0": + self.features = nn.Sequential( + nn.Conv2d(3, 96, kernel_size=7, stride=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(96, 16, 64, 64), + Fire(128, 16, 64, 64), + Fire(128, 32, 128, 128), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(256, 32, 128, 128), + Fire(256, 48, 192, 192), + Fire(384, 48, 192, 192), + Fire(384, 64, 256, 256), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(512, 64, 256, 256), + ) + elif version == "1_1": + self.features = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=3, stride=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(64, 16, 64, 64), + Fire(128, 16, 64, 64), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(128, 32, 128, 128), + Fire(256, 32, 128, 128), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(256, 48, 192, 192), + Fire(384, 48, 192, 192), + Fire(384, 64, 256, 256), + Fire(512, 64, 256, 256), + ) + else: + # FIXME: Is this needed? SqueezeNet should only be called from the + # FIXME: squeezenet1_x() functions + # FIXME: This checking is not done for the other models + raise ValueError(f"Unsupported SqueezeNet version {version}: 1_0 or 1_1 expected") + + # Final convolution is initialized differently from the rest + final_conv = nn.Conv2d(512, self.num_classes, kernel_size=1) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), final_conv, nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d((1, 1)) + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + if m is final_conv: + init.normal_(m.weight, mean=0.0, std=0.01) + else: + init.kaiming_uniform_(m.weight) + if m.bias is not None: + init.constant_(m.bias, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.classifier(x) + return torch.flatten(x, 1) + + +def _squeezenet( + version: str, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> SqueezeNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = SqueezeNet(version, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/pull/49#issuecomment-277560717", + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", +} + + +class SqueezeNet1_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "min_size": (21, 21), + "num_params": 1248424, + "_metrics": { + "ImageNet-1K": { + "acc@1": 58.092, + "acc@5": 80.420, + } + }, + "_ops": 0.819, + "_file_size": 4.778, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class SqueezeNet1_1_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/squeezenet1_1-b8a52dc0.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "min_size": (17, 17), + "num_params": 1235496, + "_metrics": { + "ImageNet-1K": { + "acc@1": 58.178, + "acc@5": 80.624, + } + }, + "_ops": 0.349, + "_file_size": 4.729, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", SqueezeNet1_0_Weights.IMAGENET1K_V1)) +def squeezenet1_0( + *, weights: Optional[SqueezeNet1_0_Weights] = None, progress: bool = True, **kwargs: Any +) -> SqueezeNet: + """SqueezeNet model architecture from the `SqueezeNet: AlexNet-level + accuracy with 50x fewer parameters and <0.5MB model size + `_ paper. + + Args: + weights (:class:`~torchvision.models.SqueezeNet1_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.SqueezeNet1_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.squeezenet.SqueezeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.SqueezeNet1_0_Weights + :members: + """ + weights = SqueezeNet1_0_Weights.verify(weights) + return _squeezenet("1_0", weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", SqueezeNet1_1_Weights.IMAGENET1K_V1)) +def squeezenet1_1( + *, weights: Optional[SqueezeNet1_1_Weights] = None, progress: bool = True, **kwargs: Any +) -> SqueezeNet: + """SqueezeNet 1.1 model from the `official SqueezeNet repo + `_. + + SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters + than SqueezeNet 1.0, without sacrificing accuracy. + + Args: + weights (:class:`~torchvision.models.SqueezeNet1_1_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.SqueezeNet1_1_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.squeezenet.SqueezeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.SqueezeNet1_1_Weights + :members: + """ + weights = SqueezeNet1_1_Weights.verify(weights) + return _squeezenet("1_1", weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/swin_transformer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/swin_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..80850b4a389e6488a2d5ae76a4159b5ad26a6faa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/swin_transformer.py @@ -0,0 +1,1033 @@ +import math +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ..ops.misc import MLP, Permute +from ..ops.stochastic_depth import StochasticDepth +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "SwinTransformer", + "Swin_T_Weights", + "Swin_S_Weights", + "Swin_B_Weights", + "Swin_V2_T_Weights", + "Swin_V2_S_Weights", + "Swin_V2_B_Weights", + "swin_t", + "swin_s", + "swin_b", + "swin_v2_t", + "swin_v2_s", + "swin_v2_b", +] + + +def _patch_merging_pad(x: torch.Tensor) -> torch.Tensor: + H, W, _ = x.shape[-3:] + x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) + x0 = x[..., 0::2, 0::2, :] # ... H/2 W/2 C + x1 = x[..., 1::2, 0::2, :] # ... H/2 W/2 C + x2 = x[..., 0::2, 1::2, :] # ... H/2 W/2 C + x3 = x[..., 1::2, 1::2, :] # ... H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # ... H/2 W/2 4*C + return x + + +torch.fx.wrap("_patch_merging_pad") + + +def _get_relative_position_bias( + relative_position_bias_table: torch.Tensor, relative_position_index: torch.Tensor, window_size: list[int] +) -> torch.Tensor: + N = window_size[0] * window_size[1] + relative_position_bias = relative_position_bias_table[relative_position_index] # type: ignore[index] + relative_position_bias = relative_position_bias.view(N, N, -1) + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(0) + return relative_position_bias + + +torch.fx.wrap("_get_relative_position_bias") + + +class PatchMerging(nn.Module): + """Patch Merging Layer. + Args: + dim (int): Number of input channels. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + """ + + def __init__(self, dim: int, norm_layer: Callable[..., nn.Module] = nn.LayerNorm): + super().__init__() + _log_api_usage_once(self) + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x: Tensor): + """ + Args: + x (Tensor): input tensor with expected layout of [..., H, W, C] + Returns: + Tensor with layout of [..., H/2, W/2, 2*C] + """ + x = _patch_merging_pad(x) + x = self.norm(x) + x = self.reduction(x) # ... H/2 W/2 2*C + return x + + +class PatchMergingV2(nn.Module): + """Patch Merging Layer for Swin Transformer V2. + Args: + dim (int): Number of input channels. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + """ + + def __init__(self, dim: int, norm_layer: Callable[..., nn.Module] = nn.LayerNorm): + super().__init__() + _log_api_usage_once(self) + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(2 * dim) # difference + + def forward(self, x: Tensor): + """ + Args: + x (Tensor): input tensor with expected layout of [..., H, W, C] + Returns: + Tensor with layout of [..., H/2, W/2, 2*C] + """ + x = _patch_merging_pad(x) + x = self.reduction(x) # ... H/2 W/2 2*C + x = self.norm(x) + return x + + +def shifted_window_attention( + input: Tensor, + qkv_weight: Tensor, + proj_weight: Tensor, + relative_position_bias: Tensor, + window_size: list[int], + num_heads: int, + shift_size: list[int], + attention_dropout: float = 0.0, + dropout: float = 0.0, + qkv_bias: Optional[Tensor] = None, + proj_bias: Optional[Tensor] = None, + logit_scale: Optional[torch.Tensor] = None, + training: bool = True, +) -> Tensor: + """ + Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + input (Tensor[N, H, W, C]): The input tensor or 4-dimensions. + qkv_weight (Tensor[in_dim, out_dim]): The weight tensor of query, key, value. + proj_weight (Tensor[out_dim, out_dim]): The weight tensor of projection. + relative_position_bias (Tensor): The learned relative position bias added to attention. + window_size (List[int]): Window size. + num_heads (int): Number of attention heads. + shift_size (List[int]): Shift size for shifted window attention. + attention_dropout (float): Dropout ratio of attention weight. Default: 0.0. + dropout (float): Dropout ratio of output. Default: 0.0. + qkv_bias (Tensor[out_dim], optional): The bias tensor of query, key, value. Default: None. + proj_bias (Tensor[out_dim], optional): The bias tensor of projection. Default: None. + logit_scale (Tensor[out_dim], optional): Logit scale of cosine attention for Swin Transformer V2. Default: None. + training (bool, optional): Training flag used by the dropout parameters. Default: True. + Returns: + Tensor[N, H, W, C]: The output tensor after shifted window attention. + """ + B, H, W, C = input.shape + # pad feature maps to multiples of window size + pad_r = (window_size[1] - W % window_size[1]) % window_size[1] + pad_b = (window_size[0] - H % window_size[0]) % window_size[0] + x = F.pad(input, (0, 0, 0, pad_r, 0, pad_b)) + _, pad_H, pad_W, _ = x.shape + + shift_size = shift_size.copy() + # If window size is larger than feature size, there is no need to shift window + if window_size[0] >= pad_H: + shift_size[0] = 0 + if window_size[1] >= pad_W: + shift_size[1] = 0 + + # cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(-shift_size[0], -shift_size[1]), dims=(1, 2)) + + # partition windows + num_windows = (pad_H // window_size[0]) * (pad_W // window_size[1]) + x = x.view(B, pad_H // window_size[0], window_size[0], pad_W // window_size[1], window_size[1], C) + x = x.permute(0, 1, 3, 2, 4, 5).reshape(B * num_windows, window_size[0] * window_size[1], C) # B*nW, Ws*Ws, C + + # multi-head attention + if logit_scale is not None and qkv_bias is not None: + qkv_bias = qkv_bias.clone() + length = qkv_bias.numel() // 3 + qkv_bias[length : 2 * length].zero_() + qkv = F.linear(x, qkv_weight, qkv_bias) + qkv = qkv.reshape(x.size(0), x.size(1), 3, num_heads, C // num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + if logit_scale is not None: + # cosine attention + attn = F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1) + logit_scale = torch.clamp(logit_scale, max=math.log(100.0)).exp() + attn = attn * logit_scale + else: + q = q * (C // num_heads) ** -0.5 + attn = q.matmul(k.transpose(-2, -1)) + # add relative position bias + attn = attn + relative_position_bias + + if sum(shift_size) > 0: + # generate attention mask + attn_mask = x.new_zeros((pad_H, pad_W)) + h_slices = ((0, -window_size[0]), (-window_size[0], -shift_size[0]), (-shift_size[0], None)) + w_slices = ((0, -window_size[1]), (-window_size[1], -shift_size[1]), (-shift_size[1], None)) + count = 0 + for h in h_slices: + for w in w_slices: + attn_mask[h[0] : h[1], w[0] : w[1]] = count + count += 1 + attn_mask = attn_mask.view(pad_H // window_size[0], window_size[0], pad_W // window_size[1], window_size[1]) + attn_mask = attn_mask.permute(0, 2, 1, 3).reshape(num_windows, window_size[0] * window_size[1]) + attn_mask = attn_mask.unsqueeze(1) - attn_mask.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + attn = attn.view(x.size(0) // num_windows, num_windows, num_heads, x.size(1), x.size(1)) + attn = attn + attn_mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, num_heads, x.size(1), x.size(1)) + + attn = F.softmax(attn, dim=-1) + attn = F.dropout(attn, p=attention_dropout, training=training) + + x = attn.matmul(v).transpose(1, 2).reshape(x.size(0), x.size(1), C) + x = F.linear(x, proj_weight, proj_bias) + x = F.dropout(x, p=dropout, training=training) + + # reverse windows + x = x.view(B, pad_H // window_size[0], pad_W // window_size[1], window_size[0], window_size[1], C) + x = x.permute(0, 1, 3, 2, 4, 5).reshape(B, pad_H, pad_W, C) + + # reverse cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(shift_size[0], shift_size[1]), dims=(1, 2)) + + # unpad features + x = x[:, :H, :W, :].contiguous() + return x + + +torch.fx.wrap("shifted_window_attention") + + +class ShiftedWindowAttention(nn.Module): + """ + See :func:`shifted_window_attention`. + """ + + def __init__( + self, + dim: int, + window_size: list[int], + shift_size: list[int], + num_heads: int, + qkv_bias: bool = True, + proj_bias: bool = True, + attention_dropout: float = 0.0, + dropout: float = 0.0, + ): + super().__init__() + if len(window_size) != 2 or len(shift_size) != 2: + raise ValueError("window_size and shift_size must be of length 2") + self.window_size = window_size + self.shift_size = shift_size + self.num_heads = num_heads + self.attention_dropout = attention_dropout + self.dropout = dropout + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + + self.define_relative_position_bias_table() + self.define_relative_position_index() + + def define_relative_position_bias_table(self): + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), self.num_heads) + ) # 2*Wh-1 * 2*Ww-1, nH + nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + def define_relative_position_index(self): + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(self.window_size[0]) + coords_w = torch.arange(self.window_size[1]) + coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij")) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 + relative_position_index = relative_coords.sum(-1).flatten() # Wh*Ww*Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + def get_relative_position_bias(self) -> torch.Tensor: + return _get_relative_position_bias( + self.relative_position_bias_table, self.relative_position_index, self.window_size # type: ignore[arg-type] + ) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Tensor with layout of [B, H, W, C] + Returns: + Tensor with same layout as input, i.e. [B, H, W, C] + """ + relative_position_bias = self.get_relative_position_bias() + return shifted_window_attention( + x, + self.qkv.weight, + self.proj.weight, + relative_position_bias, + self.window_size, + self.num_heads, + shift_size=self.shift_size, + attention_dropout=self.attention_dropout, + dropout=self.dropout, + qkv_bias=self.qkv.bias, + proj_bias=self.proj.bias, + training=self.training, + ) + + +class ShiftedWindowAttentionV2(ShiftedWindowAttention): + """ + See :func:`shifted_window_attention_v2`. + """ + + def __init__( + self, + dim: int, + window_size: list[int], + shift_size: list[int], + num_heads: int, + qkv_bias: bool = True, + proj_bias: bool = True, + attention_dropout: float = 0.0, + dropout: float = 0.0, + ): + super().__init__( + dim, + window_size, + shift_size, + num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attention_dropout=attention_dropout, + dropout=dropout, + ) + + self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1)))) + # mlp to generate continuous relative position bias + self.cpb_mlp = nn.Sequential( + nn.Linear(2, 512, bias=True), nn.ReLU(inplace=True), nn.Linear(512, num_heads, bias=False) + ) + if qkv_bias: + length = self.qkv.bias.numel() // 3 + self.qkv.bias[length : 2 * length].data.zero_() + + def define_relative_position_bias_table(self): + # get relative_coords_table + relative_coords_h = torch.arange(-(self.window_size[0] - 1), self.window_size[0], dtype=torch.float32) + relative_coords_w = torch.arange(-(self.window_size[1] - 1), self.window_size[1], dtype=torch.float32) + relative_coords_table = torch.stack(torch.meshgrid([relative_coords_h, relative_coords_w], indexing="ij")) + relative_coords_table = relative_coords_table.permute(1, 2, 0).contiguous().unsqueeze(0) # 1, 2*Wh-1, 2*Ww-1, 2 + + relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1 + relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1 + + relative_coords_table *= 8 # normalize to -8, 8 + relative_coords_table = ( + torch.sign(relative_coords_table) * torch.log2(torch.abs(relative_coords_table) + 1.0) / 3.0 + ) + self.register_buffer("relative_coords_table", relative_coords_table) + + def get_relative_position_bias(self) -> torch.Tensor: + relative_position_bias = _get_relative_position_bias( + self.cpb_mlp(self.relative_coords_table).view(-1, self.num_heads), + self.relative_position_index, # type: ignore[arg-type] + self.window_size, + ) + relative_position_bias = 16 * torch.sigmoid(relative_position_bias) + return relative_position_bias + + def forward(self, x: Tensor): + """ + Args: + x (Tensor): Tensor with layout of [B, H, W, C] + Returns: + Tensor with same layout as input, i.e. [B, H, W, C] + """ + relative_position_bias = self.get_relative_position_bias() + return shifted_window_attention( + x, + self.qkv.weight, + self.proj.weight, + relative_position_bias, + self.window_size, + self.num_heads, + shift_size=self.shift_size, + attention_dropout=self.attention_dropout, + dropout=self.dropout, + qkv_bias=self.qkv.bias, + proj_bias=self.proj.bias, + logit_scale=self.logit_scale, + training=self.training, + ) + + +class SwinTransformerBlock(nn.Module): + """ + Swin Transformer Block. + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (List[int]): Window size. + shift_size (List[int]): Shift size for shifted window attention. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob: (float): Stochastic depth rate. Default: 0.0. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + attn_layer (nn.Module): Attention layer. Default: ShiftedWindowAttention + """ + + def __init__( + self, + dim: int, + num_heads: int, + window_size: list[int], + shift_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_layer: Callable[..., nn.Module] = ShiftedWindowAttention, + ): + super().__init__() + _log_api_usage_once(self) + + self.norm1 = norm_layer(dim) + self.attn = attn_layer( + dim, + window_size, + shift_size, + num_heads, + attention_dropout=attention_dropout, + dropout=dropout, + ) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + self.norm2 = norm_layer(dim) + self.mlp = MLP(dim, [int(dim * mlp_ratio), dim], activation_layer=nn.GELU, inplace=None, dropout=dropout) + + for m in self.mlp.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.normal_(m.bias, std=1e-6) + + def forward(self, x: Tensor): + x = x + self.stochastic_depth(self.attn(self.norm1(x))) + x = x + self.stochastic_depth(self.mlp(self.norm2(x))) + return x + + +class SwinTransformerBlockV2(SwinTransformerBlock): + """ + Swin Transformer V2 Block. + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (List[int]): Window size. + shift_size (List[int]): Shift size for shifted window attention. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob: (float): Stochastic depth rate. Default: 0.0. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + attn_layer (nn.Module): Attention layer. Default: ShiftedWindowAttentionV2. + """ + + def __init__( + self, + dim: int, + num_heads: int, + window_size: list[int], + shift_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_layer: Callable[..., nn.Module] = ShiftedWindowAttentionV2, + ): + super().__init__( + dim, + num_heads, + window_size, + shift_size, + mlp_ratio=mlp_ratio, + dropout=dropout, + attention_dropout=attention_dropout, + stochastic_depth_prob=stochastic_depth_prob, + norm_layer=norm_layer, + attn_layer=attn_layer, + ) + + def forward(self, x: Tensor): + # Here is the difference, we apply norm after the attention in V2. + # In V1 we applied norm before the attention. + x = x + self.stochastic_depth(self.norm1(self.attn(x))) + x = x + self.stochastic_depth(self.norm2(self.mlp(x))) + return x + + +class SwinTransformer(nn.Module): + """ + Implements Swin Transformer from the `"Swin Transformer: Hierarchical Vision Transformer using + Shifted Windows" `_ paper. + Args: + patch_size (List[int]): Patch size. + embed_dim (int): Patch embedding dimension. + depths (List(int)): Depth of each Swin Transformer layer. + num_heads (List(int)): Number of attention heads in different layers. + window_size (List[int]): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob (float): Stochastic depth rate. Default: 0.1. + num_classes (int): Number of classes for classification head. Default: 1000. + block (nn.Module, optional): SwinTransformer Block. Default: None. + norm_layer (nn.Module, optional): Normalization layer. Default: None. + downsample_layer (nn.Module): Downsample layer (patch merging). Default: PatchMerging. + """ + + def __init__( + self, + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.1, + num_classes: int = 1000, + norm_layer: Optional[Callable[..., nn.Module]] = None, + block: Optional[Callable[..., nn.Module]] = None, + downsample_layer: Callable[..., nn.Module] = PatchMerging, + ): + super().__init__() + _log_api_usage_once(self) + self.num_classes = num_classes + + if block is None: + block = SwinTransformerBlock + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-5) + + layers: list[nn.Module] = [] + # split image into non-overlapping patches + layers.append( + nn.Sequential( + nn.Conv2d( + 3, embed_dim, kernel_size=(patch_size[0], patch_size[1]), stride=(patch_size[0], patch_size[1]) + ), + Permute([0, 2, 3, 1]), + norm_layer(embed_dim), + ) + ) + + total_stage_blocks = sum(depths) + stage_block_id = 0 + # build SwinTransformer blocks + for i_stage in range(len(depths)): + stage: list[nn.Module] = [] + dim = embed_dim * 2**i_stage + for i_layer in range(depths[i_stage]): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * float(stage_block_id) / (total_stage_blocks - 1) + stage.append( + block( + dim, + num_heads[i_stage], + window_size=window_size, + shift_size=[0 if i_layer % 2 == 0 else w // 2 for w in window_size], + mlp_ratio=mlp_ratio, + dropout=dropout, + attention_dropout=attention_dropout, + stochastic_depth_prob=sd_prob, + norm_layer=norm_layer, + ) + ) + stage_block_id += 1 + layers.append(nn.Sequential(*stage)) + # add patch merging layer + if i_stage < (len(depths) - 1): + layers.append(downsample_layer(dim, norm_layer)) + self.features = nn.Sequential(*layers) + + num_features = embed_dim * 2 ** (len(depths) - 1) + self.norm = norm_layer(num_features) + self.permute = Permute([0, 3, 1, 2]) # B H W C -> B C H W + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.flatten = nn.Flatten(1) + self.head = nn.Linear(num_features, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + def forward(self, x): + x = self.features(x) + x = self.norm(x) + x = self.permute(x) + x = self.avgpool(x) + x = self.flatten(x) + x = self.head(x) + return x + + +def _swin_transformer( + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> SwinTransformer: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = SwinTransformer( + patch_size=patch_size, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + stochastic_depth_prob=stochastic_depth_prob, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "categories": _IMAGENET_CATEGORIES, +} + + +class Swin_T_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_t-704ceda3.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=232, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 28288354, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.474, + "acc@5": 95.776, + } + }, + "_ops": 4.491, + "_file_size": 108.19, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_S_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_s-5e29d889.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=246, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 49606258, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.196, + "acc@5": 96.360, + } + }, + "_ops": 8.741, + "_file_size": 189.786, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_B_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_b-68c6b09e.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=238, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 87768224, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.582, + "acc@5": 96.640, + } + }, + "_ops": 15.431, + "_file_size": 335.364, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_V2_T_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_v2_t-b137f0e2.pth", + transforms=partial( + ImageClassification, crop_size=256, resize_size=260, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 28351570, + "min_size": (256, 256), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer-v2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.072, + "acc@5": 96.132, + } + }, + "_ops": 5.94, + "_file_size": 108.626, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_V2_S_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_v2_s-637d8ceb.pth", + transforms=partial( + ImageClassification, crop_size=256, resize_size=260, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 49737442, + "min_size": (256, 256), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer-v2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.712, + "acc@5": 96.816, + } + }, + "_ops": 11.546, + "_file_size": 190.675, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_V2_B_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_v2_b-781e5279.pth", + transforms=partial( + ImageClassification, crop_size=256, resize_size=272, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 87930848, + "min_size": (256, 256), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer-v2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.112, + "acc@5": 96.864, + } + }, + "_ops": 20.325, + "_file_size": 336.372, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_T_Weights.IMAGENET1K_V1)) +def swin_t(*, weights: Optional[Swin_T_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_tiny architecture from + `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_. + + Args: + weights (:class:`~torchvision.models.Swin_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_T_Weights + :members: + """ + weights = Swin_T_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=[7, 7], + stochastic_depth_prob=0.2, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_S_Weights.IMAGENET1K_V1)) +def swin_s(*, weights: Optional[Swin_S_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_small architecture from + `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_. + + Args: + weights (:class:`~torchvision.models.Swin_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_S_Weights + :members: + """ + weights = Swin_S_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 18, 2], + num_heads=[3, 6, 12, 24], + window_size=[7, 7], + stochastic_depth_prob=0.3, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_B_Weights.IMAGENET1K_V1)) +def swin_b(*, weights: Optional[Swin_B_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_base architecture from + `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_. + + Args: + weights (:class:`~torchvision.models.Swin_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_B_Weights + :members: + """ + weights = Swin_B_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=128, + depths=[2, 2, 18, 2], + num_heads=[4, 8, 16, 32], + window_size=[7, 7], + stochastic_depth_prob=0.5, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_V2_T_Weights.IMAGENET1K_V1)) +def swin_v2_t(*, weights: Optional[Swin_V2_T_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_v2_tiny architecture from + `Swin Transformer V2: Scaling Up Capacity and Resolution `_. + + Args: + weights (:class:`~torchvision.models.Swin_V2_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_V2_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_V2_T_Weights + :members: + """ + weights = Swin_V2_T_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 8], + stochastic_depth_prob=0.2, + weights=weights, + progress=progress, + block=SwinTransformerBlockV2, + downsample_layer=PatchMergingV2, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_V2_S_Weights.IMAGENET1K_V1)) +def swin_v2_s(*, weights: Optional[Swin_V2_S_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_v2_small architecture from + `Swin Transformer V2: Scaling Up Capacity and Resolution `_. + + Args: + weights (:class:`~torchvision.models.Swin_V2_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_V2_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_V2_S_Weights + :members: + """ + weights = Swin_V2_S_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 18, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 8], + stochastic_depth_prob=0.3, + weights=weights, + progress=progress, + block=SwinTransformerBlockV2, + downsample_layer=PatchMergingV2, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_V2_B_Weights.IMAGENET1K_V1)) +def swin_v2_b(*, weights: Optional[Swin_V2_B_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_v2_base architecture from + `Swin Transformer V2: Scaling Up Capacity and Resolution `_. + + Args: + weights (:class:`~torchvision.models.Swin_V2_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_V2_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_V2_B_Weights + :members: + """ + weights = Swin_V2_B_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=128, + depths=[2, 2, 18, 2], + num_heads=[4, 8, 16, 32], + window_size=[8, 8], + stochastic_depth_prob=0.5, + weights=weights, + progress=progress, + block=SwinTransformerBlockV2, + downsample_layer=PatchMergingV2, + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/vgg.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/vgg.py new file mode 100644 index 0000000000000000000000000000000000000000..feed0ce8d77ed53cfdca222b11d5c694dae4b104 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/vgg.py @@ -0,0 +1,511 @@ +from functools import partial +from typing import Any, cast, Optional, Union + +import torch +import torch.nn as nn + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "VGG", + "VGG11_Weights", + "VGG11_BN_Weights", + "VGG13_Weights", + "VGG13_BN_Weights", + "VGG16_Weights", + "VGG16_BN_Weights", + "VGG19_Weights", + "VGG19_BN_Weights", + "vgg11", + "vgg11_bn", + "vgg13", + "vgg13_bn", + "vgg16", + "vgg16_bn", + "vgg19", + "vgg19_bn", +] + + +class VGG(nn.Module): + def __init__( + self, features: nn.Module, num_classes: int = 1000, init_weights: bool = True, dropout: float = 0.5 + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.features = features + self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) + self.classifier = nn.Sequential( + nn.Linear(512 * 7 * 7, 4096), + nn.ReLU(True), + nn.Dropout(p=dropout), + nn.Linear(4096, 4096), + nn.ReLU(True), + nn.Dropout(p=dropout), + nn.Linear(4096, num_classes), + ) + if init_weights: + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.constant_(m.bias, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.classifier(x) + return x + + +def make_layers(cfg: list[Union[str, int]], batch_norm: bool = False) -> nn.Sequential: + layers: list[nn.Module] = [] + in_channels = 3 + for v in cfg: + if v == "M": + layers += [nn.MaxPool2d(kernel_size=2, stride=2)] + else: + v = cast(int, v) + conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) + if batch_norm: + layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] + else: + layers += [conv2d, nn.ReLU(inplace=True)] + in_channels = v + return nn.Sequential(*layers) + + +cfgs: dict[str, list[Union[str, int]]] = { + "A": [64, "M", 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], + "B": [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], + "D": [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"], + "E": [64, 64, "M", 128, 128, "M", 256, 256, 256, 256, "M", 512, 512, 512, 512, "M", 512, 512, 512, 512, "M"], +} + + +def _vgg(cfg: str, batch_norm: bool, weights: Optional[WeightsEnum], progress: bool, **kwargs: Any) -> VGG: + if weights is not None: + kwargs["init_weights"] = False + if weights.meta["categories"] is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs) + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + return model + + +_COMMON_META = { + "min_size": (32, 32), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#alexnet-and-vgg", + "_docs": """These weights were trained from scratch by using a simplified training recipe.""", +} + + +class VGG11_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg11-8a719046.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 132863336, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.020, + "acc@5": 88.628, + } + }, + "_ops": 7.609, + "_file_size": 506.84, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG11_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg11_bn-6002323d.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 132868840, + "_metrics": { + "ImageNet-1K": { + "acc@1": 70.370, + "acc@5": 89.810, + } + }, + "_ops": 7.609, + "_file_size": 506.881, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG13_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg13-19584684.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 133047848, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.928, + "acc@5": 89.246, + } + }, + "_ops": 11.308, + "_file_size": 507.545, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG13_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg13_bn-abd245e5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 133053736, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.586, + "acc@5": 90.374, + } + }, + "_ops": 11.308, + "_file_size": 507.59, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG16_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg16-397923af.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 138357544, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.592, + "acc@5": 90.382, + } + }, + "_ops": 15.47, + "_file_size": 527.796, + }, + ) + IMAGENET1K_FEATURES = Weights( + # Weights ported from https://github.com/amdegroot/ssd.pytorch/ + url="https://download.pytorch.org/models/vgg16_features-amdegroot-88682ab5.pth", + transforms=partial( + ImageClassification, + crop_size=224, + mean=(0.48235, 0.45882, 0.40784), + std=(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0), + ), + meta={ + **_COMMON_META, + "num_params": 138357544, + "categories": None, + "recipe": "https://github.com/amdegroot/ssd.pytorch#training-ssd", + "_metrics": { + "ImageNet-1K": { + "acc@1": float("nan"), + "acc@5": float("nan"), + } + }, + "_ops": 15.47, + "_file_size": 527.802, + "_docs": """ + These weights can't be used for classification because they are missing values in the `classifier` + module. Only the `features` module has valid values and can be used for feature extraction. The weights + were trained using the original input standardization method as described in the paper. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG16_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg16_bn-6c64b313.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 138365992, + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.360, + "acc@5": 91.516, + } + }, + "_ops": 15.47, + "_file_size": 527.866, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG19_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg19-dcbb9e9d.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 143667240, + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.376, + "acc@5": 90.876, + } + }, + "_ops": 19.632, + "_file_size": 548.051, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG19_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg19_bn-c79401a0.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 143678248, + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.218, + "acc@5": 91.842, + } + }, + "_ops": 19.632, + "_file_size": 548.143, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG11_Weights.IMAGENET1K_V1)) +def vgg11(*, weights: Optional[VGG11_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-11 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG11_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG11_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG11_Weights + :members: + """ + weights = VGG11_Weights.verify(weights) + + return _vgg("A", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG11_BN_Weights.IMAGENET1K_V1)) +def vgg11_bn(*, weights: Optional[VGG11_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-11-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG11_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG11_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG11_BN_Weights + :members: + """ + weights = VGG11_BN_Weights.verify(weights) + + return _vgg("A", True, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG13_Weights.IMAGENET1K_V1)) +def vgg13(*, weights: Optional[VGG13_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-13 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG13_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG13_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG13_Weights + :members: + """ + weights = VGG13_Weights.verify(weights) + + return _vgg("B", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG13_BN_Weights.IMAGENET1K_V1)) +def vgg13_bn(*, weights: Optional[VGG13_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-13-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG13_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG13_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG13_BN_Weights + :members: + """ + weights = VGG13_BN_Weights.verify(weights) + + return _vgg("B", True, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG16_Weights.IMAGENET1K_V1)) +def vgg16(*, weights: Optional[VGG16_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-16 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG16_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG16_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG16_Weights + :members: + """ + weights = VGG16_Weights.verify(weights) + + return _vgg("D", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG16_BN_Weights.IMAGENET1K_V1)) +def vgg16_bn(*, weights: Optional[VGG16_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-16-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG16_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG16_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG16_BN_Weights + :members: + """ + weights = VGG16_BN_Weights.verify(weights) + + return _vgg("D", True, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG19_Weights.IMAGENET1K_V1)) +def vgg19(*, weights: Optional[VGG19_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-19 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG19_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG19_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG19_Weights + :members: + """ + weights = VGG19_Weights.verify(weights) + + return _vgg("E", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG19_BN_Weights.IMAGENET1K_V1)) +def vgg19_bn(*, weights: Optional[VGG19_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-19_BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG19_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG19_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG19_BN_Weights + :members: + """ + weights = VGG19_BN_Weights.verify(weights) + + return _vgg("E", True, weights, progress, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1eedd3116001af22ec202d2ccec6eefad8090ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/__init__.py @@ -0,0 +1,4 @@ +from .mvit import * +from .resnet import * +from .s3d import * +from .swin_transformer import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/mvit.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/mvit.py new file mode 100644 index 0000000000000000000000000000000000000000..64d6d171b75d4f6a316e0ff4b80aa94efeb49294 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/mvit.py @@ -0,0 +1,898 @@ +import math +from collections.abc import Sequence +from dataclasses import dataclass +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.fx +import torch.nn as nn + +from ...ops import MLP, StochasticDepth +from ...transforms._presets import VideoClassification +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "MViT", + "MViT_V1_B_Weights", + "mvit_v1_b", + "MViT_V2_S_Weights", + "mvit_v2_s", +] + + +@dataclass +class MSBlockConfig: + num_heads: int + input_channels: int + output_channels: int + kernel_q: list[int] + kernel_kv: list[int] + stride_q: list[int] + stride_kv: list[int] + + +def _prod(s: Sequence[int]) -> int: + product = 1 + for v in s: + product *= v + return product + + +def _unsqueeze(x: torch.Tensor, target_dim: int, expand_dim: int) -> tuple[torch.Tensor, int]: + tensor_dim = x.dim() + if tensor_dim == target_dim - 1: + x = x.unsqueeze(expand_dim) + elif tensor_dim != target_dim: + raise ValueError(f"Unsupported input dimension {x.shape}") + return x, tensor_dim + + +def _squeeze(x: torch.Tensor, target_dim: int, expand_dim: int, tensor_dim: int) -> torch.Tensor: + if tensor_dim == target_dim - 1: + x = x.squeeze(expand_dim) + return x + + +torch.fx.wrap("_unsqueeze") +torch.fx.wrap("_squeeze") + + +class Pool(nn.Module): + def __init__( + self, + pool: nn.Module, + norm: Optional[nn.Module], + activation: Optional[nn.Module] = None, + norm_before_pool: bool = False, + ) -> None: + super().__init__() + self.pool = pool + layers = [] + if norm is not None: + layers.append(norm) + if activation is not None: + layers.append(activation) + self.norm_act = nn.Sequential(*layers) if layers else None + self.norm_before_pool = norm_before_pool + + def forward(self, x: torch.Tensor, thw: tuple[int, int, int]) -> tuple[torch.Tensor, tuple[int, int, int]]: + x, tensor_dim = _unsqueeze(x, 4, 1) + + # Separate the class token and reshape the input + class_token, x = torch.tensor_split(x, indices=(1,), dim=2) + x = x.transpose(2, 3) + B, N, C = x.shape[:3] + x = x.reshape((B * N, C) + thw).contiguous() + + # normalizing prior pooling is useful when we use BN which can be absorbed to speed up inference + if self.norm_before_pool and self.norm_act is not None: + x = self.norm_act(x) + + # apply the pool on the input and add back the token + x = self.pool(x) + T, H, W = x.shape[2:] + x = x.reshape(B, N, C, -1).transpose(2, 3) + x = torch.cat((class_token, x), dim=2) + + if not self.norm_before_pool and self.norm_act is not None: + x = self.norm_act(x) + + x = _squeeze(x, 4, 1, tensor_dim) + return x, (T, H, W) + + +def _interpolate(embedding: torch.Tensor, d: int) -> torch.Tensor: + if embedding.shape[0] == d: + return embedding + + return ( + nn.functional.interpolate( + embedding.permute(1, 0).unsqueeze(0), + size=d, + mode="linear", + ) + .squeeze(0) + .permute(1, 0) + ) + + +def _add_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + q_thw: tuple[int, int, int], + k_thw: tuple[int, int, int], + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + rel_pos_t: torch.Tensor, +) -> torch.Tensor: + # Modified code from: https://github.com/facebookresearch/SlowFast/commit/1aebd71a2efad823d52b827a3deaf15a56cf4932 + q_t, q_h, q_w = q_thw + k_t, k_h, k_w = k_thw + dh = int(2 * max(q_h, k_h) - 1) + dw = int(2 * max(q_w, k_w) - 1) + dt = int(2 * max(q_t, k_t) - 1) + + # Scale up rel pos if shapes for q and k are different. + q_h_ratio = max(k_h / q_h, 1.0) + k_h_ratio = max(q_h / k_h, 1.0) + dist_h = torch.arange(q_h)[:, None] * q_h_ratio - (torch.arange(k_h)[None, :] + (1.0 - k_h)) * k_h_ratio + q_w_ratio = max(k_w / q_w, 1.0) + k_w_ratio = max(q_w / k_w, 1.0) + dist_w = torch.arange(q_w)[:, None] * q_w_ratio - (torch.arange(k_w)[None, :] + (1.0 - k_w)) * k_w_ratio + q_t_ratio = max(k_t / q_t, 1.0) + k_t_ratio = max(q_t / k_t, 1.0) + dist_t = torch.arange(q_t)[:, None] * q_t_ratio - (torch.arange(k_t)[None, :] + (1.0 - k_t)) * k_t_ratio + + # Interpolate rel pos if needed. + rel_pos_h = _interpolate(rel_pos_h, dh) + rel_pos_w = _interpolate(rel_pos_w, dw) + rel_pos_t = _interpolate(rel_pos_t, dt) + Rh = rel_pos_h[dist_h.long()] + Rw = rel_pos_w[dist_w.long()] + Rt = rel_pos_t[dist_t.long()] + + B, n_head, _, dim = q.shape + + r_q = q[:, :, 1:].reshape(B, n_head, q_t, q_h, q_w, dim) + rel_h_q = torch.einsum("bythwc,hkc->bythwk", r_q, Rh) # [B, H, q_t, qh, qw, k_h] + rel_w_q = torch.einsum("bythwc,wkc->bythwk", r_q, Rw) # [B, H, q_t, qh, qw, k_w] + # [B, H, q_t, q_h, q_w, dim] -> [q_t, B, H, q_h, q_w, dim] -> [q_t, B*H*q_h*q_w, dim] + r_q = r_q.permute(2, 0, 1, 3, 4, 5).reshape(q_t, B * n_head * q_h * q_w, dim) + # [q_t, B*H*q_h*q_w, dim] * [q_t, dim, k_t] = [q_t, B*H*q_h*q_w, k_t] -> [B*H*q_h*q_w, q_t, k_t] + rel_q_t = torch.matmul(r_q, Rt.transpose(1, 2)).transpose(0, 1) + # [B*H*q_h*q_w, q_t, k_t] -> [B, H, q_t, q_h, q_w, k_t] + rel_q_t = rel_q_t.view(B, n_head, q_h, q_w, q_t, k_t).permute(0, 1, 4, 2, 3, 5) + + # Combine rel pos. + rel_pos = ( + rel_h_q[:, :, :, :, :, None, :, None] + + rel_w_q[:, :, :, :, :, None, None, :] + + rel_q_t[:, :, :, :, :, :, None, None] + ).reshape(B, n_head, q_t * q_h * q_w, k_t * k_h * k_w) + + # Add it to attention + attn[:, :, 1:, 1:] += rel_pos + + return attn + + +def _add_shortcut(x: torch.Tensor, shortcut: torch.Tensor, residual_with_cls_embed: bool): + if residual_with_cls_embed: + x.add_(shortcut) + else: + x[:, :, 1:, :] += shortcut[:, :, 1:, :] + return x + + +torch.fx.wrap("_add_rel_pos") +torch.fx.wrap("_add_shortcut") + + +class MultiscaleAttention(nn.Module): + def __init__( + self, + input_size: list[int], + embed_dim: int, + output_dim: int, + num_heads: int, + kernel_q: list[int], + kernel_kv: list[int], + stride_q: list[int], + stride_kv: list[int], + residual_pool: bool, + residual_with_cls_embed: bool, + rel_pos_embed: bool, + dropout: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + ) -> None: + super().__init__() + self.embed_dim = embed_dim + self.output_dim = output_dim + self.num_heads = num_heads + self.head_dim = output_dim // num_heads + self.scaler = 1.0 / math.sqrt(self.head_dim) + self.residual_pool = residual_pool + self.residual_with_cls_embed = residual_with_cls_embed + + self.qkv = nn.Linear(embed_dim, 3 * output_dim) + layers: list[nn.Module] = [nn.Linear(output_dim, output_dim)] + if dropout > 0.0: + layers.append(nn.Dropout(dropout, inplace=True)) + self.project = nn.Sequential(*layers) + + self.pool_q: Optional[nn.Module] = None + if _prod(kernel_q) > 1 or _prod(stride_q) > 1: + padding_q = [int(q // 2) for q in kernel_q] + self.pool_q = Pool( + nn.Conv3d( + self.head_dim, + self.head_dim, + kernel_q, # type: ignore[arg-type] + stride=stride_q, # type: ignore[arg-type] + padding=padding_q, # type: ignore[arg-type] + groups=self.head_dim, + bias=False, + ), + norm_layer(self.head_dim), + ) + + self.pool_k: Optional[nn.Module] = None + self.pool_v: Optional[nn.Module] = None + if _prod(kernel_kv) > 1 or _prod(stride_kv) > 1: + padding_kv = [int(kv // 2) for kv in kernel_kv] + self.pool_k = Pool( + nn.Conv3d( + self.head_dim, + self.head_dim, + kernel_kv, # type: ignore[arg-type] + stride=stride_kv, # type: ignore[arg-type] + padding=padding_kv, # type: ignore[arg-type] + groups=self.head_dim, + bias=False, + ), + norm_layer(self.head_dim), + ) + self.pool_v = Pool( + nn.Conv3d( + self.head_dim, + self.head_dim, + kernel_kv, # type: ignore[arg-type] + stride=stride_kv, # type: ignore[arg-type] + padding=padding_kv, # type: ignore[arg-type] + groups=self.head_dim, + bias=False, + ), + norm_layer(self.head_dim), + ) + + self.rel_pos_h: Optional[nn.Parameter] = None + self.rel_pos_w: Optional[nn.Parameter] = None + self.rel_pos_t: Optional[nn.Parameter] = None + if rel_pos_embed: + size = max(input_size[1:]) + q_size = size // stride_q[1] if len(stride_q) > 0 else size + kv_size = size // stride_kv[1] if len(stride_kv) > 0 else size + spatial_dim = 2 * max(q_size, kv_size) - 1 + temporal_dim = 2 * input_size[0] - 1 + self.rel_pos_h = nn.Parameter(torch.zeros(spatial_dim, self.head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(spatial_dim, self.head_dim)) + self.rel_pos_t = nn.Parameter(torch.zeros(temporal_dim, self.head_dim)) + nn.init.trunc_normal_(self.rel_pos_h, std=0.02) + nn.init.trunc_normal_(self.rel_pos_w, std=0.02) + nn.init.trunc_normal_(self.rel_pos_t, std=0.02) + + def forward(self, x: torch.Tensor, thw: tuple[int, int, int]) -> tuple[torch.Tensor, tuple[int, int, int]]: + B, N, C = x.shape + q, k, v = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).transpose(1, 3).unbind(dim=2) + + if self.pool_k is not None: + k, k_thw = self.pool_k(k, thw) + else: + k_thw = thw + if self.pool_v is not None: + v = self.pool_v(v, thw)[0] + if self.pool_q is not None: + q, thw = self.pool_q(q, thw) + + attn = torch.matmul(self.scaler * q, k.transpose(2, 3)) + if self.rel_pos_h is not None and self.rel_pos_w is not None and self.rel_pos_t is not None: + attn = _add_rel_pos( + attn, + q, + thw, + k_thw, + self.rel_pos_h, + self.rel_pos_w, + self.rel_pos_t, + ) + attn = attn.softmax(dim=-1) + + x = torch.matmul(attn, v) + if self.residual_pool: + _add_shortcut(x, q, self.residual_with_cls_embed) + x = x.transpose(1, 2).reshape(B, -1, self.output_dim) + x = self.project(x) + + return x, thw + + +class MultiscaleBlock(nn.Module): + def __init__( + self, + input_size: list[int], + cnf: MSBlockConfig, + residual_pool: bool, + residual_with_cls_embed: bool, + rel_pos_embed: bool, + proj_after_attn: bool, + dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + ) -> None: + super().__init__() + self.proj_after_attn = proj_after_attn + + self.pool_skip: Optional[nn.Module] = None + if _prod(cnf.stride_q) > 1: + kernel_skip = [s + 1 if s > 1 else s for s in cnf.stride_q] + padding_skip = [int(k // 2) for k in kernel_skip] + self.pool_skip = Pool( + nn.MaxPool3d(kernel_skip, stride=cnf.stride_q, padding=padding_skip), None # type: ignore[arg-type] + ) + + attn_dim = cnf.output_channels if proj_after_attn else cnf.input_channels + + self.norm1 = norm_layer(cnf.input_channels) + self.norm2 = norm_layer(attn_dim) + self.needs_transposal = isinstance(self.norm1, nn.BatchNorm1d) + + self.attn = MultiscaleAttention( + input_size, + cnf.input_channels, + attn_dim, + cnf.num_heads, + kernel_q=cnf.kernel_q, + kernel_kv=cnf.kernel_kv, + stride_q=cnf.stride_q, + stride_kv=cnf.stride_kv, + rel_pos_embed=rel_pos_embed, + residual_pool=residual_pool, + residual_with_cls_embed=residual_with_cls_embed, + dropout=dropout, + norm_layer=norm_layer, + ) + self.mlp = MLP( + attn_dim, + [4 * attn_dim, cnf.output_channels], + activation_layer=nn.GELU, + dropout=dropout, + inplace=None, + ) + + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + + self.project: Optional[nn.Module] = None + if cnf.input_channels != cnf.output_channels: + self.project = nn.Linear(cnf.input_channels, cnf.output_channels) + + def forward(self, x: torch.Tensor, thw: tuple[int, int, int]) -> tuple[torch.Tensor, tuple[int, int, int]]: + x_norm1 = self.norm1(x.transpose(1, 2)).transpose(1, 2) if self.needs_transposal else self.norm1(x) + x_attn, thw_new = self.attn(x_norm1, thw) + x = x if self.project is None or not self.proj_after_attn else self.project(x_norm1) + x_skip = x if self.pool_skip is None else self.pool_skip(x, thw)[0] + x = x_skip + self.stochastic_depth(x_attn) + + x_norm2 = self.norm2(x.transpose(1, 2)).transpose(1, 2) if self.needs_transposal else self.norm2(x) + x_proj = x if self.project is None or self.proj_after_attn else self.project(x_norm2) + + return x_proj + self.stochastic_depth(self.mlp(x_norm2)), thw_new + + +class PositionalEncoding(nn.Module): + def __init__(self, embed_size: int, spatial_size: tuple[int, int], temporal_size: int, rel_pos_embed: bool) -> None: + super().__init__() + self.spatial_size = spatial_size + self.temporal_size = temporal_size + + self.class_token = nn.Parameter(torch.zeros(embed_size)) + self.spatial_pos: Optional[nn.Parameter] = None + self.temporal_pos: Optional[nn.Parameter] = None + self.class_pos: Optional[nn.Parameter] = None + if not rel_pos_embed: + self.spatial_pos = nn.Parameter(torch.zeros(self.spatial_size[0] * self.spatial_size[1], embed_size)) + self.temporal_pos = nn.Parameter(torch.zeros(self.temporal_size, embed_size)) + self.class_pos = nn.Parameter(torch.zeros(embed_size)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + class_token = self.class_token.expand(x.size(0), -1).unsqueeze(1) + x = torch.cat((class_token, x), dim=1) + + if self.spatial_pos is not None and self.temporal_pos is not None and self.class_pos is not None: + hw_size, embed_size = self.spatial_pos.shape + pos_embedding = torch.repeat_interleave(self.temporal_pos, hw_size, dim=0) + pos_embedding.add_(self.spatial_pos.unsqueeze(0).expand(self.temporal_size, -1, -1).reshape(-1, embed_size)) + pos_embedding = torch.cat((self.class_pos.unsqueeze(0), pos_embedding), dim=0).unsqueeze(0) + x.add_(pos_embedding) + + return x + + +class MViT(nn.Module): + def __init__( + self, + spatial_size: tuple[int, int], + temporal_size: int, + block_setting: Sequence[MSBlockConfig], + residual_pool: bool, + residual_with_cls_embed: bool, + rel_pos_embed: bool, + proj_after_attn: bool, + dropout: float = 0.5, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + num_classes: int = 400, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + patch_embed_kernel: tuple[int, int, int] = (3, 7, 7), + patch_embed_stride: tuple[int, int, int] = (2, 4, 4), + patch_embed_padding: tuple[int, int, int] = (1, 3, 3), + ) -> None: + """ + MViT main class. + + Args: + spatial_size (tuple of ints): The spacial size of the input as ``(H, W)``. + temporal_size (int): The temporal size ``T`` of the input. + block_setting (sequence of MSBlockConfig): The Network structure. + residual_pool (bool): If True, use MViTv2 pooling residual connection. + residual_with_cls_embed (bool): If True, the addition on the residual connection will include + the class embedding. + rel_pos_embed (bool): If True, use MViTv2's relative positional embeddings. + proj_after_attn (bool): If True, apply the projection after the attention. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob: (float): Stochastic depth rate. Default: 0.0. + num_classes (int): The number of classes. + block (callable, optional): Module specifying the layer which consists of the attention and mlp. + norm_layer (callable, optional): Module specifying the normalization layer to use. + patch_embed_kernel (tuple of ints): The kernel of the convolution that patchifies the input. + patch_embed_stride (tuple of ints): The stride of the convolution that patchifies the input. + patch_embed_padding (tuple of ints): The padding of the convolution that patchifies the input. + """ + super().__init__() + # This implementation employs a different parameterization scheme than the one used at PyTorch Video: + # https://github.com/facebookresearch/pytorchvideo/blob/718d0a4/pytorchvideo/models/vision_transformers.py + # We remove any experimental configuration that didn't make it to the final variants of the models. To represent + # the configuration of the architecture we use the simplified form suggested at Table 1 of the paper. + _log_api_usage_once(self) + total_stage_blocks = len(block_setting) + if total_stage_blocks == 0: + raise ValueError("The configuration parameter can't be empty.") + + if block is None: + block = MultiscaleBlock + + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-6) + + # Patch Embedding module + self.conv_proj = nn.Conv3d( + in_channels=3, + out_channels=block_setting[0].input_channels, + kernel_size=patch_embed_kernel, + stride=patch_embed_stride, + padding=patch_embed_padding, + ) + + input_size = [size // stride for size, stride in zip((temporal_size,) + spatial_size, self.conv_proj.stride)] + + # Spatio-Temporal Class Positional Encoding + self.pos_encoding = PositionalEncoding( + embed_size=block_setting[0].input_channels, + spatial_size=(input_size[1], input_size[2]), + temporal_size=input_size[0], + rel_pos_embed=rel_pos_embed, + ) + + # Encoder module + self.blocks = nn.ModuleList() + for stage_block_id, cnf in enumerate(block_setting): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * stage_block_id / (total_stage_blocks - 1.0) + + self.blocks.append( + block( + input_size=input_size, + cnf=cnf, + residual_pool=residual_pool, + residual_with_cls_embed=residual_with_cls_embed, + rel_pos_embed=rel_pos_embed, + proj_after_attn=proj_after_attn, + dropout=attention_dropout, + stochastic_depth_prob=sd_prob, + norm_layer=norm_layer, + ) + ) + + if len(cnf.stride_q) > 0: + input_size = [size // stride for size, stride in zip(input_size, cnf.stride_q)] + self.norm = norm_layer(block_setting[-1].output_channels) + + # Classifier module + self.head = nn.Sequential( + nn.Dropout(dropout, inplace=True), + nn.Linear(block_setting[-1].output_channels, num_classes), + ) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0.0) + elif isinstance(m, nn.LayerNorm): + if m.weight is not None: + nn.init.constant_(m.weight, 1.0) + if m.bias is not None: + nn.init.constant_(m.bias, 0.0) + elif isinstance(m, PositionalEncoding): + for weights in m.parameters(): + nn.init.trunc_normal_(weights, std=0.02) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # Convert if necessary (B, C, H, W) -> (B, C, 1, H, W) + x = _unsqueeze(x, 5, 2)[0] + # patchify and reshape: (B, C, T, H, W) -> (B, embed_channels[0], T', H', W') -> (B, THW', embed_channels[0]) + x = self.conv_proj(x) + x = x.flatten(2).transpose(1, 2) + + # add positional encoding + x = self.pos_encoding(x) + + # pass patches through the encoder + thw = (self.pos_encoding.temporal_size,) + self.pos_encoding.spatial_size + for block in self.blocks: + x, thw = block(x, thw) + x = self.norm(x) + + # classifier "token" as used by standard language architectures + x = x[:, 0] + x = self.head(x) + + return x + + +def _mvit( + block_setting: list[MSBlockConfig], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> MViT: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + assert weights.meta["min_size"][0] == weights.meta["min_size"][1] + _ovewrite_named_param(kwargs, "spatial_size", weights.meta["min_size"]) + _ovewrite_named_param(kwargs, "temporal_size", weights.meta["min_temporal_size"]) + spatial_size = kwargs.pop("spatial_size", (224, 224)) + temporal_size = kwargs.pop("temporal_size", 16) + + model = MViT( + spatial_size=spatial_size, + temporal_size=temporal_size, + block_setting=block_setting, + residual_pool=kwargs.pop("residual_pool", False), + residual_with_cls_embed=kwargs.pop("residual_with_cls_embed", True), + rel_pos_embed=kwargs.pop("rel_pos_embed", False), + proj_after_attn=kwargs.pop("proj_after_attn", False), + stochastic_depth_prob=stochastic_depth_prob, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +class MViT_V1_B_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/mvit_v1_b-dbeb1030.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.45, 0.45, 0.45), + std=(0.225, 0.225, 0.225), + ), + meta={ + "min_size": (224, 224), + "min_temporal_size": 16, + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/facebookresearch/pytorchvideo/blob/main/docs/source/model_zoo.md", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=7.5`, `clips_per_video=5`, and `clip_len=16`" + ), + "num_params": 36610672, + "_metrics": { + "Kinetics-400": { + "acc@1": 78.477, + "acc@5": 93.582, + } + }, + "_ops": 70.599, + "_file_size": 139.764, + }, + ) + DEFAULT = KINETICS400_V1 + + +class MViT_V2_S_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/mvit_v2_s-ae3be167.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.45, 0.45, 0.45), + std=(0.225, 0.225, 0.225), + ), + meta={ + "min_size": (224, 224), + "min_temporal_size": 16, + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/facebookresearch/SlowFast/blob/main/MODEL_ZOO.md", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=7.5`, `clips_per_video=5`, and `clip_len=16`" + ), + "num_params": 34537744, + "_metrics": { + "Kinetics-400": { + "acc@1": 80.757, + "acc@5": 94.665, + } + }, + "_ops": 64.224, + "_file_size": 131.884, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MViT_V1_B_Weights.KINETICS400_V1)) +def mvit_v1_b(*, weights: Optional[MViT_V1_B_Weights] = None, progress: bool = True, **kwargs: Any) -> MViT: + """ + Constructs a base MViTV1 architecture from + `Multiscale Vision Transformers `__. + + .. betastatus:: video module + + Args: + weights (:class:`~torchvision.models.video.MViT_V1_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.MViT_V1_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.MViT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.MViT_V1_B_Weights + :members: + """ + weights = MViT_V1_B_Weights.verify(weights) + + config: dict[str, list] = { + "num_heads": [1, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8], + "input_channels": [96, 192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768, 768], + "output_channels": [192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768, 768, 768], + "kernel_q": [[], [3, 3, 3], [], [3, 3, 3], [], [], [], [], [], [], [], [], [], [], [3, 3, 3], []], + "kernel_kv": [ + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + ], + "stride_q": [[], [1, 2, 2], [], [1, 2, 2], [], [], [], [], [], [], [], [], [], [], [1, 2, 2], []], + "stride_kv": [ + [1, 8, 8], + [1, 4, 4], + [1, 4, 4], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 1, 1], + [1, 1, 1], + ], + } + + block_setting = [] + for i in range(len(config["num_heads"])): + block_setting.append( + MSBlockConfig( + num_heads=config["num_heads"][i], + input_channels=config["input_channels"][i], + output_channels=config["output_channels"][i], + kernel_q=config["kernel_q"][i], + kernel_kv=config["kernel_kv"][i], + stride_q=config["stride_q"][i], + stride_kv=config["stride_kv"][i], + ) + ) + + return _mvit( + spatial_size=(224, 224), + temporal_size=16, + block_setting=block_setting, + residual_pool=False, + residual_with_cls_embed=False, + stochastic_depth_prob=kwargs.pop("stochastic_depth_prob", 0.2), + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MViT_V2_S_Weights.KINETICS400_V1)) +def mvit_v2_s(*, weights: Optional[MViT_V2_S_Weights] = None, progress: bool = True, **kwargs: Any) -> MViT: + """Constructs a small MViTV2 architecture from + `Multiscale Vision Transformers `__ and + `MViTv2: Improved Multiscale Vision Transformers for Classification + and Detection `__. + + .. betastatus:: video module + + Args: + weights (:class:`~torchvision.models.video.MViT_V2_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.MViT_V2_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.MViT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.MViT_V2_S_Weights + :members: + """ + weights = MViT_V2_S_Weights.verify(weights) + + config: dict[str, list] = { + "num_heads": [1, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8], + "input_channels": [96, 96, 192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768], + "output_channels": [96, 192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768, 768], + "kernel_q": [ + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + ], + "kernel_kv": [ + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + ], + "stride_q": [ + [1, 1, 1], + [1, 2, 2], + [1, 1, 1], + [1, 2, 2], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 2, 2], + [1, 1, 1], + ], + "stride_kv": [ + [1, 8, 8], + [1, 4, 4], + [1, 4, 4], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 1, 1], + [1, 1, 1], + ], + } + + block_setting = [] + for i in range(len(config["num_heads"])): + block_setting.append( + MSBlockConfig( + num_heads=config["num_heads"][i], + input_channels=config["input_channels"][i], + output_channels=config["output_channels"][i], + kernel_q=config["kernel_q"][i], + kernel_kv=config["kernel_kv"][i], + stride_q=config["stride_q"][i], + stride_kv=config["stride_kv"][i], + ) + ) + + return _mvit( + spatial_size=(224, 224), + temporal_size=16, + block_setting=block_setting, + residual_pool=True, + residual_with_cls_embed=False, + rel_pos_embed=True, + proj_after_attn=True, + stochastic_depth_prob=kwargs.pop("stochastic_depth_prob", 0.2), + weights=weights, + progress=progress, + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/resnet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..43b0df48ffe35c055e63362031088d18c24a2dbe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/resnet.py @@ -0,0 +1,504 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch.nn as nn +from torch import Tensor + +from ...transforms._presets import VideoClassification +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "VideoResNet", + "R3D_18_Weights", + "MC3_18_Weights", + "R2Plus1D_18_Weights", + "r3d_18", + "mc3_18", + "r2plus1d_18", +] + + +class Conv3DSimple(nn.Conv3d): + def __init__( + self, in_planes: int, out_planes: int, midplanes: Optional[int] = None, stride: int = 1, padding: int = 1 + ) -> None: + + super().__init__( + in_channels=in_planes, + out_channels=out_planes, + kernel_size=(3, 3, 3), + stride=stride, + padding=padding, + bias=False, + ) + + @staticmethod + def get_downsample_stride(stride: int) -> tuple[int, int, int]: + return stride, stride, stride + + +class Conv2Plus1D(nn.Sequential): + def __init__(self, in_planes: int, out_planes: int, midplanes: int, stride: int = 1, padding: int = 1) -> None: + super().__init__( + nn.Conv3d( + in_planes, + midplanes, + kernel_size=(1, 3, 3), + stride=(1, stride, stride), + padding=(0, padding, padding), + bias=False, + ), + nn.BatchNorm3d(midplanes), + nn.ReLU(inplace=True), + nn.Conv3d( + midplanes, out_planes, kernel_size=(3, 1, 1), stride=(stride, 1, 1), padding=(padding, 0, 0), bias=False + ), + ) + + @staticmethod + def get_downsample_stride(stride: int) -> tuple[int, int, int]: + return stride, stride, stride + + +class Conv3DNoTemporal(nn.Conv3d): + def __init__( + self, in_planes: int, out_planes: int, midplanes: Optional[int] = None, stride: int = 1, padding: int = 1 + ) -> None: + + super().__init__( + in_channels=in_planes, + out_channels=out_planes, + kernel_size=(1, 3, 3), + stride=(1, stride, stride), + padding=(0, padding, padding), + bias=False, + ) + + @staticmethod + def get_downsample_stride(stride: int) -> tuple[int, int, int]: + return 1, stride, stride + + +class BasicBlock(nn.Module): + + expansion = 1 + + def __init__( + self, + inplanes: int, + planes: int, + conv_builder: Callable[..., nn.Module], + stride: int = 1, + downsample: Optional[nn.Module] = None, + ) -> None: + midplanes = (inplanes * planes * 3 * 3 * 3) // (inplanes * 3 * 3 + 3 * planes) + + super().__init__() + self.conv1 = nn.Sequential( + conv_builder(inplanes, planes, midplanes, stride), nn.BatchNorm3d(planes), nn.ReLU(inplace=True) + ) + self.conv2 = nn.Sequential(conv_builder(planes, planes, midplanes), nn.BatchNorm3d(planes)) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + residual = x + + out = self.conv1(x) + out = self.conv2(out) + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__( + self, + inplanes: int, + planes: int, + conv_builder: Callable[..., nn.Module], + stride: int = 1, + downsample: Optional[nn.Module] = None, + ) -> None: + + super().__init__() + midplanes = (inplanes * planes * 3 * 3 * 3) // (inplanes * 3 * 3 + 3 * planes) + + # 1x1x1 + self.conv1 = nn.Sequential( + nn.Conv3d(inplanes, planes, kernel_size=1, bias=False), nn.BatchNorm3d(planes), nn.ReLU(inplace=True) + ) + # Second kernel + self.conv2 = nn.Sequential( + conv_builder(planes, planes, midplanes, stride), nn.BatchNorm3d(planes), nn.ReLU(inplace=True) + ) + + # 1x1x1 + self.conv3 = nn.Sequential( + nn.Conv3d(planes, planes * self.expansion, kernel_size=1, bias=False), + nn.BatchNorm3d(planes * self.expansion), + ) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + residual = x + + out = self.conv1(x) + out = self.conv2(out) + out = self.conv3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class BasicStem(nn.Sequential): + """The default conv-batchnorm-relu stem""" + + def __init__(self) -> None: + super().__init__( + nn.Conv3d(3, 64, kernel_size=(3, 7, 7), stride=(1, 2, 2), padding=(1, 3, 3), bias=False), + nn.BatchNorm3d(64), + nn.ReLU(inplace=True), + ) + + +class R2Plus1dStem(nn.Sequential): + """R(2+1)D stem is different than the default one as it uses separated 3D convolution""" + + def __init__(self) -> None: + super().__init__( + nn.Conv3d(3, 45, kernel_size=(1, 7, 7), stride=(1, 2, 2), padding=(0, 3, 3), bias=False), + nn.BatchNorm3d(45), + nn.ReLU(inplace=True), + nn.Conv3d(45, 64, kernel_size=(3, 1, 1), stride=(1, 1, 1), padding=(1, 0, 0), bias=False), + nn.BatchNorm3d(64), + nn.ReLU(inplace=True), + ) + + +class VideoResNet(nn.Module): + def __init__( + self, + block: type[Union[BasicBlock, Bottleneck]], + conv_makers: Sequence[type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]]], + layers: list[int], + stem: Callable[..., nn.Module], + num_classes: int = 400, + zero_init_residual: bool = False, + ) -> None: + """Generic resnet video generator. + + Args: + block (Type[Union[BasicBlock, Bottleneck]]): resnet building block + conv_makers (List[Type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]]]): generator + function for each layer + layers (List[int]): number of blocks per layer + stem (Callable[..., nn.Module]): module specifying the ResNet stem. + num_classes (int, optional): Dimension of the final FC layer. Defaults to 400. + zero_init_residual (bool, optional): Zero init bottleneck residual BN. Defaults to False. + """ + super().__init__() + _log_api_usage_once(self) + self.inplanes = 64 + + self.stem = stem() + + self.layer1 = self._make_layer(block, conv_makers[0], 64, layers[0], stride=1) + self.layer2 = self._make_layer(block, conv_makers[1], 128, layers[1], stride=2) + self.layer3 = self._make_layer(block, conv_makers[2], 256, layers[2], stride=2) + self.layer4 = self._make_layer(block, conv_makers[3], 512, layers[3], stride=2) + + self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1)) + self.fc = nn.Linear(512 * block.expansion, num_classes) + + # init weights + for m in self.modules(): + if isinstance(m, nn.Conv3d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm3d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.constant_(m.bias, 0) + + if zero_init_residual: + for m in self.modules(): + if isinstance(m, Bottleneck): + nn.init.constant_(m.bn3.weight, 0) # type: ignore[union-attr, arg-type] + + def forward(self, x: Tensor) -> Tensor: + x = self.stem(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + x = self.avgpool(x) + # Flatten the layer to fc + x = x.flatten(1) + x = self.fc(x) + + return x + + def _make_layer( + self, + block: type[Union[BasicBlock, Bottleneck]], + conv_builder: type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]], + planes: int, + blocks: int, + stride: int = 1, + ) -> nn.Sequential: + downsample = None + + if stride != 1 or self.inplanes != planes * block.expansion: + ds_stride = conv_builder.get_downsample_stride(stride) + downsample = nn.Sequential( + nn.Conv3d(self.inplanes, planes * block.expansion, kernel_size=1, stride=ds_stride, bias=False), + nn.BatchNorm3d(planes * block.expansion), + ) + layers = [] + layers.append(block(self.inplanes, planes, conv_builder, stride, downsample)) + + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes, conv_builder)) + + return nn.Sequential(*layers) + + +def _video_resnet( + block: type[Union[BasicBlock, Bottleneck]], + conv_makers: Sequence[type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]]], + layers: list[int], + stem: Callable[..., nn.Module], + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> VideoResNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = VideoResNet(block, conv_makers, layers, stem, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/video_classification", + "_docs": ( + "The weights reproduce closely the accuracy of the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=5`, and `clip_len=16`." + ), +} + + +class R3D_18_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/r3d_18-b3b3357e.pth", + transforms=partial(VideoClassification, crop_size=(112, 112), resize_size=(128, 171)), + meta={ + **_COMMON_META, + "num_params": 33371472, + "_metrics": { + "Kinetics-400": { + "acc@1": 63.200, + "acc@5": 83.479, + } + }, + "_ops": 40.697, + "_file_size": 127.359, + }, + ) + DEFAULT = KINETICS400_V1 + + +class MC3_18_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/mc3_18-a90a0ba3.pth", + transforms=partial(VideoClassification, crop_size=(112, 112), resize_size=(128, 171)), + meta={ + **_COMMON_META, + "num_params": 11695440, + "_metrics": { + "Kinetics-400": { + "acc@1": 63.960, + "acc@5": 84.130, + } + }, + "_ops": 43.343, + "_file_size": 44.672, + }, + ) + DEFAULT = KINETICS400_V1 + + +class R2Plus1D_18_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/r2plus1d_18-91a641e6.pth", + transforms=partial(VideoClassification, crop_size=(112, 112), resize_size=(128, 171)), + meta={ + **_COMMON_META, + "num_params": 31505325, + "_metrics": { + "Kinetics-400": { + "acc@1": 67.463, + "acc@5": 86.175, + } + }, + "_ops": 40.519, + "_file_size": 120.318, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", R3D_18_Weights.KINETICS400_V1)) +def r3d_18(*, weights: Optional[R3D_18_Weights] = None, progress: bool = True, **kwargs: Any) -> VideoResNet: + """Construct 18 layer Resnet3D model. + + .. betastatus:: video module + + Reference: `A Closer Look at Spatiotemporal Convolutions for Action Recognition `__. + + Args: + weights (:class:`~torchvision.models.video.R3D_18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.R3D_18_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.resnet.VideoResNet`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.R3D_18_Weights + :members: + """ + weights = R3D_18_Weights.verify(weights) + + return _video_resnet( + BasicBlock, + [Conv3DSimple] * 4, + [2, 2, 2, 2], + BasicStem, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MC3_18_Weights.KINETICS400_V1)) +def mc3_18(*, weights: Optional[MC3_18_Weights] = None, progress: bool = True, **kwargs: Any) -> VideoResNet: + """Construct 18 layer Mixed Convolution network as in + + .. betastatus:: video module + + Reference: `A Closer Look at Spatiotemporal Convolutions for Action Recognition `__. + + Args: + weights (:class:`~torchvision.models.video.MC3_18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.MC3_18_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.resnet.VideoResNet`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.MC3_18_Weights + :members: + """ + weights = MC3_18_Weights.verify(weights) + + return _video_resnet( + BasicBlock, + [Conv3DSimple] + [Conv3DNoTemporal] * 3, # type: ignore[list-item] + [2, 2, 2, 2], + BasicStem, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", R2Plus1D_18_Weights.KINETICS400_V1)) +def r2plus1d_18(*, weights: Optional[R2Plus1D_18_Weights] = None, progress: bool = True, **kwargs: Any) -> VideoResNet: + """Construct 18 layer deep R(2+1)D network as in + + .. betastatus:: video module + + Reference: `A Closer Look at Spatiotemporal Convolutions for Action Recognition `__. + + Args: + weights (:class:`~torchvision.models.video.R2Plus1D_18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.R2Plus1D_18_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.resnet.VideoResNet`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.R2Plus1D_18_Weights + :members: + """ + weights = R2Plus1D_18_Weights.verify(weights) + + return _video_resnet( + BasicBlock, + [Conv2Plus1D] * 4, + [2, 2, 2, 2], + R2Plus1dStem, + weights, + progress, + **kwargs, + ) + + +# The dictionary below is internal implementation detail and will be removed in v0.15 +from .._utils import _ModelURLs + + +model_urls = _ModelURLs( + { + "r3d_18": R3D_18_Weights.KINETICS400_V1.url, + "mc3_18": MC3_18_Weights.KINETICS400_V1.url, + "r2plus1d_18": R2Plus1D_18_Weights.KINETICS400_V1.url, + } +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/s3d.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/s3d.py new file mode 100644 index 0000000000000000000000000000000000000000..4b202829b24fb1dc314452d38a521dfe6c8e446f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/s3d.py @@ -0,0 +1,219 @@ +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn +from torchvision.ops.misc import Conv3dNormActivation + +from ...transforms._presets import VideoClassification +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "S3D", + "S3D_Weights", + "s3d", +] + + +class TemporalSeparableConv(nn.Sequential): + def __init__( + self, + in_planes: int, + out_planes: int, + kernel_size: int, + stride: int, + padding: int, + norm_layer: Callable[..., nn.Module], + ): + super().__init__( + Conv3dNormActivation( + in_planes, + out_planes, + kernel_size=(1, kernel_size, kernel_size), + stride=(1, stride, stride), + padding=(0, padding, padding), + bias=False, + norm_layer=norm_layer, + ), + Conv3dNormActivation( + out_planes, + out_planes, + kernel_size=(kernel_size, 1, 1), + stride=(stride, 1, 1), + padding=(padding, 0, 0), + bias=False, + norm_layer=norm_layer, + ), + ) + + +class SepInceptionBlock3D(nn.Module): + def __init__( + self, + in_planes: int, + b0_out: int, + b1_mid: int, + b1_out: int, + b2_mid: int, + b2_out: int, + b3_out: int, + norm_layer: Callable[..., nn.Module], + ): + super().__init__() + + self.branch0 = Conv3dNormActivation(in_planes, b0_out, kernel_size=1, stride=1, norm_layer=norm_layer) + self.branch1 = nn.Sequential( + Conv3dNormActivation(in_planes, b1_mid, kernel_size=1, stride=1, norm_layer=norm_layer), + TemporalSeparableConv(b1_mid, b1_out, kernel_size=3, stride=1, padding=1, norm_layer=norm_layer), + ) + self.branch2 = nn.Sequential( + Conv3dNormActivation(in_planes, b2_mid, kernel_size=1, stride=1, norm_layer=norm_layer), + TemporalSeparableConv(b2_mid, b2_out, kernel_size=3, stride=1, padding=1, norm_layer=norm_layer), + ) + self.branch3 = nn.Sequential( + nn.MaxPool3d(kernel_size=(3, 3, 3), stride=1, padding=1), + Conv3dNormActivation(in_planes, b3_out, kernel_size=1, stride=1, norm_layer=norm_layer), + ) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + out = torch.cat((x0, x1, x2, x3), 1) + + return out + + +class S3D(nn.Module): + """S3D main class. + + Args: + num_class (int): number of classes for the classification task. + dropout (float): dropout probability. + norm_layer (Optional[Callable]): Module specifying the normalization layer to use. + + Inputs: + x (Tensor): batch of videos with dimensions (batch, channel, time, height, width) + """ + + def __init__( + self, + num_classes: int = 400, + dropout: float = 0.2, + norm_layer: Optional[Callable[..., torch.nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if norm_layer is None: + norm_layer = partial(nn.BatchNorm3d, eps=0.001, momentum=0.001) + + self.features = nn.Sequential( + TemporalSeparableConv(3, 64, 7, 2, 3, norm_layer), + nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1)), + Conv3dNormActivation( + 64, + 64, + kernel_size=1, + stride=1, + norm_layer=norm_layer, + ), + TemporalSeparableConv(64, 192, 3, 1, 1, norm_layer), + nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1)), + SepInceptionBlock3D(192, 64, 96, 128, 16, 32, 32, norm_layer), + SepInceptionBlock3D(256, 128, 128, 192, 32, 96, 64, norm_layer), + nn.MaxPool3d(kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(1, 1, 1)), + SepInceptionBlock3D(480, 192, 96, 208, 16, 48, 64, norm_layer), + SepInceptionBlock3D(512, 160, 112, 224, 24, 64, 64, norm_layer), + SepInceptionBlock3D(512, 128, 128, 256, 24, 64, 64, norm_layer), + SepInceptionBlock3D(512, 112, 144, 288, 32, 64, 64, norm_layer), + SepInceptionBlock3D(528, 256, 160, 320, 32, 128, 128, norm_layer), + nn.MaxPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2), padding=(0, 0, 0)), + SepInceptionBlock3D(832, 256, 160, 320, 32, 128, 128, norm_layer), + SepInceptionBlock3D(832, 384, 192, 384, 48, 128, 128, norm_layer), + ) + self.avgpool = nn.AvgPool3d(kernel_size=(2, 7, 7), stride=1) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), + nn.Conv3d(1024, num_classes, kernel_size=1, stride=1, bias=True), + ) + + def forward(self, x): + x = self.features(x) + x = self.avgpool(x) + x = self.classifier(x) + x = torch.mean(x, dim=(2, 3, 4)) + return x + + +class S3D_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/s3d-d76dad2f.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256, 256), + ), + meta={ + "min_size": (224, 224), + "min_temporal_size": 14, + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/video_classification#s3d", + "_docs": ( + "The weights aim to approximate the accuracy of the paper. The accuracies are estimated on clip-level " + "with parameters `frame_rate=15`, `clips_per_video=1`, and `clip_len=128`." + ), + "num_params": 8320048, + "_metrics": { + "Kinetics-400": { + "acc@1": 68.368, + "acc@5": 88.050, + } + }, + "_ops": 17.979, + "_file_size": 31.972, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", S3D_Weights.KINETICS400_V1)) +def s3d(*, weights: Optional[S3D_Weights] = None, progress: bool = True, **kwargs: Any) -> S3D: + """Construct Separable 3D CNN model. + + Reference: `Rethinking Spatiotemporal Feature Learning `__. + + .. betastatus:: video module + + Args: + weights (:class:`~torchvision.models.video.S3D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.S3D_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.S3D`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.S3D_Weights + :members: + """ + weights = S3D_Weights.verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = S3D(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/swin_transformer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/swin_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..1a198142874224a6766f321d9e0dfc97a01ecb43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/video/swin_transformer.py @@ -0,0 +1,743 @@ +# Modified from 2d Swin Transformers in torchvision: +# https://github.com/pytorch/vision/blob/main/torchvision/models/swin_transformer.py + +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ...transforms._presets import VideoClassification + +from ...utils import _log_api_usage_once + +from .._api import register_model, Weights, WeightsEnum + +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..swin_transformer import PatchMerging, SwinTransformerBlock + +__all__ = [ + "SwinTransformer3d", + "Swin3D_T_Weights", + "Swin3D_S_Weights", + "Swin3D_B_Weights", + "swin3d_t", + "swin3d_s", + "swin3d_b", +] + + +def _get_window_and_shift_size( + shift_size: list[int], size_dhw: list[int], window_size: list[int] +) -> tuple[list[int], list[int]]: + for i in range(3): + if size_dhw[i] <= window_size[i]: + # In this case, window_size will adapt to the input size, and no need to shift + window_size[i] = size_dhw[i] + shift_size[i] = 0 + + return window_size, shift_size + + +torch.fx.wrap("_get_window_and_shift_size") + + +def _get_relative_position_bias( + relative_position_bias_table: torch.Tensor, relative_position_index: torch.Tensor, window_size: list[int] +) -> Tensor: + window_vol = window_size[0] * window_size[1] * window_size[2] + # In 3d case we flatten the relative_position_bias + relative_position_bias = relative_position_bias_table[ + relative_position_index[:window_vol, :window_vol].flatten() # type: ignore[index] + ] + relative_position_bias = relative_position_bias.view(window_vol, window_vol, -1) + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(0) + return relative_position_bias + + +torch.fx.wrap("_get_relative_position_bias") + + +def _compute_pad_size_3d(size_dhw: tuple[int, int, int], patch_size: tuple[int, int, int]) -> tuple[int, int, int]: + pad_size = [(patch_size[i] - size_dhw[i] % patch_size[i]) % patch_size[i] for i in range(3)] + return pad_size[0], pad_size[1], pad_size[2] + + +torch.fx.wrap("_compute_pad_size_3d") + + +def _compute_attention_mask_3d( + x: Tensor, + size_dhw: tuple[int, int, int], + window_size: tuple[int, int, int], + shift_size: tuple[int, int, int], +) -> Tensor: + # generate attention mask + attn_mask = x.new_zeros(*size_dhw) + num_windows = (size_dhw[0] // window_size[0]) * (size_dhw[1] // window_size[1]) * (size_dhw[2] // window_size[2]) + slices = [ + ( + (0, -window_size[i]), + (-window_size[i], -shift_size[i]), + (-shift_size[i], None), + ) + for i in range(3) + ] + count = 0 + for d in slices[0]: + for h in slices[1]: + for w in slices[2]: + attn_mask[d[0] : d[1], h[0] : h[1], w[0] : w[1]] = count + count += 1 + + # Partition window on attn_mask + attn_mask = attn_mask.view( + size_dhw[0] // window_size[0], + window_size[0], + size_dhw[1] // window_size[1], + window_size[1], + size_dhw[2] // window_size[2], + window_size[2], + ) + attn_mask = attn_mask.permute(0, 2, 4, 1, 3, 5).reshape( + num_windows, window_size[0] * window_size[1] * window_size[2] + ) + attn_mask = attn_mask.unsqueeze(1) - attn_mask.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + return attn_mask + + +torch.fx.wrap("_compute_attention_mask_3d") + + +def shifted_window_attention_3d( + input: Tensor, + qkv_weight: Tensor, + proj_weight: Tensor, + relative_position_bias: Tensor, + window_size: list[int], + num_heads: int, + shift_size: list[int], + attention_dropout: float = 0.0, + dropout: float = 0.0, + qkv_bias: Optional[Tensor] = None, + proj_bias: Optional[Tensor] = None, + training: bool = True, +) -> Tensor: + """ + Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + input (Tensor[B, T, H, W, C]): The input tensor, 5-dimensions. + qkv_weight (Tensor[in_dim, out_dim]): The weight tensor of query, key, value. + proj_weight (Tensor[out_dim, out_dim]): The weight tensor of projection. + relative_position_bias (Tensor): The learned relative position bias added to attention. + window_size (List[int]): 3-dimensions window size, T, H, W . + num_heads (int): Number of attention heads. + shift_size (List[int]): Shift size for shifted window attention (T, H, W). + attention_dropout (float): Dropout ratio of attention weight. Default: 0.0. + dropout (float): Dropout ratio of output. Default: 0.0. + qkv_bias (Tensor[out_dim], optional): The bias tensor of query, key, value. Default: None. + proj_bias (Tensor[out_dim], optional): The bias tensor of projection. Default: None. + training (bool, optional): Training flag used by the dropout parameters. Default: True. + Returns: + Tensor[B, T, H, W, C]: The output tensor after shifted window attention. + """ + b, t, h, w, c = input.shape + # pad feature maps to multiples of window size + pad_size = _compute_pad_size_3d((t, h, w), (window_size[0], window_size[1], window_size[2])) + x = F.pad(input, (0, 0, 0, pad_size[2], 0, pad_size[1], 0, pad_size[0])) + _, tp, hp, wp, _ = x.shape + padded_size = (tp, hp, wp) + + # cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(-shift_size[0], -shift_size[1], -shift_size[2]), dims=(1, 2, 3)) + + # partition windows + num_windows = ( + (padded_size[0] // window_size[0]) * (padded_size[1] // window_size[1]) * (padded_size[2] // window_size[2]) + ) + x = x.view( + b, + padded_size[0] // window_size[0], + window_size[0], + padded_size[1] // window_size[1], + window_size[1], + padded_size[2] // window_size[2], + window_size[2], + c, + ) + x = x.permute(0, 1, 3, 5, 2, 4, 6, 7).reshape( + b * num_windows, window_size[0] * window_size[1] * window_size[2], c + ) # B*nW, Wd*Wh*Ww, C + + # multi-head attention + qkv = F.linear(x, qkv_weight, qkv_bias) + qkv = qkv.reshape(x.size(0), x.size(1), 3, num_heads, c // num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + q = q * (c // num_heads) ** -0.5 + attn = q.matmul(k.transpose(-2, -1)) + # add relative position bias + attn = attn + relative_position_bias + + if sum(shift_size) > 0: + # generate attention mask to handle shifted windows with varying size + attn_mask = _compute_attention_mask_3d( + x, + (padded_size[0], padded_size[1], padded_size[2]), + (window_size[0], window_size[1], window_size[2]), + (shift_size[0], shift_size[1], shift_size[2]), + ) + attn = attn.view(x.size(0) // num_windows, num_windows, num_heads, x.size(1), x.size(1)) + attn = attn + attn_mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, num_heads, x.size(1), x.size(1)) + + attn = F.softmax(attn, dim=-1) + attn = F.dropout(attn, p=attention_dropout, training=training) + + x = attn.matmul(v).transpose(1, 2).reshape(x.size(0), x.size(1), c) + x = F.linear(x, proj_weight, proj_bias) + x = F.dropout(x, p=dropout, training=training) + + # reverse windows + x = x.view( + b, + padded_size[0] // window_size[0], + padded_size[1] // window_size[1], + padded_size[2] // window_size[2], + window_size[0], + window_size[1], + window_size[2], + c, + ) + x = x.permute(0, 1, 4, 2, 5, 3, 6, 7).reshape(b, tp, hp, wp, c) + + # reverse cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(shift_size[0], shift_size[1], shift_size[2]), dims=(1, 2, 3)) + + # unpad features + x = x[:, :t, :h, :w, :].contiguous() + return x + + +torch.fx.wrap("shifted_window_attention_3d") + + +class ShiftedWindowAttention3d(nn.Module): + """ + See :func:`shifted_window_attention_3d`. + """ + + def __init__( + self, + dim: int, + window_size: list[int], + shift_size: list[int], + num_heads: int, + qkv_bias: bool = True, + proj_bias: bool = True, + attention_dropout: float = 0.0, + dropout: float = 0.0, + ) -> None: + super().__init__() + if len(window_size) != 3 or len(shift_size) != 3: + raise ValueError("window_size and shift_size must be of length 2") + + self.window_size = window_size # Wd, Wh, Ww + self.shift_size = shift_size + self.num_heads = num_heads + self.attention_dropout = attention_dropout + self.dropout = dropout + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + + self.define_relative_position_bias_table() + self.define_relative_position_index() + + def define_relative_position_bias_table(self) -> None: + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros( + (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1), + self.num_heads, + ) + ) # 2*Wd-1 * 2*Wh-1 * 2*Ww-1, nH + nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + def define_relative_position_index(self) -> None: + # get pair-wise relative position index for each token inside the window + coords_dhw = [torch.arange(self.window_size[i]) for i in range(3)] + coords = torch.stack( + torch.meshgrid(coords_dhw[0], coords_dhw[1], coords_dhw[2], indexing="ij") + ) # 3, Wd, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 3, Wd*Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 3, Wd*Wh*Ww, Wd*Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wd*Wh*Ww, Wd*Wh*Ww, 3 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 2] += self.window_size[2] - 1 + + relative_coords[:, :, 0] *= (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1) + relative_coords[:, :, 1] *= 2 * self.window_size[2] - 1 + # We don't flatten the relative_position_index here in 3d case. + relative_position_index = relative_coords.sum(-1) # Wd*Wh*Ww, Wd*Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + def get_relative_position_bias(self, window_size: list[int]) -> torch.Tensor: + return _get_relative_position_bias(self.relative_position_bias_table, self.relative_position_index, window_size) # type: ignore + + def forward(self, x: Tensor) -> Tensor: + _, t, h, w, _ = x.shape + size_dhw = [t, h, w] + window_size, shift_size = self.window_size.copy(), self.shift_size.copy() + # Handle case where window_size is larger than the input tensor + window_size, shift_size = _get_window_and_shift_size(shift_size, size_dhw, window_size) + + relative_position_bias = self.get_relative_position_bias(window_size) + + return shifted_window_attention_3d( + x, + self.qkv.weight, + self.proj.weight, + relative_position_bias, + window_size, + self.num_heads, + shift_size=shift_size, + attention_dropout=self.attention_dropout, + dropout=self.dropout, + qkv_bias=self.qkv.bias, + proj_bias=self.proj.bias, + training=self.training, + ) + + +# Modified from: +# https://github.com/SwinTransformer/Video-Swin-Transformer/blob/master/mmaction/models/backbones/swin_transformer.py +class PatchEmbed3d(nn.Module): + """Video to Patch Embedding. + + Args: + patch_size (List[int]): Patch token size. + in_channels (int): Number of input channels. Default: 3 + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ + + def __init__( + self, + patch_size: list[int], + in_channels: int = 3, + embed_dim: int = 96, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.tuple_patch_size = (patch_size[0], patch_size[1], patch_size[2]) + + self.proj = nn.Conv3d( + in_channels, + embed_dim, + kernel_size=self.tuple_patch_size, + stride=self.tuple_patch_size, + ) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + """Forward function.""" + # padding + _, _, t, h, w = x.size() + pad_size = _compute_pad_size_3d((t, h, w), self.tuple_patch_size) + x = F.pad(x, (0, pad_size[2], 0, pad_size[1], 0, pad_size[0])) + x = self.proj(x) # B C T Wh Ww + x = x.permute(0, 2, 3, 4, 1) # B T Wh Ww C + if self.norm is not None: + x = self.norm(x) + return x + + +class SwinTransformer3d(nn.Module): + """ + Implements 3D Swin Transformer from the `"Video Swin Transformer" `_ paper. + Args: + patch_size (List[int]): Patch size. + embed_dim (int): Patch embedding dimension. + depths (List(int)): Depth of each Swin Transformer layer. + num_heads (List(int)): Number of attention heads in different layers. + window_size (List[int]): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob (float): Stochastic depth rate. Default: 0.1. + num_classes (int): Number of classes for classification head. Default: 400. + norm_layer (nn.Module, optional): Normalization layer. Default: None. + block (nn.Module, optional): SwinTransformer Block. Default: None. + downsample_layer (nn.Module): Downsample layer (patch merging). Default: PatchMerging. + patch_embed (nn.Module, optional): Patch Embedding layer. Default: None. + """ + + def __init__( + self, + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.1, + num_classes: int = 400, + norm_layer: Optional[Callable[..., nn.Module]] = None, + block: Optional[Callable[..., nn.Module]] = None, + downsample_layer: Callable[..., nn.Module] = PatchMerging, + patch_embed: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.num_classes = num_classes + + if block is None: + block = partial(SwinTransformerBlock, attn_layer=ShiftedWindowAttention3d) + + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-5) + + if patch_embed is None: + patch_embed = PatchEmbed3d + + # split image into non-overlapping patches + self.patch_embed = patch_embed(patch_size=patch_size, embed_dim=embed_dim, norm_layer=norm_layer) + self.pos_drop = nn.Dropout(p=dropout) + + layers: list[nn.Module] = [] + total_stage_blocks = sum(depths) + stage_block_id = 0 + # build SwinTransformer blocks + for i_stage in range(len(depths)): + stage: list[nn.Module] = [] + dim = embed_dim * 2**i_stage + for i_layer in range(depths[i_stage]): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * float(stage_block_id) / (total_stage_blocks - 1) + stage.append( + block( + dim, + num_heads[i_stage], + window_size=window_size, + shift_size=[0 if i_layer % 2 == 0 else w // 2 for w in window_size], + mlp_ratio=mlp_ratio, + dropout=dropout, + attention_dropout=attention_dropout, + stochastic_depth_prob=sd_prob, + norm_layer=norm_layer, + attn_layer=ShiftedWindowAttention3d, + ) + ) + stage_block_id += 1 + layers.append(nn.Sequential(*stage)) + # add patch merging layer + if i_stage < (len(depths) - 1): + layers.append(downsample_layer(dim, norm_layer)) + self.features = nn.Sequential(*layers) + + self.num_features = embed_dim * 2 ** (len(depths) - 1) + self.norm = norm_layer(self.num_features) + self.avgpool = nn.AdaptiveAvgPool3d(1) + self.head = nn.Linear(self.num_features, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + def forward(self, x: Tensor) -> Tensor: + # x: B C T H W + x = self.patch_embed(x) # B _T _H _W C + x = self.pos_drop(x) + x = self.features(x) # B _T _H _W C + x = self.norm(x) + x = x.permute(0, 4, 1, 2, 3) # B, C, _T, _H, _W + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.head(x) + return x + + +def _swin_transformer3d( + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> SwinTransformer3d: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = SwinTransformer3d( + patch_size=patch_size, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + stochastic_depth_prob=stochastic_depth_prob, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "categories": _KINETICS400_CATEGORIES, + "min_size": (1, 1), + "min_temporal_size": 1, +} + + +class Swin3D_T_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_t-7615ae03.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 28158070, + "_metrics": { + "Kinetics-400": { + "acc@1": 77.715, + "acc@5": 93.519, + } + }, + "_ops": 43.882, + "_file_size": 121.543, + }, + ) + DEFAULT = KINETICS400_V1 + + +class Swin3D_S_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_s-da41c237.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 49816678, + "_metrics": { + "Kinetics-400": { + "acc@1": 79.521, + "acc@5": 94.158, + } + }, + "_ops": 82.841, + "_file_size": 218.288, + }, + ) + DEFAULT = KINETICS400_V1 + + +class Swin3D_B_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_b_1k-24f7c7c6.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 88048984, + "_metrics": { + "Kinetics-400": { + "acc@1": 79.427, + "acc@5": 94.386, + } + }, + "_ops": 140.667, + "_file_size": 364.134, + }, + ) + KINETICS400_IMAGENET22K_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_b_22k-7c6ae6fa.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 88048984, + "_metrics": { + "Kinetics-400": { + "acc@1": 81.643, + "acc@5": 95.574, + } + }, + "_ops": 140.667, + "_file_size": 364.134, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin3D_T_Weights.KINETICS400_V1)) +def swin3d_t(*, weights: Optional[Swin3D_T_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer3d: + """ + Constructs a swin_tiny architecture from + `Video Swin Transformer `_. + + Args: + weights (:class:`~torchvision.models.video.Swin3D_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.Swin3D_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.Swin3D_T_Weights + :members: + """ + weights = Swin3D_T_Weights.verify(weights) + + return _swin_transformer3d( + patch_size=[2, 4, 4], + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 7, 7], + stochastic_depth_prob=0.1, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin3D_S_Weights.KINETICS400_V1)) +def swin3d_s(*, weights: Optional[Swin3D_S_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer3d: + """ + Constructs a swin_small architecture from + `Video Swin Transformer `_. + + Args: + weights (:class:`~torchvision.models.video.Swin3D_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.Swin3D_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.Swin3D_S_Weights + :members: + """ + weights = Swin3D_S_Weights.verify(weights) + + return _swin_transformer3d( + patch_size=[2, 4, 4], + embed_dim=96, + depths=[2, 2, 18, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 7, 7], + stochastic_depth_prob=0.1, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin3D_B_Weights.KINETICS400_V1)) +def swin3d_b(*, weights: Optional[Swin3D_B_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer3d: + """ + Constructs a swin_base architecture from + `Video Swin Transformer `_. + + Args: + weights (:class:`~torchvision.models.video.Swin3D_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.Swin3D_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.Swin3D_B_Weights + :members: + """ + weights = Swin3D_B_Weights.verify(weights) + + return _swin_transformer3d( + patch_size=[2, 4, 4], + embed_dim=128, + depths=[2, 2, 18, 2], + num_heads=[4, 8, 16, 32], + window_size=[8, 7, 7], + stochastic_depth_prob=0.1, + weights=weights, + progress=progress, + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/vision_transformer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..4ec3a5c59f0a4112f1eec0ec7d5c0ccba5289946 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/models/vision_transformer.py @@ -0,0 +1,864 @@ +import math +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, NamedTuple, Optional + +import torch +import torch.nn as nn + +from ..ops.misc import Conv2dNormActivation, MLP +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "VisionTransformer", + "ViT_B_16_Weights", + "ViT_B_32_Weights", + "ViT_L_16_Weights", + "ViT_L_32_Weights", + "ViT_H_14_Weights", + "vit_b_16", + "vit_b_32", + "vit_l_16", + "vit_l_32", + "vit_h_14", +] + + +class ConvStemConfig(NamedTuple): + out_channels: int + kernel_size: int + stride: int + norm_layer: Callable[..., nn.Module] = nn.BatchNorm2d + activation_layer: Callable[..., nn.Module] = nn.ReLU + + +class MLPBlock(MLP): + """Transformer MLP block.""" + + _version = 2 + + def __init__(self, in_dim: int, mlp_dim: int, dropout: float): + super().__init__(in_dim, [mlp_dim, in_dim], activation_layer=nn.GELU, inplace=None, dropout=dropout) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.normal_(m.bias, std=1e-6) + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + # Replacing legacy MLPBlock with MLP. See https://github.com/pytorch/vision/pull/6053 + for i in range(2): + for type in ["weight", "bias"]: + old_key = f"{prefix}linear_{i+1}.{type}" + new_key = f"{prefix}{3*i}.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + +class EncoderBlock(nn.Module): + """Transformer encoder block.""" + + def __init__( + self, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + dropout: float, + attention_dropout: float, + norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), + ): + super().__init__() + self.num_heads = num_heads + + # Attention block + self.ln_1 = norm_layer(hidden_dim) + self.self_attention = nn.MultiheadAttention(hidden_dim, num_heads, dropout=attention_dropout, batch_first=True) + self.dropout = nn.Dropout(dropout) + + # MLP block + self.ln_2 = norm_layer(hidden_dim) + self.mlp = MLPBlock(hidden_dim, mlp_dim, dropout) + + def forward(self, input: torch.Tensor): + torch._assert(input.dim() == 3, f"Expected (batch_size, seq_length, hidden_dim) got {input.shape}") + x = self.ln_1(input) + x, _ = self.self_attention(x, x, x, need_weights=False) + x = self.dropout(x) + x = x + input + + y = self.ln_2(x) + y = self.mlp(y) + return x + y + + +class Encoder(nn.Module): + """Transformer Model Encoder for sequence to sequence translation.""" + + def __init__( + self, + seq_length: int, + num_layers: int, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + dropout: float, + attention_dropout: float, + norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), + ): + super().__init__() + # Note that batch_size is on the first dim because + # we have batch_first=True in nn.MultiAttention() by default + self.pos_embedding = nn.Parameter(torch.empty(1, seq_length, hidden_dim).normal_(std=0.02)) # from BERT + self.dropout = nn.Dropout(dropout) + layers: OrderedDict[str, nn.Module] = OrderedDict() + for i in range(num_layers): + layers[f"encoder_layer_{i}"] = EncoderBlock( + num_heads, + hidden_dim, + mlp_dim, + dropout, + attention_dropout, + norm_layer, + ) + self.layers = nn.Sequential(layers) + self.ln = norm_layer(hidden_dim) + + def forward(self, input: torch.Tensor): + torch._assert(input.dim() == 3, f"Expected (batch_size, seq_length, hidden_dim) got {input.shape}") + input = input + self.pos_embedding + return self.ln(self.layers(self.dropout(input))) + + +class VisionTransformer(nn.Module): + """Vision Transformer as per https://arxiv.org/abs/2010.11929.""" + + def __init__( + self, + image_size: int, + patch_size: int, + num_layers: int, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + dropout: float = 0.0, + attention_dropout: float = 0.0, + num_classes: int = 1000, + representation_size: Optional[int] = None, + norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), + conv_stem_configs: Optional[list[ConvStemConfig]] = None, + ): + super().__init__() + _log_api_usage_once(self) + torch._assert(image_size % patch_size == 0, "Input shape indivisible by patch size!") + self.image_size = image_size + self.patch_size = patch_size + self.hidden_dim = hidden_dim + self.mlp_dim = mlp_dim + self.attention_dropout = attention_dropout + self.dropout = dropout + self.num_classes = num_classes + self.representation_size = representation_size + self.norm_layer = norm_layer + + if conv_stem_configs is not None: + # As per https://arxiv.org/abs/2106.14881 + seq_proj = nn.Sequential() + prev_channels = 3 + for i, conv_stem_layer_config in enumerate(conv_stem_configs): + seq_proj.add_module( + f"conv_bn_relu_{i}", + Conv2dNormActivation( + in_channels=prev_channels, + out_channels=conv_stem_layer_config.out_channels, + kernel_size=conv_stem_layer_config.kernel_size, + stride=conv_stem_layer_config.stride, + norm_layer=conv_stem_layer_config.norm_layer, + activation_layer=conv_stem_layer_config.activation_layer, + ), + ) + prev_channels = conv_stem_layer_config.out_channels + seq_proj.add_module( + "conv_last", nn.Conv2d(in_channels=prev_channels, out_channels=hidden_dim, kernel_size=1) + ) + self.conv_proj: nn.Module = seq_proj + else: + self.conv_proj = nn.Conv2d( + in_channels=3, out_channels=hidden_dim, kernel_size=patch_size, stride=patch_size + ) + + seq_length = (image_size // patch_size) ** 2 + + # Add a class token + self.class_token = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + seq_length += 1 + + self.encoder = Encoder( + seq_length, + num_layers, + num_heads, + hidden_dim, + mlp_dim, + dropout, + attention_dropout, + norm_layer, + ) + self.seq_length = seq_length + + heads_layers: OrderedDict[str, nn.Module] = OrderedDict() + if representation_size is None: + heads_layers["head"] = nn.Linear(hidden_dim, num_classes) + else: + heads_layers["pre_logits"] = nn.Linear(hidden_dim, representation_size) + heads_layers["act"] = nn.Tanh() + heads_layers["head"] = nn.Linear(representation_size, num_classes) + + self.heads = nn.Sequential(heads_layers) + + if isinstance(self.conv_proj, nn.Conv2d): + # Init the patchify stem + fan_in = self.conv_proj.in_channels * self.conv_proj.kernel_size[0] * self.conv_proj.kernel_size[1] + nn.init.trunc_normal_(self.conv_proj.weight, std=math.sqrt(1 / fan_in)) + if self.conv_proj.bias is not None: + nn.init.zeros_(self.conv_proj.bias) + elif self.conv_proj.conv_last is not None and isinstance(self.conv_proj.conv_last, nn.Conv2d): + # Init the last 1x1 conv of the conv stem + nn.init.normal_( + self.conv_proj.conv_last.weight, mean=0.0, std=math.sqrt(2.0 / self.conv_proj.conv_last.out_channels) + ) + if self.conv_proj.conv_last.bias is not None: + nn.init.zeros_(self.conv_proj.conv_last.bias) + + if hasattr(self.heads, "pre_logits") and isinstance(self.heads.pre_logits, nn.Linear): + fan_in = self.heads.pre_logits.in_features + nn.init.trunc_normal_(self.heads.pre_logits.weight, std=math.sqrt(1 / fan_in)) + nn.init.zeros_(self.heads.pre_logits.bias) + + if isinstance(self.heads.head, nn.Linear): + nn.init.zeros_(self.heads.head.weight) + nn.init.zeros_(self.heads.head.bias) + + def _process_input(self, x: torch.Tensor) -> torch.Tensor: + n, c, h, w = x.shape + p = self.patch_size + torch._assert(h == self.image_size, f"Wrong image height! Expected {self.image_size} but got {h}!") + torch._assert(w == self.image_size, f"Wrong image width! Expected {self.image_size} but got {w}!") + n_h = h // p + n_w = w // p + + # (n, c, h, w) -> (n, hidden_dim, n_h, n_w) + x = self.conv_proj(x) + # (n, hidden_dim, n_h, n_w) -> (n, hidden_dim, (n_h * n_w)) + x = x.reshape(n, self.hidden_dim, n_h * n_w) + + # (n, hidden_dim, (n_h * n_w)) -> (n, (n_h * n_w), hidden_dim) + # The self attention layer expects inputs in the format (N, S, E) + # where S is the source sequence length, N is the batch size, E is the + # embedding dimension + x = x.permute(0, 2, 1) + + return x + + def forward(self, x: torch.Tensor): + # Reshape and permute the input tensor + x = self._process_input(x) + n = x.shape[0] + + # Expand the class token to the full batch + batch_class_token = self.class_token.expand(n, -1, -1) + x = torch.cat([batch_class_token, x], dim=1) + + x = self.encoder(x) + + # Classifier "token" as used by standard language architectures + x = x[:, 0] + + x = self.heads(x) + + return x + + +def _vision_transformer( + patch_size: int, + num_layers: int, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> VisionTransformer: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + assert weights.meta["min_size"][0] == weights.meta["min_size"][1] + _ovewrite_named_param(kwargs, "image_size", weights.meta["min_size"][0]) + image_size = kwargs.pop("image_size", 224) + + model = VisionTransformer( + image_size=image_size, + patch_size=patch_size, + num_layers=num_layers, + num_heads=num_heads, + hidden_dim=hidden_dim, + mlp_dim=mlp_dim, + **kwargs, + ) + + if weights: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META: dict[str, Any] = { + "categories": _IMAGENET_CATEGORIES, +} + +_COMMON_SWAG_META = { + **_COMMON_META, + "recipe": "https://github.com/facebookresearch/SWAG", + "license": "https://github.com/facebookresearch/SWAG/blob/main/LICENSE", +} + + +class ViT_B_16_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_16-c867db91.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 86567656, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_b_16", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.072, + "acc@5": 95.318, + } + }, + "_ops": 17.564, + "_file_size": 330.285, + "_docs": """ + These weights were trained from scratch by using a modified version of `DeIT + `_'s training recipe. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_16_swag-9ac1b537.pth", + transforms=partial( + ImageClassification, + crop_size=384, + resize_size=384, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 86859496, + "min_size": (384, 384), + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.304, + "acc@5": 97.650, + } + }, + "_ops": 55.484, + "_file_size": 331.398, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_16_lc_swag-4e70ced5.pth", + transforms=partial( + ImageClassification, + crop_size=224, + resize_size=224, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 86567656, + "min_size": (224, 224), + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.886, + "acc@5": 96.180, + } + }, + "_ops": 17.564, + "_file_size": 330.285, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_B_32_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_32-d86f8d99.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 88224232, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_b_32", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.912, + "acc@5": 92.466, + } + }, + "_ops": 4.409, + "_file_size": 336.604, + "_docs": """ + These weights were trained from scratch by using a modified version of `DeIT + `_'s training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_L_16_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_16-852ce7e3.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=242), + meta={ + **_COMMON_META, + "num_params": 304326632, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_l_16", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.662, + "acc@5": 94.638, + } + }, + "_ops": 61.555, + "_file_size": 1161.023, + "_docs": """ + These weights were trained from scratch by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_16_swag-4f3808c9.pth", + transforms=partial( + ImageClassification, + crop_size=512, + resize_size=512, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 305174504, + "min_size": (512, 512), + "_metrics": { + "ImageNet-1K": { + "acc@1": 88.064, + "acc@5": 98.512, + } + }, + "_ops": 361.986, + "_file_size": 1164.258, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_16_lc_swag-4d563306.pth", + transforms=partial( + ImageClassification, + crop_size=224, + resize_size=224, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 304326632, + "min_size": (224, 224), + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.146, + "acc@5": 97.422, + } + }, + "_ops": 61.555, + "_file_size": 1161.023, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_L_32_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_32-c7638314.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 306535400, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_l_32", + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.972, + "acc@5": 93.07, + } + }, + "_ops": 15.378, + "_file_size": 1169.449, + "_docs": """ + These weights were trained from scratch by using a modified version of `DeIT + `_'s training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_H_14_Weights(WeightsEnum): + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/vit_h_14_swag-80465313.pth", + transforms=partial( + ImageClassification, + crop_size=518, + resize_size=518, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 633470440, + "min_size": (518, 518), + "_metrics": { + "ImageNet-1K": { + "acc@1": 88.552, + "acc@5": 98.694, + } + }, + "_ops": 1016.717, + "_file_size": 2416.643, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/vit_h_14_lc_swag-c1eb923e.pth", + transforms=partial( + ImageClassification, + crop_size=224, + resize_size=224, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 632045800, + "min_size": (224, 224), + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.708, + "acc@5": 97.730, + } + }, + "_ops": 167.295, + "_file_size": 2411.209, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_SWAG_E2E_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_B_16_Weights.IMAGENET1K_V1)) +def vit_b_16(*, weights: Optional[ViT_B_16_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_b_16 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_B_16_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_B_16_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_B_16_Weights + :members: + """ + weights = ViT_B_16_Weights.verify(weights) + + return _vision_transformer( + patch_size=16, + num_layers=12, + num_heads=12, + hidden_dim=768, + mlp_dim=3072, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_B_32_Weights.IMAGENET1K_V1)) +def vit_b_32(*, weights: Optional[ViT_B_32_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_b_32 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_B_32_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_B_32_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_B_32_Weights + :members: + """ + weights = ViT_B_32_Weights.verify(weights) + + return _vision_transformer( + patch_size=32, + num_layers=12, + num_heads=12, + hidden_dim=768, + mlp_dim=3072, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_L_16_Weights.IMAGENET1K_V1)) +def vit_l_16(*, weights: Optional[ViT_L_16_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_l_16 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_L_16_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_L_16_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_L_16_Weights + :members: + """ + weights = ViT_L_16_Weights.verify(weights) + + return _vision_transformer( + patch_size=16, + num_layers=24, + num_heads=16, + hidden_dim=1024, + mlp_dim=4096, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_L_32_Weights.IMAGENET1K_V1)) +def vit_l_32(*, weights: Optional[ViT_L_32_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_l_32 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_L_32_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_L_32_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_L_32_Weights + :members: + """ + weights = ViT_L_32_Weights.verify(weights) + + return _vision_transformer( + patch_size=32, + num_layers=24, + num_heads=16, + hidden_dim=1024, + mlp_dim=4096, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", None)) +def vit_h_14(*, weights: Optional[ViT_H_14_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_h_14 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_H_14_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_H_14_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_H_14_Weights + :members: + """ + weights = ViT_H_14_Weights.verify(weights) + + return _vision_transformer( + patch_size=14, + num_layers=32, + num_heads=16, + hidden_dim=1280, + mlp_dim=5120, + weights=weights, + progress=progress, + **kwargs, + ) + + +def interpolate_embeddings( + image_size: int, + patch_size: int, + model_state: "OrderedDict[str, torch.Tensor]", + interpolation_mode: str = "bicubic", + reset_heads: bool = False, +) -> "OrderedDict[str, torch.Tensor]": + """This function helps interpolate positional embeddings during checkpoint loading, + especially when you want to apply a pre-trained model on images with different resolution. + + Args: + image_size (int): Image size of the new model. + patch_size (int): Patch size of the new model. + model_state (OrderedDict[str, torch.Tensor]): State dict of the pre-trained model. + interpolation_mode (str): The algorithm used for upsampling. Default: bicubic. + reset_heads (bool): If true, not copying the state of heads. Default: False. + + Returns: + OrderedDict[str, torch.Tensor]: A state dict which can be loaded into the new model. + """ + # Shape of pos_embedding is (1, seq_length, hidden_dim) + pos_embedding = model_state["encoder.pos_embedding"] + n, seq_length, hidden_dim = pos_embedding.shape + if n != 1: + raise ValueError(f"Unexpected position embedding shape: {pos_embedding.shape}") + + new_seq_length = (image_size // patch_size) ** 2 + 1 + + # Need to interpolate the weights for the position embedding. + # We do this by reshaping the positions embeddings to a 2d grid, performing + # an interpolation in the (h, w) space and then reshaping back to a 1d grid. + if new_seq_length != seq_length: + # The class token embedding shouldn't be interpolated, so we split it up. + seq_length -= 1 + new_seq_length -= 1 + pos_embedding_token = pos_embedding[:, :1, :] + pos_embedding_img = pos_embedding[:, 1:, :] + + # (1, seq_length, hidden_dim) -> (1, hidden_dim, seq_length) + pos_embedding_img = pos_embedding_img.permute(0, 2, 1) + seq_length_1d = int(math.sqrt(seq_length)) + if seq_length_1d * seq_length_1d != seq_length: + raise ValueError( + f"seq_length is not a perfect square! Instead got seq_length_1d * seq_length_1d = {seq_length_1d * seq_length_1d } and seq_length = {seq_length}" + ) + + # (1, hidden_dim, seq_length) -> (1, hidden_dim, seq_l_1d, seq_l_1d) + pos_embedding_img = pos_embedding_img.reshape(1, hidden_dim, seq_length_1d, seq_length_1d) + new_seq_length_1d = image_size // patch_size + + # Perform interpolation. + # (1, hidden_dim, seq_l_1d, seq_l_1d) -> (1, hidden_dim, new_seq_l_1d, new_seq_l_1d) + new_pos_embedding_img = nn.functional.interpolate( + pos_embedding_img, + size=new_seq_length_1d, + mode=interpolation_mode, + align_corners=True, + ) + + # (1, hidden_dim, new_seq_l_1d, new_seq_l_1d) -> (1, hidden_dim, new_seq_length) + new_pos_embedding_img = new_pos_embedding_img.reshape(1, hidden_dim, new_seq_length) + + # (1, hidden_dim, new_seq_length) -> (1, new_seq_length, hidden_dim) + new_pos_embedding_img = new_pos_embedding_img.permute(0, 2, 1) + new_pos_embedding = torch.cat([pos_embedding_token, new_pos_embedding_img], dim=1) + + model_state["encoder.pos_embedding"] = new_pos_embedding + + if reset_heads: + model_state_copy: "OrderedDict[str, torch.Tensor]" = OrderedDict() + for k, v in model_state.items(): + if not k.startswith("heads"): + model_state_copy[k] = v + model_state = model_state_copy + + return model_state diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..827505b842d4f1ad0e16dfe54ef28658364cc9ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/__init__.py @@ -0,0 +1,73 @@ +from ._register_onnx_ops import _register_custom_op +from .boxes import ( + batched_nms, + box_area, + box_convert, + box_iou, + clip_boxes_to_image, + complete_box_iou, + distance_box_iou, + generalized_box_iou, + masks_to_boxes, + nms, + remove_small_boxes, +) +from .ciou_loss import complete_box_iou_loss +from .deform_conv import deform_conv2d, DeformConv2d +from .diou_loss import distance_box_iou_loss +from .drop_block import drop_block2d, drop_block3d, DropBlock2d, DropBlock3d +from .feature_pyramid_network import FeaturePyramidNetwork +from .focal_loss import sigmoid_focal_loss +from .giou_loss import generalized_box_iou_loss +from .misc import Conv2dNormActivation, Conv3dNormActivation, FrozenBatchNorm2d, MLP, Permute, SqueezeExcitation +from .poolers import MultiScaleRoIAlign +from .ps_roi_align import ps_roi_align, PSRoIAlign +from .ps_roi_pool import ps_roi_pool, PSRoIPool +from .roi_align import roi_align, RoIAlign +from .roi_pool import roi_pool, RoIPool +from .stochastic_depth import stochastic_depth, StochasticDepth + +_register_custom_op() + + +__all__ = [ + "masks_to_boxes", + "deform_conv2d", + "DeformConv2d", + "nms", + "batched_nms", + "remove_small_boxes", + "clip_boxes_to_image", + "box_convert", + "box_area", + "box_iou", + "generalized_box_iou", + "distance_box_iou", + "complete_box_iou", + "roi_align", + "RoIAlign", + "roi_pool", + "RoIPool", + "ps_roi_align", + "PSRoIAlign", + "ps_roi_pool", + "PSRoIPool", + "MultiScaleRoIAlign", + "FeaturePyramidNetwork", + "sigmoid_focal_loss", + "stochastic_depth", + "StochasticDepth", + "FrozenBatchNorm2d", + "Conv2dNormActivation", + "Conv3dNormActivation", + "SqueezeExcitation", + "MLP", + "Permute", + "generalized_box_iou_loss", + "distance_box_iou_loss", + "complete_box_iou_loss", + "drop_block2d", + "DropBlock2d", + "drop_block3d", + "DropBlock3d", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_box_convert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_box_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..81406248020b5e284b8d4a6ae8bd6528bb12c58a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_box_convert.py @@ -0,0 +1,207 @@ +import torch +from torch import Tensor + + +def _box_cxcywh_to_xyxy(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (cx, cy, w, h) format to (x1, y1, x2, y2) format. + (cx, cy) refers to center of bounding box + (w, h) are width and height of bounding box + Args: + boxes (Tensor[N, 4]): boxes in (cx, cy, w, h) format which will be converted. + + Returns: + boxes (Tensor(N, 4)): boxes in (x1, y1, x2, y2) format. + """ + # We need to change all 4 of them so some temporary variable is needed. + cx, cy, w, h = boxes.unbind(-1) + x1 = cx - 0.5 * w + y1 = cy - 0.5 * h + x2 = cx + 0.5 * w + y2 = cy + 0.5 * h + + boxes = torch.stack((x1, y1, x2, y2), dim=-1) + + return boxes + + +def _box_xyxy_to_cxcywh(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (x1, y1, x2, y2) format to (cx, cy, w, h) format. + (x1, y1) refer to top left of bounding box + (x2, y2) refer to bottom right of bounding box + Args: + boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) format which will be converted. + + Returns: + boxes (Tensor(N, 4)): boxes in (cx, cy, w, h) format. + """ + x1, y1, x2, y2 = boxes.unbind(-1) + cx = (x1 + x2) / 2 + cy = (y1 + y2) / 2 + w = x2 - x1 + h = y2 - y1 + + boxes = torch.stack((cx, cy, w, h), dim=-1) + + return boxes + + +def _box_xywh_to_xyxy(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (x, y, w, h) format to (x1, y1, x2, y2) format. + (x, y) refers to top left of bounding box. + (w, h) refers to width and height of box. + Args: + boxes (Tensor[N, 4]): boxes in (x, y, w, h) which will be converted. + + Returns: + boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) format. + """ + x, y, w, h = boxes.unbind(-1) + boxes = torch.stack([x, y, x + w, y + h], dim=-1) + return boxes + + +def _box_xyxy_to_xywh(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (x1, y1, x2, y2) format to (x, y, w, h) format. + (x1, y1) refer to top left of bounding box + (x2, y2) refer to bottom right of bounding box + Args: + boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) which will be converted. + + Returns: + boxes (Tensor[N, 4]): boxes in (x, y, w, h) format. + """ + x1, y1, x2, y2 = boxes.unbind(-1) + w = x2 - x1 # x2 - x1 + h = y2 - y1 # y2 - y1 + boxes = torch.stack((x1, y1, w, h), dim=-1) + return boxes + + +def _box_cxcywhr_to_xywhr(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (cx, cy, w, h, r) format to (x1, y1, w, h, r) format. + (cx, cy) refers to center of bounding box + (w, h) refers to width and height of rotated bounding box + (x1, y1) refers to top left of rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + Args: + boxes (Tensor[N, 5]): boxes in (cx, cy, w, h, r) format which will be converted. + + Returns: + boxes (Tensor(N, 5)): rotated boxes in (x1, y1, w, h, r) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + cx, cy, w, h, r = boxes.unbind(-1) + r_rad = r * torch.pi / 180.0 + cos, sin = torch.cos(r_rad), torch.sin(r_rad) + + x1 = cx - w / 2 * cos - h / 2 * sin + y1 = cy - h / 2 * cos + w / 2 * sin + boxes = torch.stack((x1, y1, w, h, r), dim=-1) + + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes + + +def _box_xywhr_to_cxcywhr(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (x1, y1, w, h, r) format to (cx, cy, w, h, r) format. + (x1, y1) refers to top left of rotated bounding box + (w, h) refers to width and height of rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + Args: + boxes (Tensor[N, 5]): rotated boxes in (x1, y1, w, h, r) format which will be converted. + + Returns: + boxes (Tensor[N, 5]): rotated boxes in (cx, cy, w, h, r) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + x1, y1, w, h, r = boxes.unbind(-1) + r_rad = r * torch.pi / 180.0 + cos, sin = torch.cos(r_rad), torch.sin(r_rad) + + cx = x1 + w / 2 * cos + h / 2 * sin + cy = y1 - w / 2 * sin + h / 2 * cos + + boxes = torch.stack([cx, cy, w, h, r], dim=-1) + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes + + +def _box_xywhr_to_xyxyxyxy(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (x1, y1, w, h, r) format to (x1, y1, x2, y2, x3, y3, x4, y4) format. + (x1, y1) refer to top left of bounding box + (w, h) are width and height of the rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + (x1, y1) refer to top left of rotated bounding box + (x2, y2) refer to top right of rotated bounding box + (x3, y3) refer to bottom right of rotated bounding box + (x4, y4) refer to bottom left ofrotated bounding box + Args: + boxes (Tensor[N, 5]): rotated boxes in (cx, cy, w, h, r) format which will be converted. + + Returns: + boxes (Tensor(N, 8)): rotated boxes in (x1, y1, x2, y2, x3, y3, x4, y4) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + x1, y1, w, h, r = boxes.unbind(-1) + r_rad = r * torch.pi / 180.0 + cos, sin = torch.cos(r_rad), torch.sin(r_rad) + + x2 = x1 + w * cos + y2 = y1 - w * sin + x3 = x2 + h * sin + y3 = y2 + h * cos + x4 = x1 + h * sin + y4 = y1 + h * cos + + boxes = torch.stack((x1, y1, x2, y2, x3, y3, x4, y4), dim=-1) + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes + + +def _box_xyxyxyxy_to_xywhr(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (x1, y1, x2, y2, x3, y3, x4, y4) format to (x1, y1, w, h, r) format. + (x1, y1) refer to top left of the rotated bounding box + (x2, y2) refer to bottom left of the rotated bounding box + (x3, y3) refer to bottom right of the rotated bounding box + (x4, y4) refer to top right of the rotated bounding box + (w, h) refers to width and height of rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + Args: + boxes (Tensor(N, 8)): rotated boxes in (x1, y1, x2, y2, x3, y3, x4, y4) format. + + Returns: + boxes (Tensor[N, 5]): rotated boxes in (x1, y1, w, h, r) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + x1, y1, x2, y2, x3, y3, x4, y4 = boxes.unbind(-1) + r_rad = torch.atan2(y1 - y2, x2 - x1) + r = r_rad * 180 / torch.pi + + w = ((x2 - x1) ** 2 + (y1 - y2) ** 2).sqrt() + h = ((x3 - x2) ** 2 + (y3 - y2) ** 2).sqrt() + + boxes = torch.stack((x1, y1, w, h, r), dim=-1) + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_register_onnx_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_register_onnx_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd263a5d8ef497becc4aa39252a93c913b84880 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_register_onnx_ops.py @@ -0,0 +1,107 @@ +import sys +import warnings + +import torch +from torch.onnx import symbolic_opset11 as opset11 +from torch.onnx.symbolic_helper import parse_args + +_ONNX_OPSET_VERSION_11 = 11 +_ONNX_OPSET_VERSION_16 = 16 +BASE_ONNX_OPSET_VERSION = _ONNX_OPSET_VERSION_11 + + +@parse_args("v", "v", "f") +def symbolic_multi_label_nms(g, boxes, scores, iou_threshold): + boxes = opset11.unsqueeze(g, boxes, 0) + scores = opset11.unsqueeze(g, opset11.unsqueeze(g, scores, 0), 0) + max_output_per_class = g.op("Constant", value_t=torch.tensor([sys.maxsize], dtype=torch.long)) + iou_threshold = g.op("Constant", value_t=torch.tensor([iou_threshold], dtype=torch.float)) + + # Cast boxes and scores to float32 in case they are float64 inputs + nms_out = g.op( + "NonMaxSuppression", + g.op("Cast", boxes, to_i=torch.onnx.TensorProtoDataType.FLOAT), + g.op("Cast", scores, to_i=torch.onnx.TensorProtoDataType.FLOAT), + max_output_per_class, + iou_threshold, + ) + return opset11.squeeze( + g, opset11.select(g, nms_out, 1, g.op("Constant", value_t=torch.tensor([2], dtype=torch.long))), 1 + ) + + +def _process_batch_indices_for_roi_align(g, rois): + indices = opset11.squeeze( + g, opset11.select(g, rois, 1, g.op("Constant", value_t=torch.tensor([0], dtype=torch.long))), 1 + ) + return g.op("Cast", indices, to_i=torch.onnx.TensorProtoDataType.INT64) + + +def _process_rois_for_roi_align(g, rois): + return opset11.select(g, rois, 1, g.op("Constant", value_t=torch.tensor([1, 2, 3, 4], dtype=torch.long))) + + +def _process_sampling_ratio_for_roi_align(g, sampling_ratio: int): + if sampling_ratio < 0: + warnings.warn( + "ONNX export for RoIAlign with a non-zero sampling_ratio is not supported. " + "The model will be exported with a sampling_ratio of 0." + ) + sampling_ratio = 0 + return sampling_ratio + + +@parse_args("v", "v", "f", "i", "i", "i", "i") +def roi_align_opset11(g, input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + batch_indices = _process_batch_indices_for_roi_align(g, rois) + rois = _process_rois_for_roi_align(g, rois) + if aligned: + warnings.warn( + "ROIAlign with aligned=True is only supported in opset >= 16. " + "Please export with opset 16 or higher, or use aligned=False." + ) + sampling_ratio = _process_sampling_ratio_for_roi_align(g, sampling_ratio) + return g.op( + "RoiAlign", + input, + rois, + batch_indices, + spatial_scale_f=spatial_scale, + output_height_i=pooled_height, + output_width_i=pooled_width, + sampling_ratio_i=sampling_ratio, + ) + + +@parse_args("v", "v", "f", "i", "i", "i", "i") +def roi_align_opset16(g, input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + batch_indices = _process_batch_indices_for_roi_align(g, rois) + rois = _process_rois_for_roi_align(g, rois) + coordinate_transformation_mode = "half_pixel" if aligned else "output_half_pixel" + sampling_ratio = _process_sampling_ratio_for_roi_align(g, sampling_ratio) + return g.op( + "RoiAlign", + input, + rois, + batch_indices, + coordinate_transformation_mode_s=coordinate_transformation_mode, + spatial_scale_f=spatial_scale, + output_height_i=pooled_height, + output_width_i=pooled_width, + sampling_ratio_i=sampling_ratio, + ) + + +@parse_args("v", "v", "f", "i", "i") +def roi_pool(g, input, rois, spatial_scale, pooled_height, pooled_width): + roi_pool = g.op( + "MaxRoiPool", input, rois, pooled_shape_i=(pooled_height, pooled_width), spatial_scale_f=spatial_scale + ) + return roi_pool, None + + +def _register_custom_op(): + torch.onnx.register_custom_op_symbolic("torchvision::nms", symbolic_multi_label_nms, _ONNX_OPSET_VERSION_11) + torch.onnx.register_custom_op_symbolic("torchvision::roi_align", roi_align_opset11, _ONNX_OPSET_VERSION_11) + torch.onnx.register_custom_op_symbolic("torchvision::roi_align", roi_align_opset16, _ONNX_OPSET_VERSION_16) + torch.onnx.register_custom_op_symbolic("torchvision::roi_pool", roi_pool, _ONNX_OPSET_VERSION_11) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..40bae605d028d3f522531711a1e28298b63ffbfc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/_utils.py @@ -0,0 +1,106 @@ +from typing import Optional, Union + +import torch +from torch import nn, Tensor + + +def _cat(tensors: list[Tensor], dim: int = 0) -> Tensor: + """ + Efficient version of torch.cat that avoids a copy if there is only a single element in a list + """ + # TODO add back the assert + # assert isinstance(tensors, (list, tuple)) + if len(tensors) == 1: + return tensors[0] + return torch.cat(tensors, dim) + + +def convert_boxes_to_roi_format(boxes: list[Tensor]) -> Tensor: + concat_boxes = _cat([b for b in boxes], dim=0) + temp = [] + for i, b in enumerate(boxes): + temp.append(torch.full_like(b[:, :1], i)) + ids = _cat(temp, dim=0) + rois = torch.cat([ids, concat_boxes], dim=1) + return rois + + +def check_roi_boxes_shape(boxes: Union[Tensor, list[Tensor]]): + if isinstance(boxes, (list, tuple)): + for _tensor in boxes: + torch._assert( + _tensor.size(1) == 4, "The shape of the tensor in the boxes list is not correct as List[Tensor[L, 4]]" + ) + elif isinstance(boxes, torch.Tensor): + torch._assert(boxes.size(1) == 5, "The boxes tensor shape is not correct as Tensor[K, 5]") + else: + torch._assert(False, "boxes is expected to be a Tensor[L, 5] or a List[Tensor[K, 4]]") + return + + +def split_normalization_params( + model: nn.Module, norm_classes: Optional[list[type]] = None +) -> tuple[list[Tensor], list[Tensor]]: + # Adapted from https://github.com/facebookresearch/ClassyVision/blob/659d7f78/classy_vision/generic/util.py#L501 + if not norm_classes: + norm_classes = [ + nn.modules.batchnorm._BatchNorm, + nn.LayerNorm, + nn.GroupNorm, + nn.modules.instancenorm._InstanceNorm, + nn.LocalResponseNorm, + ] + + for t in norm_classes: + if not issubclass(t, nn.Module): + raise ValueError(f"Class {t} is not a subclass of nn.Module.") + + classes = tuple(norm_classes) + + norm_params = [] + other_params = [] + for module in model.modules(): + if next(module.children(), None): + other_params.extend(p for p in module.parameters(recurse=False) if p.requires_grad) + elif isinstance(module, classes): + norm_params.extend(p for p in module.parameters() if p.requires_grad) + else: + other_params.extend(p for p in module.parameters() if p.requires_grad) + return norm_params, other_params + + +def _upcast(t: Tensor) -> Tensor: + # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type + if t.is_floating_point(): + return t if t.dtype in (torch.float32, torch.float64) else t.float() + else: + return t if t.dtype in (torch.int32, torch.int64) else t.int() + + +def _upcast_non_float(t: Tensor) -> Tensor: + # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type + if t.dtype not in (torch.float32, torch.float64): + return t.float() + return t + + +def _loss_inter_union( + boxes1: torch.Tensor, + boxes2: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + + # Intersection keypoints + xkis1 = torch.max(x1, x1g) + ykis1 = torch.max(y1, y1g) + xkis2 = torch.min(x2, x2g) + ykis2 = torch.min(y2, y2g) + + intsctk = torch.zeros_like(x1) + mask = (ykis2 > ykis1) & (xkis2 > xkis1) + intsctk[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask]) + unionk = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsctk + + return intsctk, unionk diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/boxes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..54f8d6b86e9720ca4656c965b565b623204b2064 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/boxes.py @@ -0,0 +1,520 @@ +import torch +import torchvision +from torch import Tensor +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._box_convert import ( + _box_cxcywh_to_xyxy, + _box_cxcywhr_to_xywhr, + _box_xywh_to_xyxy, + _box_xywhr_to_cxcywhr, + _box_xywhr_to_xyxyxyxy, + _box_xyxy_to_cxcywh, + _box_xyxy_to_xywh, + _box_xyxyxyxy_to_xywhr, +) +from ._utils import _upcast + + +def nms(boxes: Tensor, scores: Tensor, iou_threshold: float) -> Tensor: + """ + Performs non-maximum suppression (NMS) on the boxes according + to their intersection-over-union (IoU). + + NMS iteratively removes lower scoring boxes which have an + IoU greater than ``iou_threshold`` with another (higher scoring) + box. + + If multiple boxes have the exact same score and satisfy the IoU + criterion with respect to a reference box, the selected box is + not guaranteed to be the same between CPU and GPU. This is similar + to the behavior of argsort in PyTorch when repeated values are present. + + Args: + boxes (Tensor[N, 4])): boxes to perform NMS on. They + are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and + ``0 <= y1 < y2``. + scores (Tensor[N]): scores for each one of the boxes + iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold + + Returns: + Tensor: int64 tensor with the indices of the elements that have been kept + by NMS, sorted in decreasing order of scores + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(nms) + _assert_has_ops() + return torch.ops.torchvision.nms(boxes, scores, iou_threshold) + + +def batched_nms( + boxes: Tensor, + scores: Tensor, + idxs: Tensor, + iou_threshold: float, +) -> Tensor: + """ + Performs non-maximum suppression in a batched fashion. + + Each index value correspond to a category, and NMS + will not be applied between elements of different categories. + + Args: + boxes (Tensor[N, 4]): boxes where NMS will be performed. They + are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and + ``0 <= y1 < y2``. + scores (Tensor[N]): scores for each one of the boxes + idxs (Tensor[N]): indices of the categories for each one of the boxes. + iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold + + Returns: + Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted + in decreasing order of scores + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(batched_nms) + # Benchmarks that drove the following thresholds are at + # https://github.com/pytorch/vision/issues/1311#issuecomment-781329339 + # and https://github.com/pytorch/vision/pull/8925 + if boxes.numel() > (4000 if boxes.device.type == "cpu" else 100_000) and not torchvision._is_tracing(): + return _batched_nms_vanilla(boxes, scores, idxs, iou_threshold) + else: + return _batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold) + + +@torch.jit._script_if_tracing +def _batched_nms_coordinate_trick( + boxes: Tensor, + scores: Tensor, + idxs: Tensor, + iou_threshold: float, +) -> Tensor: + # strategy: in order to perform NMS independently per class, + # we add an offset to all the boxes. The offset is dependent + # only on the class idx, and is large enough so that boxes + # from different classes do not overlap + if boxes.numel() == 0: + return torch.empty((0,), dtype=torch.int64, device=boxes.device) + max_coordinate = boxes.max() + offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes)) + boxes_for_nms = boxes + offsets[:, None] + keep = nms(boxes_for_nms, scores, iou_threshold) + return keep + + +@torch.jit._script_if_tracing +def _batched_nms_vanilla( + boxes: Tensor, + scores: Tensor, + idxs: Tensor, + iou_threshold: float, +) -> Tensor: + # Based on Detectron2 implementation, just manually call nms() on each class independently + keep_mask = torch.zeros_like(scores, dtype=torch.bool) + for class_id in torch.unique(idxs): + curr_indices = torch.where(idxs == class_id)[0] + curr_keep_indices = nms(boxes[curr_indices], scores[curr_indices], iou_threshold) + keep_mask[curr_indices[curr_keep_indices]] = True + keep_indices = torch.where(keep_mask)[0] + return keep_indices[scores[keep_indices].sort(descending=True)[1]] + + +def remove_small_boxes(boxes: Tensor, min_size: float) -> Tensor: + """ + Remove every box from ``boxes`` which contains at least one side length + that is smaller than ``min_size``. + + .. note:: + For sanitizing a :class:`~torchvision.tv_tensors.BoundingBoxes` object, consider using + the transform :func:`~torchvision.transforms.v2.SanitizeBoundingBoxes` instead. + + Args: + boxes (Tensor[..., 4]): boxes in ``(x1, y1, x2, y2)`` format + with ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + min_size (float): minimum size + + Returns: + Tensor[K]: indices of the boxes that have both sides + larger than ``min_size`` + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(remove_small_boxes) + ws, hs = boxes[..., 2] - boxes[..., 0], boxes[..., 3] - boxes[..., 1] + keep = (ws >= min_size) & (hs >= min_size) + keep = torch.where(keep)[0] + return keep + + +def clip_boxes_to_image(boxes: Tensor, size: tuple[int, int]) -> Tensor: + """ + Clip boxes so that they lie inside an image of size ``size``. + + .. note:: + For clipping a :class:`~torchvision.tv_tensors.BoundingBoxes` object, consider using + the transform :func:`~torchvision.transforms.v2.ClampBoundingBoxes` instead. + + Args: + boxes (Tensor[..., 4]): boxes in ``(x1, y1, x2, y2)`` format + with ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + size (Tuple[height, width]): size of the image + + Returns: + Tensor[..., 4]: clipped boxes + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(clip_boxes_to_image) + dim = boxes.dim() + boxes_x = boxes[..., 0::2] + boxes_y = boxes[..., 1::2] + height, width = size + + if torchvision._is_tracing(): + boxes_x = torch.max(boxes_x, torch.tensor(0, dtype=boxes.dtype, device=boxes.device)) + boxes_x = torch.min(boxes_x, torch.tensor(width, dtype=boxes.dtype, device=boxes.device)) + boxes_y = torch.max(boxes_y, torch.tensor(0, dtype=boxes.dtype, device=boxes.device)) + boxes_y = torch.min(boxes_y, torch.tensor(height, dtype=boxes.dtype, device=boxes.device)) + else: + boxes_x = boxes_x.clamp(min=0, max=width) + boxes_y = boxes_y.clamp(min=0, max=height) + + clipped_boxes = torch.stack((boxes_x, boxes_y), dim=dim) + return clipped_boxes.reshape(boxes.shape) + + +def box_convert(boxes: Tensor, in_fmt: str, out_fmt: str) -> Tensor: + """ + Converts :class:`torch.Tensor` boxes from a given ``in_fmt`` to ``out_fmt``. + + .. note:: + For converting a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.BoundingBoxes` object + between different formats, + consider using :func:`~torchvision.transforms.v2.functional.convert_bounding_box_format` instead. + Or see the corresponding transform :func:`~torchvision.transforms.v2.ConvertBoundingBoxFormat`. + + Supported ``in_fmt`` and ``out_fmt`` strings are: + + ``'xyxy'``: boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right. + This is the format that torchvision utilities expect. + + ``'xywh'``: boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height. + + ``'cxcywh'``: boxes are represented via centre, width and height, cx, cy being center of box, w, h + being width and height. + + ``'xywhr'``: boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height. + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + ``'cxcywhr'``: boxes are represented via centre, width and height, cx, cy being center of box, w, h + being width and height. + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + ``'xyxyxyxy'``: boxes are represented via corners, x1, y1 being top left, x2, y2 top right, + x3, y3 bottom right, and x4, y4 bottom left. + + Args: + boxes (Tensor[N, K]): boxes which will be converted. K is the number of coordinates (4 for unrotated bounding boxes, 5 or 8 for rotated bounding boxes) + in_fmt (str): Input format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh', 'xywhr', 'cxcywhr', 'xyxyxyxy']. + out_fmt (str): Output format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh', 'xywhr', 'cxcywhr', 'xyxyxyxy'] + + Returns: + Tensor[N, K]: Boxes into converted format. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(box_convert) + allowed_fmts = ( + "xyxy", + "xywh", + "cxcywh", + "xywhr", + "cxcywhr", + "xyxyxyxy", + ) + if in_fmt not in allowed_fmts or out_fmt not in allowed_fmts: + raise ValueError(f"Unsupported Bounding Box Conversions for given in_fmt {in_fmt} and out_fmt {out_fmt}") + + if in_fmt == out_fmt: + return boxes.clone() + e = (in_fmt, out_fmt) + if e == ("xywh", "xyxy"): + boxes = _box_xywh_to_xyxy(boxes) + elif e == ("cxcywh", "xyxy"): + boxes = _box_cxcywh_to_xyxy(boxes) + elif e == ("xyxy", "xywh"): + boxes = _box_xyxy_to_xywh(boxes) + elif e == ("xyxy", "cxcywh"): + boxes = _box_xyxy_to_cxcywh(boxes) + elif e == ("xywh", "cxcywh"): + boxes = _box_xywh_to_xyxy(boxes) + boxes = _box_xyxy_to_cxcywh(boxes) + elif e == ("cxcywh", "xywh"): + boxes = _box_cxcywh_to_xyxy(boxes) + boxes = _box_xyxy_to_xywh(boxes) + elif e == ("cxcywhr", "xywhr"): + boxes = _box_cxcywhr_to_xywhr(boxes) + elif e == ("xywhr", "cxcywhr"): + boxes = _box_xywhr_to_cxcywhr(boxes) + elif e == ("cxcywhr", "xyxyxyxy"): + boxes = _box_cxcywhr_to_xywhr(boxes).to(boxes.dtype) + boxes = _box_xywhr_to_xyxyxyxy(boxes) + elif e == ("xyxyxyxy", "cxcywhr"): + boxes = _box_xyxyxyxy_to_xywhr(boxes).to(boxes.dtype) + boxes = _box_xywhr_to_cxcywhr(boxes) + elif e == ("xywhr", "xyxyxyxy"): + boxes = _box_xywhr_to_xyxyxyxy(boxes) + elif e == ("xyxyxyxy", "xywhr"): + boxes = _box_xyxyxyxy_to_xywhr(boxes) + else: + raise NotImplementedError(f"Unsupported Bounding Box Conversions for given in_fmt {e[0]} and out_fmt {e[1]}") + + return boxes + + +def box_area(boxes: Tensor, fmt: str = "xyxy") -> Tensor: + """ + Computes the area of a set of bounding boxes from a given format. + + Args: + boxes (Tensor[..., 4]): boxes for which the area will be computed. + fmt (str): Format of the input boxes. + Default is "xyxy" to preserve backward compatibility. + Supported formats are "xyxy", "xywh", and "cxcywh". + + Returns: + Tensor[N]: Tensor containing the area for each box. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(box_area) + allowed_fmts = ( + "xyxy", + "xywh", + "cxcywh", + ) + if fmt not in allowed_fmts: + raise ValueError(f"Unsupported Bounding Box area for given format {fmt}") + boxes = _upcast(boxes) + if fmt == "xyxy": + area = (boxes[..., 2] - boxes[..., 0]) * (boxes[..., 3] - boxes[..., 1]) + else: + # For formats with width and height, area = width * height + # Supported: cxcywh, xywh + area = boxes[..., 2] * boxes[..., 3] + + return area + + +# implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py +# with slight modifications +def _box_inter_union(boxes1: Tensor, boxes2: Tensor, fmt: str = "xyxy") -> tuple[Tensor, Tensor]: + area1 = box_area(boxes1, fmt=fmt) + area2 = box_area(boxes2, fmt=fmt) + + allowed_fmts = ( + "xyxy", + "xywh", + "cxcywh", + ) + if fmt not in allowed_fmts: + raise ValueError(f"Unsupported Box IoU Calculation for given fmt {fmt}.") + + if fmt == "xyxy": + lt = torch.max(boxes1[..., None, :2], boxes2[..., None, :, :2]) # [...,N,M,2] + rb = torch.min(boxes1[..., None, 2:], boxes2[..., None, :, 2:]) # [...,N,M,2] + elif fmt == "xywh": + lt = torch.max(boxes1[..., None, :2], boxes2[..., None, :, :2]) # [...,N,M,2] + rb = torch.min( + boxes1[..., None, :2] + boxes1[..., None, 2:], boxes2[..., None, :, :2] + boxes2[..., None, :, 2:] + ) # [...,N,M,2] + else: # fmt == "cxcywh": + lt = torch.max( + boxes1[..., None, :2] - boxes1[..., None, 2:] / 2, boxes2[..., None, :, :2] - boxes2[..., None, :, 2:] / 2 + ) # [N,M,2] + rb = torch.min( + boxes1[..., None, :2] + boxes1[..., None, 2:] / 2, boxes2[..., None, :, :2] + boxes2[..., None, :, 2:] / 2 + ) # [N,M,2] + + wh = _upcast(rb - lt).clamp(min=0) # [N,M,2] + inter = wh[..., 0] * wh[..., 1] # [N,M] + + union = area1[..., None] + area2[..., None, :] - inter + + return inter, union + + +def box_iou(boxes1: Tensor, boxes2: Tensor, fmt: str = "xyxy") -> Tensor: + """ + Return intersection-over-union (Jaccard index) between two sets of boxes from a given format. + + Args: + boxes1 (Tensor[..., N, 4]): first set of boxes + boxes2 (Tensor[..., M, 4]): second set of boxes + fmt (str): Format of the input boxes. + Default is "xyxy" to preserve backward compatibility. + Supported formats are "xyxy", "xywh", and "cxcywh". + + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise IoU values for every element + in boxes1 and boxes2 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(box_iou) + allowed_fmts = ( + "xyxy", + "xywh", + "cxcywh", + ) + if fmt not in allowed_fmts: + raise ValueError(f"Unsupported Box IoU Calculation for given format {fmt}.") + inter, union = _box_inter_union(boxes1, boxes2, fmt=fmt) + iou = inter / union + return iou + + +# Implementation adapted from https://github.com/facebookresearch/detr/blob/master/util/box_ops.py +def generalized_box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor: + """ + Return generalized intersection-over-union (Jaccard index) between two sets of boxes. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + + Args: + boxes1 (Tensor[..., N, 4]): first set of boxes + boxes2 (Tensor[..., M, 4]): second set of boxes + + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise generalized IoU values + for every element in boxes1 and boxes2 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(generalized_box_iou) + + inter, union = _box_inter_union(boxes1, boxes2) + iou = inter / union + + lti = torch.min(boxes1[..., None, :2], boxes2[..., None, :, :2]) + rbi = torch.max(boxes1[..., None, 2:], boxes2[..., None, :, 2:]) + + whi = _upcast(rbi - lti).clamp(min=0) # [N,M,2] + areai = whi[..., 0] * whi[..., 1] + + return iou - (areai - union) / areai + + +def complete_box_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> Tensor: + """ + Return complete intersection-over-union (Jaccard index) between two sets of boxes. + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + Args: + boxes1 (Tensor[..., N, 4]): first set of boxes + boxes2 (Tensor[..., M, 4]): second set of boxes + eps (float, optional): small number to prevent division by zero. Default: 1e-7 + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise complete IoU values + for every element in boxes1 and boxes2 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(complete_box_iou) + + boxes1 = _upcast(boxes1) + boxes2 = _upcast(boxes2) + + diou, iou = _box_diou_iou(boxes1, boxes2, eps) + + w_pred = boxes1[..., None, 2] - boxes1[..., None, 0] + h_pred = boxes1[..., None, 3] - boxes1[..., None, 1] + + w_gt = boxes2[..., None, :, 2] - boxes2[..., None, :, 0] + h_gt = boxes2[..., None, :, 3] - boxes2[..., None, :, 1] + + v = (4 / (torch.pi**2)) * torch.pow(torch.atan(w_pred / h_pred) - torch.atan(w_gt / h_gt), 2) + with torch.no_grad(): + alpha = v / (1 - iou + v + eps) + return diou - alpha * v + + +def distance_box_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> Tensor: + """ + Return distance intersection-over-union (Jaccard index) between two sets of boxes. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + + Args: + boxes1 (Tensor[..., N, 4]): first set of boxes + boxes2 (Tensor[..., M, 4]): second set of boxes + eps (float, optional): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise distance IoU values + for every element in boxes1 and boxes2 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(distance_box_iou) + + boxes1 = _upcast(boxes1) + boxes2 = _upcast(boxes2) + diou, _ = _box_diou_iou(boxes1, boxes2, eps=eps) + return diou + + +def _box_diou_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> tuple[Tensor, Tensor]: + + iou = box_iou(boxes1, boxes2) + lti = torch.min(boxes1[..., None, :2], boxes2[..., None, :, :2]) + rbi = torch.max(boxes1[..., None, 2:], boxes2[..., None, :, 2:]) + whi = _upcast(rbi - lti).clamp(min=0) # [N,M,2] + diagonal_distance_squared = (whi[..., 0] ** 2) + (whi[..., 1] ** 2) + eps + # centers of boxes + x_p = (boxes1[..., 0] + boxes1[..., 2]) / 2 + y_p = (boxes1[..., 1] + boxes1[..., 3]) / 2 + x_g = (boxes2[..., 0] + boxes2[..., 2]) / 2 + y_g = (boxes2[..., 1] + boxes2[..., 3]) / 2 + # The distance between boxes' centers squared. + centers_distance_squared = (_upcast(x_p[..., None] - x_g[..., None, :]) ** 2) + ( + _upcast(y_p[..., None] - y_g[..., None, :]) ** 2 + ) + # The distance IoU is the IoU penalized by a normalized + # distance between boxes' centers squared. + return iou - (centers_distance_squared / diagonal_distance_squared), iou + + +def masks_to_boxes(masks: torch.Tensor) -> torch.Tensor: + """ + Compute the bounding boxes around the provided masks. + + Returns a [N, 4] tensor containing bounding boxes. The boxes are in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 <= x2`` and ``0 <= y1 <= y2``. + + .. warning:: + + In most cases the output will guarantee ``x1 < x2`` and ``y1 < y2``. But + if the input is degenerate, e.g. if a mask is a single row or a single + column, then the output may have x1 = x2 or y1 = y2. + + Args: + masks (Tensor[N, H, W]): masks to transform where N is the number of masks + and (H, W) are the spatial dimensions. + + Returns: + Tensor[N, 4]: bounding boxes + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(masks_to_boxes) + if masks.numel() == 0: + return torch.zeros((0, 4), device=masks.device, dtype=torch.float) + + n = masks.shape[0] + + bounding_boxes = torch.zeros((n, 4), device=masks.device, dtype=torch.float) + + for index, mask in enumerate(masks): + y, x = torch.where(mask != 0) + + bounding_boxes[index, 0] = torch.min(x) + bounding_boxes[index, 1] = torch.min(y) + bounding_boxes[index, 2] = torch.max(x) + bounding_boxes[index, 3] = torch.max(y) + + return bounding_boxes diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ciou_loss.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ciou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..d825e79dff0953389897195785b34cbf905f01e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ciou_loss.py @@ -0,0 +1,77 @@ +import torch + +from ..utils import _log_api_usage_once +from ._utils import _upcast_non_float +from .diou_loss import _diou_iou_loss + + +def complete_box_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + reduction: str = "none", + eps: float = 1e-7, +) -> torch.Tensor: + """ + Gradient-friendly IoU loss with an additional penalty that is non-zero when the + boxes do not overlap. This loss function considers important geometrical + factors such as overlap area, normalized central point distance and aspect ratio. + This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the + same dimensions. + + Args: + boxes1 : (Tensor[N, 4] or Tensor[4]) first set of boxes + boxes2 : (Tensor[N, 4] or Tensor[4]) second set of boxes + reduction : (string, optional) Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be + applied to the output. ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'`` + eps : (float): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor: Loss tensor with the reduction option applied. + + Reference: + Zhaohui Zheng et al.: Complete Intersection over Union Loss: + https://arxiv.org/abs/1911.08287 + + """ + + # Original Implementation from https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/losses.py + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(complete_box_iou_loss) + + boxes1 = _upcast_non_float(boxes1) + boxes2 = _upcast_non_float(boxes2) + + diou_loss, iou = _diou_iou_loss(boxes1, boxes2) + + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + + # width and height of boxes + w_pred = x2 - x1 + h_pred = y2 - y1 + w_gt = x2g - x1g + h_gt = y2g - y1g + v = (4 / (torch.pi**2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2) + with torch.no_grad(): + alpha = v / (1 - iou + v + eps) + + loss = diou_loss + alpha * v + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/deform_conv.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/deform_conv.py new file mode 100644 index 0000000000000000000000000000000000000000..da13ee6da9a69770ca321f1dc74a19382e4b7c20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/deform_conv.py @@ -0,0 +1,195 @@ +import math +from typing import Optional + +import torch +from torch import nn, Tensor +from torch.nn import init +from torch.nn.modules.utils import _pair +from torch.nn.parameter import Parameter +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once + + +def deform_conv2d( + input: Tensor, + offset: Tensor, + weight: Tensor, + bias: Optional[Tensor] = None, + stride: tuple[int, int] = (1, 1), + padding: tuple[int, int] = (0, 0), + dilation: tuple[int, int] = (1, 1), + mask: Optional[Tensor] = None, +) -> Tensor: + r""" + Performs Deformable Convolution v2, described in + `Deformable ConvNets v2: More Deformable, Better Results + `__ if :attr:`mask` is not ``None`` and + Performs Deformable Convolution, described in + `Deformable Convolutional Networks + `__ if :attr:`mask` is ``None``. + + Args: + input (Tensor[batch_size, in_channels, in_height, in_width]): input tensor + offset (Tensor[batch_size, 2 * offset_groups * kernel_height * kernel_width, out_height, out_width]): + offsets to be applied for each position in the convolution kernel. + weight (Tensor[out_channels, in_channels // groups, kernel_height, kernel_width]): convolution weights, + split into groups of size (in_channels // groups) + bias (Tensor[out_channels]): optional bias of shape (out_channels,). Default: None + stride (int or Tuple[int, int]): distance between convolution centers. Default: 1 + padding (int or Tuple[int, int]): height/width of padding of zeroes around + each image. Default: 0 + dilation (int or Tuple[int, int]): the spacing between kernel elements. Default: 1 + mask (Tensor[batch_size, offset_groups * kernel_height * kernel_width, out_height, out_width]): + masks to be applied for each position in the convolution kernel. Default: None + + Returns: + Tensor[batch_sz, out_channels, out_h, out_w]: result of convolution + + Examples:: + >>> input = torch.rand(4, 3, 10, 10) + >>> kh, kw = 3, 3 + >>> weight = torch.rand(5, 3, kh, kw) + >>> # offset and mask should have the same spatial size as the output + >>> # of the convolution. In this case, for an input of 10, stride of 1 + >>> # and kernel size of 3, without padding, the output size is 8 + >>> offset = torch.rand(4, 2 * kh * kw, 8, 8) + >>> mask = torch.rand(4, kh * kw, 8, 8) + >>> out = deform_conv2d(input, offset, weight, mask=mask) + >>> print(out.shape) + >>> # returns + >>> torch.Size([4, 5, 8, 8]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(deform_conv2d) + _assert_has_ops() + out_channels = weight.shape[0] + + use_mask = mask is not None + + if mask is None: + mask = torch.zeros((input.shape[0], 1), device=input.device, dtype=input.dtype) + + if bias is None: + bias = torch.zeros(out_channels, device=input.device, dtype=input.dtype) + + stride_h, stride_w = _pair(stride) + pad_h, pad_w = _pair(padding) + dil_h, dil_w = _pair(dilation) + weights_h, weights_w = weight.shape[-2:] + _, n_in_channels, _, _ = input.shape + + n_offset_grps = offset.shape[1] // (2 * weights_h * weights_w) + n_weight_grps = n_in_channels // weight.shape[1] + + if n_offset_grps == 0: + raise RuntimeError( + "the shape of the offset tensor at dimension 1 is not valid. It should " + "be a multiple of 2 * weight.size[2] * weight.size[3].\n" + f"Got offset.shape[1]={offset.shape[1]}, while 2 * weight.size[2] * weight.size[3]={2 * weights_h * weights_w}" + ) + + return torch.ops.torchvision.deform_conv2d( + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dil_h, + dil_w, + n_weight_grps, + n_offset_grps, + use_mask, + ) + + +class DeformConv2d(nn.Module): + """ + See :func:`deform_conv2d`. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int = 1, + padding: int = 0, + dilation: int = 1, + groups: int = 1, + bias: bool = True, + ): + super().__init__() + _log_api_usage_once(self) + + if in_channels % groups != 0: + raise ValueError("in_channels must be divisible by groups") + if out_channels % groups != 0: + raise ValueError("out_channels must be divisible by groups") + + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = _pair(kernel_size) + self.stride = _pair(stride) + self.padding = _pair(padding) + self.dilation = _pair(dilation) + self.groups = groups + + self.weight = Parameter( + torch.empty(out_channels, in_channels // groups, self.kernel_size[0], self.kernel_size[1]) + ) + + if bias: + self.bias = Parameter(torch.empty(out_channels)) + else: + self.register_parameter("bias", None) + + self.reset_parameters() + + def reset_parameters(self) -> None: + init.kaiming_uniform_(self.weight, a=math.sqrt(5)) + + if self.bias is not None: + fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight) + bound = 1 / math.sqrt(fan_in) + init.uniform_(self.bias, -bound, bound) + + def forward(self, input: Tensor, offset: Tensor, mask: Optional[Tensor] = None) -> Tensor: + """ + Args: + input (Tensor[batch_size, in_channels, in_height, in_width]): input tensor + offset (Tensor[batch_size, 2 * offset_groups * kernel_height * kernel_width, out_height, out_width]): + offsets to be applied for each position in the convolution kernel. + mask (Tensor[batch_size, offset_groups * kernel_height * kernel_width, out_height, out_width]): + masks to be applied for each position in the convolution kernel. + """ + return deform_conv2d( + input, + offset, + self.weight, + self.bias, + stride=self.stride, + padding=self.padding, + dilation=self.dilation, + mask=mask, + ) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"{self.in_channels}" + f", {self.out_channels}" + f", kernel_size={self.kernel_size}" + f", stride={self.stride}" + ) + s += f", padding={self.padding}" if self.padding != (0, 0) else "" + s += f", dilation={self.dilation}" if self.dilation != (1, 1) else "" + s += f", groups={self.groups}" if self.groups != 1 else "" + s += ", bias=False" if self.bias is None else "" + s += ")" + + return s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/diou_loss.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/diou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..9381878ce1d81e853b370d8cc92681cfd3a5b5c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/diou_loss.py @@ -0,0 +1,91 @@ +import torch + +from ..utils import _log_api_usage_once +from ._utils import _loss_inter_union, _upcast_non_float + + +def distance_box_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + reduction: str = "none", + eps: float = 1e-7, +) -> torch.Tensor: + """ + Gradient-friendly IoU loss with an additional penalty that is non-zero when the + distance between boxes' centers isn't zero. Indeed, for two exactly overlapping + boxes, the distance IoU is the same as the IoU loss. + This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the + same dimensions. + + Args: + boxes1 (Tensor[N, 4]): first set of boxes + boxes2 (Tensor[N, 4]): second set of boxes + reduction (string, optional): Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be + applied to the output. ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'`` + eps (float, optional): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor: Loss tensor with the reduction option applied. + + Reference: + Zhaohui Zheng et al.: Distance Intersection over Union Loss: + https://arxiv.org/abs/1911.08287 + """ + + # Original Implementation from https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/losses.py + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(distance_box_iou_loss) + + boxes1 = _upcast_non_float(boxes1) + boxes2 = _upcast_non_float(boxes2) + + loss, _ = _diou_iou_loss(boxes1, boxes2, eps) + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss + + +def _diou_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + eps: float = 1e-7, +) -> tuple[torch.Tensor, torch.Tensor]: + + intsct, union = _loss_inter_union(boxes1, boxes2) + iou = intsct / (union + eps) + # smallest enclosing box + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + xc1 = torch.min(x1, x1g) + yc1 = torch.min(y1, y1g) + xc2 = torch.max(x2, x2g) + yc2 = torch.max(y2, y2g) + # The diagonal distance of the smallest enclosing box squared + diagonal_distance_squared = ((xc2 - xc1) ** 2) + ((yc2 - yc1) ** 2) + eps + # centers of boxes + x_p = (x2 + x1) / 2 + y_p = (y2 + y1) / 2 + x_g = (x1g + x2g) / 2 + y_g = (y1g + y2g) / 2 + # The distance between boxes' centers squared. + centers_distance_squared = ((x_p - x_g) ** 2) + ((y_p - y_g) ** 2) + # The distance IoU is the IoU penalized by a normalized + # distance between boxes' centers squared. + loss = 1 - iou + (centers_distance_squared / diagonal_distance_squared) + return loss, iou diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/drop_block.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/drop_block.py new file mode 100644 index 0000000000000000000000000000000000000000..eb80921e3afaf9d4163e4cbfe857e1218dd02337 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/drop_block.py @@ -0,0 +1,161 @@ +import torch +import torch.fx +import torch.nn.functional as F +from torch import nn, Tensor + +from ..utils import _log_api_usage_once + + +def drop_block2d( + input: Tensor, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06, training: bool = True +) -> Tensor: + """ + Implements DropBlock2d from `"DropBlock: A regularization method for convolutional networks" + `. + + Args: + input (Tensor[N, C, H, W]): The input tensor or 4-dimensions with the first one + being its batch i.e. a batch with ``N`` rows. + p (float): Probability of an element to be dropped. + block_size (int): Size of the block to drop. + inplace (bool): If set to ``True``, will do this operation in-place. Default: ``False``. + eps (float): A value added to the denominator for numerical stability. Default: 1e-6. + training (bool): apply dropblock if is ``True``. Default: ``True``. + + Returns: + Tensor[N, C, H, W]: The randomly zeroed tensor after dropblock. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(drop_block2d) + if p < 0.0 or p > 1.0: + raise ValueError(f"drop probability has to be between 0 and 1, but got {p}.") + if input.ndim != 4: + raise ValueError(f"input should be 4 dimensional. Got {input.ndim} dimensions.") + if not training or p == 0.0: + return input + + N, C, H, W = input.size() + block_size = min(block_size, W, H) + if block_size % 2 == 0: + raise ValueError(f"block size should be odd. Got {block_size} which is even.") + + # compute the gamma of Bernoulli distribution + gamma = (p * H * W) / ((block_size**2) * ((H - block_size + 1) * (W - block_size + 1))) + noise = torch.empty((N, C, H - block_size + 1, W - block_size + 1), dtype=input.dtype, device=input.device) + noise.bernoulli_(gamma) + + noise = F.pad(noise, [block_size // 2] * 4, value=0) + noise = F.max_pool2d(noise, stride=(1, 1), kernel_size=(block_size, block_size), padding=block_size // 2) + noise = 1 - noise + normalize_scale = noise.numel() / (eps + noise.sum()) + if inplace: + input.mul_(noise).mul_(normalize_scale) + else: + input = input * noise * normalize_scale + return input + + +def drop_block3d( + input: Tensor, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06, training: bool = True +) -> Tensor: + """ + Implements DropBlock3d from `"DropBlock: A regularization method for convolutional networks" + `. + + Args: + input (Tensor[N, C, D, H, W]): The input tensor or 5-dimensions with the first one + being its batch i.e. a batch with ``N`` rows. + p (float): Probability of an element to be dropped. + block_size (int): Size of the block to drop. + inplace (bool): If set to ``True``, will do this operation in-place. Default: ``False``. + eps (float): A value added to the denominator for numerical stability. Default: 1e-6. + training (bool): apply dropblock if is ``True``. Default: ``True``. + + Returns: + Tensor[N, C, D, H, W]: The randomly zeroed tensor after dropblock. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(drop_block3d) + if p < 0.0 or p > 1.0: + raise ValueError(f"drop probability has to be between 0 and 1, but got {p}.") + if input.ndim != 5: + raise ValueError(f"input should be 5 dimensional. Got {input.ndim} dimensions.") + if not training or p == 0.0: + return input + + N, C, D, H, W = input.size() + block_size = min(block_size, D, H, W) + if block_size % 2 == 0: + raise ValueError(f"block size should be odd. Got {block_size} which is even.") + + # compute the gamma of Bernoulli distribution + gamma = (p * D * H * W) / ((block_size**3) * ((D - block_size + 1) * (H - block_size + 1) * (W - block_size + 1))) + noise = torch.empty( + (N, C, D - block_size + 1, H - block_size + 1, W - block_size + 1), dtype=input.dtype, device=input.device + ) + noise.bernoulli_(gamma) + + noise = F.pad(noise, [block_size // 2] * 6, value=0) + noise = F.max_pool3d( + noise, stride=(1, 1, 1), kernel_size=(block_size, block_size, block_size), padding=block_size // 2 + ) + noise = 1 - noise + normalize_scale = noise.numel() / (eps + noise.sum()) + if inplace: + input.mul_(noise).mul_(normalize_scale) + else: + input = input * noise * normalize_scale + return input + + +torch.fx.wrap("drop_block2d") + + +class DropBlock2d(nn.Module): + """ + See :func:`drop_block2d`. + """ + + def __init__(self, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06) -> None: + super().__init__() + + self.p = p + self.block_size = block_size + self.inplace = inplace + self.eps = eps + + def forward(self, input: Tensor) -> Tensor: + """ + Args: + input (Tensor): Input feature map on which some areas will be randomly + dropped. + Returns: + Tensor: The tensor after DropBlock layer. + """ + return drop_block2d(input, self.p, self.block_size, self.inplace, self.eps, self.training) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(p={self.p}, block_size={self.block_size}, inplace={self.inplace})" + return s + + +torch.fx.wrap("drop_block3d") + + +class DropBlock3d(DropBlock2d): + """ + See :func:`drop_block3d`. + """ + + def __init__(self, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06) -> None: + super().__init__(p, block_size, inplace, eps) + + def forward(self, input: Tensor) -> Tensor: + """ + Args: + input (Tensor): Input feature map on which some areas will be randomly + dropped. + Returns: + Tensor: The tensor after DropBlock layer. + """ + return drop_block3d(input, self.p, self.block_size, self.inplace, self.eps, self.training) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/feature_pyramid_network.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/feature_pyramid_network.py new file mode 100644 index 0000000000000000000000000000000000000000..5c85e19a6996e38b5b1a5a5690708d2c9ff99dff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/feature_pyramid_network.py @@ -0,0 +1,250 @@ +from collections import OrderedDict +from typing import Callable, Optional + +import torch.nn.functional as F +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation +from ..utils import _log_api_usage_once + + +class ExtraFPNBlock(nn.Module): + """ + Base class for the extra block in the FPN. + + Args: + results (List[Tensor]): the result of the FPN + x (List[Tensor]): the original feature maps + names (List[str]): the names for each one of the + original feature maps + + Returns: + results (List[Tensor]): the extended set of results + of the FPN + names (List[str]): the extended set of names for the results + """ + + def forward( + self, + results: list[Tensor], + x: list[Tensor], + names: list[str], + ) -> tuple[list[Tensor], list[str]]: + pass + + +class FeaturePyramidNetwork(nn.Module): + """ + Module that adds a FPN from on top of a set of feature maps. This is based on + `"Feature Pyramid Network for Object Detection" `_. + + The feature maps are currently supposed to be in increasing depth + order. + + The input to the model is expected to be an OrderedDict[Tensor], containing + the feature maps on top of which the FPN will be added. + + Args: + in_channels_list (list[int]): number of channels for each feature map that + is passed to the module + out_channels (int): number of channels of the FPN representation + extra_blocks (ExtraFPNBlock or None): if provided, extra operations will + be performed. It is expected to take the fpn features, the original + features and the names of the original features as input, and returns + a new list of feature maps and their corresponding names + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + + Examples:: + + >>> m = torchvision.ops.FeaturePyramidNetwork([10, 20, 30], 5) + >>> # get some dummy data + >>> x = OrderedDict() + >>> x['feat0'] = torch.rand(1, 10, 64, 64) + >>> x['feat2'] = torch.rand(1, 20, 16, 16) + >>> x['feat3'] = torch.rand(1, 30, 8, 8) + >>> # compute the FPN on top of x + >>> output = m(x) + >>> print([(k, v.shape) for k, v in output.items()]) + >>> # returns + >>> [('feat0', torch.Size([1, 5, 64, 64])), + >>> ('feat2', torch.Size([1, 5, 16, 16])), + >>> ('feat3', torch.Size([1, 5, 8, 8]))] + + """ + + _version = 2 + + def __init__( + self, + in_channels_list: list[int], + out_channels: int, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + super().__init__() + _log_api_usage_once(self) + self.inner_blocks = nn.ModuleList() + self.layer_blocks = nn.ModuleList() + for in_channels in in_channels_list: + if in_channels == 0: + raise ValueError("in_channels=0 is currently not supported") + inner_block_module = Conv2dNormActivation( + in_channels, out_channels, kernel_size=1, padding=0, norm_layer=norm_layer, activation_layer=None + ) + layer_block_module = Conv2dNormActivation( + out_channels, out_channels, kernel_size=3, norm_layer=norm_layer, activation_layer=None + ) + self.inner_blocks.append(inner_block_module) + self.layer_blocks.append(layer_block_module) + + # initialize parameters now to avoid modifying the initialization of top_blocks + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_uniform_(m.weight, a=1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + if extra_blocks is not None: + if not isinstance(extra_blocks, ExtraFPNBlock): + raise TypeError(f"extra_blocks should be of type ExtraFPNBlock not {type(extra_blocks)}") + self.extra_blocks = extra_blocks + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + num_blocks = len(self.inner_blocks) + for block in ["inner_blocks", "layer_blocks"]: + for i in range(num_blocks): + for type in ["weight", "bias"]: + old_key = f"{prefix}{block}.{i}.{type}" + new_key = f"{prefix}{block}.{i}.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def get_result_from_inner_blocks(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.inner_blocks[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.inner_blocks) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.inner_blocks): + if i == idx: + out = module(x) + return out + + def get_result_from_layer_blocks(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.layer_blocks[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.layer_blocks) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.layer_blocks): + if i == idx: + out = module(x) + return out + + def forward(self, x: dict[str, Tensor]) -> dict[str, Tensor]: + """ + Computes the FPN for a set of feature maps. + + Args: + x (OrderedDict[Tensor]): feature maps for each feature level. + + Returns: + results (OrderedDict[Tensor]): feature maps after FPN layers. + They are ordered from the highest resolution first. + """ + # unpack OrderedDict into two lists for easier handling + names = list(x.keys()) + x = list(x.values()) + + last_inner = self.get_result_from_inner_blocks(x[-1], -1) + results = [] + results.append(self.get_result_from_layer_blocks(last_inner, -1)) + + for idx in range(len(x) - 2, -1, -1): + inner_lateral = self.get_result_from_inner_blocks(x[idx], idx) + feat_shape = inner_lateral.shape[-2:] + inner_top_down = F.interpolate(last_inner, size=feat_shape, mode="nearest") + last_inner = inner_lateral + inner_top_down + results.insert(0, self.get_result_from_layer_blocks(last_inner, idx)) + + if self.extra_blocks is not None: + results, names = self.extra_blocks(results, x, names) + + # make it back an OrderedDict + out = OrderedDict([(k, v) for k, v in zip(names, results)]) + + return out + + +class LastLevelMaxPool(ExtraFPNBlock): + """ + Applies a max_pool2d (not actual max_pool2d, we just subsample) on top of the last feature map + """ + + def forward( + self, + x: list[Tensor], + y: list[Tensor], + names: list[str], + ) -> tuple[list[Tensor], list[str]]: + names.append("pool") + # Use max pooling to simulate stride 2 subsampling + x.append(F.max_pool2d(x[-1], kernel_size=1, stride=2, padding=0)) + return x, names + + +class LastLevelP6P7(ExtraFPNBlock): + """ + This module is used in RetinaNet to generate extra layers, P6 and P7. + """ + + def __init__(self, in_channels: int, out_channels: int): + super().__init__() + self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) + self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) + for module in [self.p6, self.p7]: + nn.init.kaiming_uniform_(module.weight, a=1) + nn.init.constant_(module.bias, 0) + self.use_P5 = in_channels == out_channels + + def forward( + self, + p: list[Tensor], + c: list[Tensor], + names: list[str], + ) -> tuple[list[Tensor], list[str]]: + p5, c5 = p[-1], c[-1] + x = p5 if self.use_P5 else c5 + p6 = self.p6(x) + p7 = self.p7(F.relu(p6)) + p.extend([p6, p7]) + names.extend(["p6", "p7"]) + return p, names diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/focal_loss.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd781eaab54b3eec755c341f2678a58068e84eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/focal_loss.py @@ -0,0 +1,61 @@ +import torch +import torch.nn.functional as F + +from ..utils import _log_api_usage_once + + +def sigmoid_focal_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + alpha: float = 0.25, + gamma: float = 2, + reduction: str = "none", +) -> torch.Tensor: + """ + Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. + + Args: + inputs (Tensor): A float tensor of arbitrary shape. + The predictions for each example. + targets (Tensor): A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + alpha (float): Weighting factor in range [0, 1] to balance + positive vs negative examples or -1 for ignore. Default: ``0.25``. + gamma (float): Exponent of the modulating factor (1 - p_t) to + balance easy vs hard examples. Default: ``2``. + reduction (string): ``'none'`` | ``'mean'`` | ``'sum'`` + ``'none'``: No reduction will be applied to the output. + ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'``. + Returns: + Loss tensor with the reduction option applied. + """ + # Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py + + if not (0 <= alpha <= 1) and alpha != -1: + raise ValueError(f"Invalid alpha value: {alpha}. alpha must be in the range [0,1] or -1 for ignore.") + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(sigmoid_focal_loss) + p = torch.sigmoid(inputs) + ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + p_t = p * targets + (1 - p) * (1 - targets) + loss = ce_loss * ((1 - p_t) ** gamma) + + if alpha >= 0: + alpha_t = alpha * targets + (1 - alpha) * (1 - targets) + loss = alpha_t * loss + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/giou_loss.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/giou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..e56dcc16c7d84fe6ba0f59c0b60e30a84110fbb0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/giou_loss.py @@ -0,0 +1,75 @@ +import torch + +from ..utils import _log_api_usage_once +from ._utils import _loss_inter_union, _upcast_non_float + + +def generalized_box_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + reduction: str = "none", + eps: float = 1e-7, +) -> torch.Tensor: + """ + Gradient-friendly IoU loss with an additional penalty that is non-zero when the + boxes do not overlap and scales with the size of their smallest enclosing box. + This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the + same dimensions. + + Args: + boxes1 (Tensor[N, 4] or Tensor[4]): first set of boxes + boxes2 (Tensor[N, 4] or Tensor[4]): second set of boxes + reduction (string, optional): Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be + applied to the output. ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'`` + eps (float): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor: Loss tensor with the reduction option applied. + + Reference: + Hamid Rezatofighi et al.: Generalized Intersection over Union: + A Metric and A Loss for Bounding Box Regression: + https://arxiv.org/abs/1902.09630 + """ + + # Original implementation from https://github.com/facebookresearch/fvcore/blob/bfff2ef/fvcore/nn/giou_loss.py + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(generalized_box_iou_loss) + + boxes1 = _upcast_non_float(boxes1) + boxes2 = _upcast_non_float(boxes2) + intsctk, unionk = _loss_inter_union(boxes1, boxes2) + iouk = intsctk / (unionk + eps) + + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + + # smallest enclosing box + xc1 = torch.min(x1, x1g) + yc1 = torch.min(y1, y1g) + xc2 = torch.max(x2, x2g) + yc2 = torch.max(y2, y2g) + + area_c = (xc2 - xc1) * (yc2 - yc1) + miouk = iouk - ((area_c - unionk) / (area_c + eps)) + + loss = 1 - miouk + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/misc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..cfa1e23a5ee62a81784949157fb485b7529a37e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/misc.py @@ -0,0 +1,321 @@ +import warnings +from collections.abc import Sequence +from typing import Callable, Optional, Union + +import torch +from torch import Tensor + +from ..utils import _log_api_usage_once, _make_ntuple + + +interpolate = torch.nn.functional.interpolate + + +class FrozenBatchNorm2d(torch.nn.Module): + """ + BatchNorm2d where the batch statistics and the affine parameters are fixed + + Args: + num_features (int): Number of features ``C`` from an expected input of size ``(N, C, H, W)`` + eps (float): a value added to the denominator for numerical stability. Default: 1e-5 + """ + + def __init__( + self, + num_features: int, + eps: float = 1e-5, + ): + super().__init__() + _log_api_usage_once(self) + self.eps = eps + self.register_buffer("weight", torch.ones(num_features)) + self.register_buffer("bias", torch.zeros(num_features)) + self.register_buffer("running_mean", torch.zeros(num_features)) + self.register_buffer("running_var", torch.ones(num_features)) + + def _load_from_state_dict( + self, + state_dict: dict, + prefix: str, + local_metadata: dict, + strict: bool, + missing_keys: list[str], + unexpected_keys: list[str], + error_msgs: list[str], + ): + num_batches_tracked_key = prefix + "num_batches_tracked" + if num_batches_tracked_key in state_dict: + del state_dict[num_batches_tracked_key] + + super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + def forward(self, x: Tensor) -> Tensor: + # move reshapes to the beginning + # to make it fuser-friendly + w = self.weight.reshape(1, -1, 1, 1) + b = self.bias.reshape(1, -1, 1, 1) + rv = self.running_var.reshape(1, -1, 1, 1) + rm = self.running_mean.reshape(1, -1, 1, 1) + scale = w * (rv + self.eps).rsqrt() + bias = b - rm * scale + return x * scale + bias + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.weight.shape[0]}, eps={self.eps})" + + +class ConvNormActivation(torch.nn.Sequential): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: Union[int, tuple[int, ...]] = 3, + stride: Union[int, tuple[int, ...]] = 1, + padding: Optional[Union[int, tuple[int, ...], str]] = None, + groups: int = 1, + norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm2d, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + dilation: Union[int, tuple[int, ...]] = 1, + inplace: Optional[bool] = True, + bias: Optional[bool] = None, + conv_layer: Callable[..., torch.nn.Module] = torch.nn.Conv2d, + ) -> None: + + if padding is None: + if isinstance(kernel_size, int) and isinstance(dilation, int): + padding = (kernel_size - 1) // 2 * dilation + else: + _conv_dim = len(kernel_size) if isinstance(kernel_size, Sequence) else len(dilation) + kernel_size = _make_ntuple(kernel_size, _conv_dim) + dilation = _make_ntuple(dilation, _conv_dim) + padding = tuple((kernel_size[i] - 1) // 2 * dilation[i] for i in range(_conv_dim)) + if bias is None: + bias = norm_layer is None + + layers = [ + conv_layer( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation=dilation, + groups=groups, + bias=bias, + ) + ] + + if norm_layer is not None: + layers.append(norm_layer(out_channels)) + + if activation_layer is not None: + params = {} if inplace is None else {"inplace": inplace} + layers.append(activation_layer(**params)) + super().__init__(*layers) + _log_api_usage_once(self) + self.out_channels = out_channels + + if self.__class__ == ConvNormActivation: + warnings.warn( + "Don't use ConvNormActivation directly, please use Conv2dNormActivation and Conv3dNormActivation instead." + ) + + +class Conv2dNormActivation(ConvNormActivation): + """ + Configurable block used for Convolution2d-Normalization-Activation blocks. + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the Convolution-Normalization-Activation block + kernel_size: (int, optional): Size of the convolving kernel. Default: 3 + stride (int, optional): Stride of the convolution. Default: 1 + padding (int, tuple or str, optional): Padding added to all four sides of the input. Default: None, in which case it will be calculated as ``padding = (kernel_size - 1) // 2 * dilation`` + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the convolution layer. If ``None`` this layer won't be used. Default: ``torch.nn.BatchNorm2d`` + activation_layer (Callable[..., torch.nn.Module], optional): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the conv layer. If ``None`` this layer won't be used. Default: ``torch.nn.ReLU`` + dilation (int): Spacing between kernel elements. Default: 1 + inplace (bool): Parameter for the activation layer, which can optionally do the operation in-place. Default ``True`` + bias (bool, optional): Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is None``. + + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: Union[int, tuple[int, int]] = 3, + stride: Union[int, tuple[int, int]] = 1, + padding: Optional[Union[int, tuple[int, int], str]] = None, + groups: int = 1, + norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm2d, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + dilation: Union[int, tuple[int, int]] = 1, + inplace: Optional[bool] = True, + bias: Optional[bool] = None, + ) -> None: + + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups, + norm_layer, + activation_layer, + dilation, + inplace, + bias, + torch.nn.Conv2d, + ) + + +class Conv3dNormActivation(ConvNormActivation): + """ + Configurable block used for Convolution3d-Normalization-Activation blocks. + + Args: + in_channels (int): Number of channels in the input video. + out_channels (int): Number of channels produced by the Convolution-Normalization-Activation block + kernel_size: (int, optional): Size of the convolving kernel. Default: 3 + stride (int, optional): Stride of the convolution. Default: 1 + padding (int, tuple or str, optional): Padding added to all four sides of the input. Default: None, in which case it will be calculated as ``padding = (kernel_size - 1) // 2 * dilation`` + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the convolution layer. If ``None`` this layer won't be used. Default: ``torch.nn.BatchNorm3d`` + activation_layer (Callable[..., torch.nn.Module], optional): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the conv layer. If ``None`` this layer won't be used. Default: ``torch.nn.ReLU`` + dilation (int): Spacing between kernel elements. Default: 1 + inplace (bool): Parameter for the activation layer, which can optionally do the operation in-place. Default ``True`` + bias (bool, optional): Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is None``. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: Union[int, tuple[int, int, int]] = 3, + stride: Union[int, tuple[int, int, int]] = 1, + padding: Optional[Union[int, tuple[int, int, int], str]] = None, + groups: int = 1, + norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm3d, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + dilation: Union[int, tuple[int, int, int]] = 1, + inplace: Optional[bool] = True, + bias: Optional[bool] = None, + ) -> None: + + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups, + norm_layer, + activation_layer, + dilation, + inplace, + bias, + torch.nn.Conv3d, + ) + + +class SqueezeExcitation(torch.nn.Module): + """ + This block implements the Squeeze-and-Excitation block from https://arxiv.org/abs/1709.01507 (see Fig. 1). + Parameters ``activation``, and ``scale_activation`` correspond to ``delta`` and ``sigma`` in eq. 3. + + Args: + input_channels (int): Number of channels in the input image + squeeze_channels (int): Number of squeeze channels + activation (Callable[..., torch.nn.Module], optional): ``delta`` activation. Default: ``torch.nn.ReLU`` + scale_activation (Callable[..., torch.nn.Module]): ``sigma`` activation. Default: ``torch.nn.Sigmoid`` + """ + + def __init__( + self, + input_channels: int, + squeeze_channels: int, + activation: Callable[..., torch.nn.Module] = torch.nn.ReLU, + scale_activation: Callable[..., torch.nn.Module] = torch.nn.Sigmoid, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.avgpool = torch.nn.AdaptiveAvgPool2d(1) + self.fc1 = torch.nn.Conv2d(input_channels, squeeze_channels, 1) + self.fc2 = torch.nn.Conv2d(squeeze_channels, input_channels, 1) + self.activation = activation() + self.scale_activation = scale_activation() + + def _scale(self, input: Tensor) -> Tensor: + scale = self.avgpool(input) + scale = self.fc1(scale) + scale = self.activation(scale) + scale = self.fc2(scale) + return self.scale_activation(scale) + + def forward(self, input: Tensor) -> Tensor: + scale = self._scale(input) + return scale * input + + +class MLP(torch.nn.Sequential): + """This block implements the multi-layer perceptron (MLP) module. + + Args: + in_channels (int): Number of channels of the input + hidden_channels (List[int]): List of the hidden channel dimensions + norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the linear layer. If ``None`` this layer won't be used. Default: ``None`` + activation_layer (Callable[..., torch.nn.Module], optional): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the linear layer. If ``None`` this layer won't be used. Default: ``torch.nn.ReLU`` + inplace (bool, optional): Parameter for the activation layer, which can optionally do the operation in-place. + Default is ``None``, which uses the respective default values of the ``activation_layer`` and Dropout layer. + bias (bool): Whether to use bias in the linear layer. Default ``True`` + dropout (float): The probability for the dropout layer. Default: 0.0 + """ + + def __init__( + self, + in_channels: int, + hidden_channels: list[int], + norm_layer: Optional[Callable[..., torch.nn.Module]] = None, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + inplace: Optional[bool] = None, + bias: bool = True, + dropout: float = 0.0, + ): + # The addition of `norm_layer` is inspired from the implementation of TorchMultimodal: + # https://github.com/facebookresearch/multimodal/blob/5dec8a/torchmultimodal/modules/layers/mlp.py + params = {} if inplace is None else {"inplace": inplace} + + layers = [] + in_dim = in_channels + for hidden_dim in hidden_channels[:-1]: + layers.append(torch.nn.Linear(in_dim, hidden_dim, bias=bias)) + if norm_layer is not None: + layers.append(norm_layer(hidden_dim)) + layers.append(activation_layer(**params)) + layers.append(torch.nn.Dropout(dropout, **params)) + in_dim = hidden_dim + + layers.append(torch.nn.Linear(in_dim, hidden_channels[-1], bias=bias)) + layers.append(torch.nn.Dropout(dropout, **params)) + + super().__init__(*layers) + _log_api_usage_once(self) + + +class Permute(torch.nn.Module): + """This module returns a view of the tensor input with its dimensions permuted. + + Args: + dims (List[int]): The desired ordering of dimensions + """ + + def __init__(self, dims: list[int]): + super().__init__() + self.dims = dims + + def forward(self, x: Tensor) -> Tensor: + return torch.permute(x, self.dims) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/poolers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/poolers.py new file mode 100644 index 0000000000000000000000000000000000000000..f887f6aee332e8785f2a6596fe0c11f66264cb88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/poolers.py @@ -0,0 +1,327 @@ +from typing import Optional, Union + +import torch +import torch.fx +import torchvision +from torch import nn, Tensor +from torchvision.ops.boxes import box_area + +from ..utils import _log_api_usage_once +from .roi_align import roi_align + + +# copying result_idx_in_level to a specific index in result[] +# is not supported by ONNX tracing yet. +# _onnx_merge_levels() is an implementation supported by ONNX +# that merges the levels to the right indices +@torch.jit.unused +def _onnx_merge_levels(levels: Tensor, unmerged_results: list[Tensor]) -> Tensor: + first_result = unmerged_results[0] + dtype, device = first_result.dtype, first_result.device + res = torch.zeros( + (levels.size(0), first_result.size(1), first_result.size(2), first_result.size(3)), dtype=dtype, device=device + ) + for level in range(len(unmerged_results)): + index = torch.where(levels == level)[0].view(-1, 1, 1, 1) + index = index.expand( + index.size(0), + unmerged_results[level].size(1), + unmerged_results[level].size(2), + unmerged_results[level].size(3), + ) + res = res.scatter(0, index, unmerged_results[level]) + return res + + +# TODO: (eellison) T54974082 https://github.com/pytorch/pytorch/issues/26744/pytorch/issues/26744 +def initLevelMapper( + k_min: int, + k_max: int, + canonical_scale: int = 224, + canonical_level: int = 4, + eps: float = 1e-6, +): + return LevelMapper(k_min, k_max, canonical_scale, canonical_level, eps) + + +class LevelMapper: + """Determine which FPN level each RoI in a set of RoIs should map to based + on the heuristic in the FPN paper. + + Args: + k_min (int) + k_max (int) + canonical_scale (int) + canonical_level (int) + eps (float) + """ + + def __init__( + self, + k_min: int, + k_max: int, + canonical_scale: int = 224, + canonical_level: int = 4, + eps: float = 1e-6, + ): + self.k_min = k_min + self.k_max = k_max + self.s0 = canonical_scale + self.lvl0 = canonical_level + self.eps = eps + + def __call__(self, boxlists: list[Tensor]) -> Tensor: + """ + Args: + boxlists (list[BoxList]) + """ + # Compute level ids + s = torch.sqrt(torch.cat([box_area(boxlist) for boxlist in boxlists])) + + # Eqn.(1) in FPN paper + target_lvls = torch.floor(self.lvl0 + torch.log2(s / self.s0) + torch.tensor(self.eps, dtype=s.dtype)) + target_lvls = torch.clamp(target_lvls, min=self.k_min, max=self.k_max) + return (target_lvls.to(torch.int64) - self.k_min).to(torch.int64) + + +def _convert_to_roi_format(boxes: list[Tensor]) -> Tensor: + concat_boxes = torch.cat(boxes, dim=0) + device, dtype = concat_boxes.device, concat_boxes.dtype + ids = torch.cat( + [torch.full_like(b[:, :1], i, dtype=dtype, layout=torch.strided, device=device) for i, b in enumerate(boxes)], + dim=0, + ) + rois = torch.cat([ids, concat_boxes], dim=1) + return rois + + +def _infer_scale(feature: Tensor, original_size: list[int]) -> float: + # assumption: the scale is of the form 2 ** (-k), with k integer + size = feature.shape[-2:] + possible_scales: list[float] = [] + for s1, s2 in zip(size, original_size): + approx_scale = float(s1) / float(s2) + scale = 2 ** float(torch.tensor(approx_scale).log2().round()) + possible_scales.append(scale) + return possible_scales[0] + + +@torch.fx.wrap +def _setup_scales( + features: list[Tensor], image_shapes: list[tuple[int, int]], canonical_scale: int, canonical_level: int +) -> tuple[list[float], LevelMapper]: + if not image_shapes: + raise ValueError("images list should not be empty") + max_x = 0 + max_y = 0 + for shape in image_shapes: + max_x = max(shape[0], max_x) + max_y = max(shape[1], max_y) + original_input_shape = (max_x, max_y) + + scales = [_infer_scale(feat, original_input_shape) for feat in features] + # get the levels in the feature map by leveraging the fact that the network always + # downsamples by a factor of 2 at each level. + lvl_min = -torch.log2(torch.tensor(scales[0], dtype=torch.float32)).item() + lvl_max = -torch.log2(torch.tensor(scales[-1], dtype=torch.float32)).item() + + map_levels = initLevelMapper( + int(lvl_min), + int(lvl_max), + canonical_scale=canonical_scale, + canonical_level=canonical_level, + ) + return scales, map_levels + + +@torch.fx.wrap +def _filter_input(x: dict[str, Tensor], featmap_names: list[str]) -> list[Tensor]: + x_filtered = [] + for k, v in x.items(): + if k in featmap_names: + x_filtered.append(v) + return x_filtered + + +@torch.fx.wrap +def _multiscale_roi_align( + x_filtered: list[Tensor], + boxes: list[Tensor], + output_size: list[int], + sampling_ratio: int, + scales: Optional[list[float]], + mapper: Optional[LevelMapper], +) -> Tensor: + """ + Args: + x_filtered (List[Tensor]): List of input tensors. + boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in + (x1, y1, x2, y2) format and in the image reference size, not the feature map + reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + output_size (Union[List[Tuple[int, int]], List[int]]): size of the output + sampling_ratio (int): sampling ratio for ROIAlign + scales (Optional[List[float]]): If None, scales will be automatically inferred. Default value is None. + mapper (Optional[LevelMapper]): If none, mapper will be automatically inferred. Default value is None. + Returns: + result (Tensor) + """ + if scales is None or mapper is None: + raise ValueError("scales and mapper should not be None") + + num_levels = len(x_filtered) + rois = _convert_to_roi_format(boxes) + + if num_levels == 1: + return roi_align( + x_filtered[0], + rois, + output_size=output_size, + spatial_scale=scales[0], + sampling_ratio=sampling_ratio, + ) + + levels = mapper(boxes) + + num_rois = len(rois) + num_channels = x_filtered[0].shape[1] + + dtype, device = x_filtered[0].dtype, x_filtered[0].device + result = torch.zeros( + ( + num_rois, + num_channels, + ) + + output_size, + dtype=dtype, + device=device, + ) + + tracing_results = [] + for level, (per_level_feature, scale) in enumerate(zip(x_filtered, scales)): + idx_in_level = torch.where(levels == level)[0] + rois_per_level = rois[idx_in_level] + + result_idx_in_level = roi_align( + per_level_feature, + rois_per_level, + output_size=output_size, + spatial_scale=scale, + sampling_ratio=sampling_ratio, + ) + + if torchvision._is_tracing(): + tracing_results.append(result_idx_in_level.to(dtype)) + else: + # result and result_idx_in_level's dtypes are based on dtypes of different + # elements in x_filtered. x_filtered contains tensors output by different + # layers. When autocast is active, it may choose different dtypes for + # different layers' outputs. Therefore, we defensively match result's dtype + # before copying elements from result_idx_in_level in the following op. + # We need to cast manually (can't rely on autocast to cast for us) because + # the op acts on result in-place, and autocast only affects out-of-place ops. + result[idx_in_level] = result_idx_in_level.to(result.dtype) + + if torchvision._is_tracing(): + result = _onnx_merge_levels(levels, tracing_results) + + return result + + +class MultiScaleRoIAlign(nn.Module): + """ + Multi-scale RoIAlign pooling, which is useful for detection with or without FPN. + + It infers the scale of the pooling via the heuristics specified in eq. 1 + of the `Feature Pyramid Network paper `_. + They keyword-only parameters ``canonical_scale`` and ``canonical_level`` + correspond respectively to ``224`` and ``k0=4`` in eq. 1, and + have the following meaning: ``canonical_level`` is the target level of the pyramid from + which to pool a region of interest with ``w x h = canonical_scale x canonical_scale``. + + Args: + featmap_names (List[str]): the names of the feature maps that will be used + for the pooling. + output_size (List[Tuple[int, int]] or List[int]): output size for the pooled region + sampling_ratio (int): sampling ratio for ROIAlign + canonical_scale (int, optional): canonical_scale for LevelMapper + canonical_level (int, optional): canonical_level for LevelMapper + + Examples:: + + >>> m = torchvision.ops.MultiScaleRoIAlign(['feat1', 'feat3'], 3, 2) + >>> i = OrderedDict() + >>> i['feat1'] = torch.rand(1, 5, 64, 64) + >>> i['feat2'] = torch.rand(1, 5, 32, 32) # this feature won't be used in the pooling + >>> i['feat3'] = torch.rand(1, 5, 16, 16) + >>> # create some random bounding boxes + >>> boxes = torch.rand(6, 4) * 256; boxes[:, 2:] += boxes[:, :2] + >>> # original image size, before computing the feature maps + >>> image_sizes = [(512, 512)] + >>> output = m(i, [boxes], image_sizes) + >>> print(output.shape) + >>> torch.Size([6, 5, 3, 3]) + + """ + + __annotations__ = {"scales": Optional[list[float]], "map_levels": Optional[LevelMapper]} + + def __init__( + self, + featmap_names: list[str], + output_size: Union[int, tuple[int], list[int]], + sampling_ratio: int, + *, + canonical_scale: int = 224, + canonical_level: int = 4, + ): + super().__init__() + _log_api_usage_once(self) + if isinstance(output_size, int): + output_size = (output_size, output_size) + self.featmap_names = featmap_names + self.sampling_ratio = sampling_ratio + self.output_size = tuple(output_size) + self.scales = None + self.map_levels = None + self.canonical_scale = canonical_scale + self.canonical_level = canonical_level + + def forward( + self, + x: dict[str, Tensor], + boxes: list[Tensor], + image_shapes: list[tuple[int, int]], + ) -> Tensor: + """ + Args: + x (OrderedDict[Tensor]): feature maps for each level. They are assumed to have + all the same number of channels, but they can have different sizes. + boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in + (x1, y1, x2, y2) format and in the image reference size, not the feature map + reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + image_shapes (List[Tuple[height, width]]): the sizes of each image before they + have been fed to a CNN to obtain feature maps. This allows us to infer the + scale factor for each one of the levels to be pooled. + Returns: + result (Tensor) + """ + x_filtered = _filter_input(x, self.featmap_names) + if self.scales is None or self.map_levels is None: + self.scales, self.map_levels = _setup_scales( + x_filtered, image_shapes, self.canonical_scale, self.canonical_level + ) + + return _multiscale_roi_align( + x_filtered, + boxes, + self.output_size, + self.sampling_ratio, + self.scales, + self.map_levels, + ) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(featmap_names={self.featmap_names}, " + f"output_size={self.output_size}, sampling_ratio={self.sampling_ratio})" + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ps_roi_align.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ps_roi_align.py new file mode 100644 index 0000000000000000000000000000000000000000..82809b8f8885667b28eccd22aca60d1dca02f3bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ps_roi_align.py @@ -0,0 +1,90 @@ +import torch +import torch.fx +from torch import nn, Tensor +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +@torch.fx.wrap +def ps_roi_align( + input: Tensor, + boxes: Tensor, + output_size: int, + spatial_scale: float = 1.0, + sampling_ratio: int = -1, +) -> Tensor: + """ + Performs Position-Sensitive Region of Interest (RoI) Align operator + mentioned in Light-Head R-CNN. + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling + is performed, as (height, width). + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + sampling_ratio (int): number of sampling points in the interpolation grid + used to compute the output value of each pooled output bin. If > 0, + then exactly ``sampling_ratio x sampling_ratio`` sampling points per bin are used. If + <= 0, then an adaptive number of grid points are used (computed as + ``ceil(roi_width / output_width)``, and likewise for height). Default: -1 + + Returns: + Tensor[K, C / (output_size[0] * output_size[1]), output_size[0], output_size[1]]: The pooled RoIs + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(ps_roi_align) + _assert_has_ops() + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + output, _ = torch.ops.torchvision.ps_roi_align( + input, rois, spatial_scale, output_size[0], output_size[1], sampling_ratio + ) + return output + + +class PSRoIAlign(nn.Module): + """ + See :func:`ps_roi_align`. + """ + + def __init__( + self, + output_size: int, + spatial_scale: float, + sampling_ratio: int, + ): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + self.sampling_ratio = sampling_ratio + + def forward(self, input: Tensor, rois: Tensor) -> Tensor: + return ps_roi_align(input, rois, self.output_size, self.spatial_scale, self.sampling_ratio) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"output_size={self.output_size}" + f", spatial_scale={self.spatial_scale}" + f", sampling_ratio={self.sampling_ratio}" + f")" + ) + return s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ps_roi_pool.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ps_roi_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..15292dcad97490aaa740cdec2d0aedb31e5662eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/ps_roi_pool.py @@ -0,0 +1,70 @@ +import torch +import torch.fx +from torch import nn, Tensor +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +@torch.fx.wrap +def ps_roi_pool( + input: Tensor, + boxes: Tensor, + output_size: int, + spatial_scale: float = 1.0, +) -> Tensor: + """ + Performs Position-Sensitive Region of Interest (RoI) Pool operator + described in R-FCN + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling + is performed, as (height, width). + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + + Returns: + Tensor[K, C / (output_size[0] * output_size[1]), output_size[0], output_size[1]]: The pooled RoIs. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(ps_roi_pool) + _assert_has_ops() + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + output, _ = torch.ops.torchvision.ps_roi_pool(input, rois, spatial_scale, output_size[0], output_size[1]) + return output + + +class PSRoIPool(nn.Module): + """ + See :func:`ps_roi_pool`. + """ + + def __init__(self, output_size: int, spatial_scale: float): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + + def forward(self, input: Tensor, rois: Tensor) -> Tensor: + return ps_roi_pool(input, rois, self.output_size, self.spatial_scale) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(output_size={self.output_size}, spatial_scale={self.spatial_scale})" + return s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/roi_align.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/roi_align.py new file mode 100644 index 0000000000000000000000000000000000000000..25214d6b13038149d5333c1bab16dc3fb6946396 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/roi_align.py @@ -0,0 +1,294 @@ +import functools +from typing import Union + +import torch +import torch.fx +from torch import nn, Tensor +from torch._dynamo.utils import is_compile_supported +from torch.jit.annotations import BroadcastingList2 +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops, _has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +def lazy_compile(**compile_kwargs): + """Lazily wrap a function with torch.compile on the first call + + This avoids eagerly importing dynamo. + """ + + def decorate_fn(fn): + @functools.wraps(fn) + def compile_hook(*args, **kwargs): + compiled_fn = torch.compile(fn, **compile_kwargs) + globals()[fn.__name__] = functools.wraps(fn)(compiled_fn) + return compiled_fn(*args, **kwargs) + + return compile_hook + + return decorate_fn + + +# NB: all inputs are tensors +def _bilinear_interpolate( + input, # [N, C, H, W] + roi_batch_ind, # [K] + y, # [K, PH, IY] + x, # [K, PW, IX] + ymask, # [K, IY] + xmask, # [K, IX] +): + _, channels, height, width = input.size() + + # deal with inverse element out of feature map boundary + y = y.clamp(min=0) + x = x.clamp(min=0) + y_low = y.int() + x_low = x.int() + y_high = torch.where(y_low >= height - 1, height - 1, y_low + 1) + y_low = torch.where(y_low >= height - 1, height - 1, y_low) + y = torch.where(y_low >= height - 1, y.to(input.dtype), y) + + x_high = torch.where(x_low >= width - 1, width - 1, x_low + 1) + x_low = torch.where(x_low >= width - 1, width - 1, x_low) + x = torch.where(x_low >= width - 1, x.to(input.dtype), x) + + ly = y - y_low + lx = x - x_low + hy = 1.0 - ly + hx = 1.0 - lx + + # do bilinear interpolation, but respect the masking! + # TODO: It's possible the masking here is unnecessary if y and + # x were clamped appropriately; hard to tell + def masked_index( + y, # [K, PH, IY] + x, # [K, PW, IX] + ): + if ymask is not None: + assert xmask is not None + y = torch.where(ymask[:, None, :], y, 0) + x = torch.where(xmask[:, None, :], x, 0) + return input[ + roi_batch_ind[:, None, None, None, None, None], + torch.arange(channels, device=input.device)[None, :, None, None, None, None], + y[:, None, :, None, :, None], # prev [K, PH, IY] + x[:, None, None, :, None, :], # prev [K, PW, IX] + ] # [K, C, PH, PW, IY, IX] + + v1 = masked_index(y_low, x_low) + v2 = masked_index(y_low, x_high) + v3 = masked_index(y_high, x_low) + v4 = masked_index(y_high, x_high) + + # all ws preemptively [K, C, PH, PW, IY, IX] + def outer_prod(y, x): + return y[:, None, :, None, :, None] * x[:, None, None, :, None, :] + + w1 = outer_prod(hy, hx) + w2 = outer_prod(hy, lx) + w3 = outer_prod(ly, hx) + w4 = outer_prod(ly, lx) + + val = w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4 + return val + + +# TODO: this doesn't actually cache +# TODO: main library should make this easier to do +def maybe_cast(tensor): + if torch.is_autocast_enabled() and tensor.is_cuda and tensor.dtype != torch.double: + return tensor.float() + else: + return tensor + + +# This is a pure Python and differentiable implementation of roi_align. When +# run in eager mode, it uses a lot of memory, but when compiled it has +# acceptable memory usage. The main point of this implementation is that +# its backwards is deterministic. +# It is transcribed directly off of the roi_align CUDA kernel, see +# https://dev-discuss.pytorch.org/t/a-pure-python-implementation-of-roi-align-that-looks-just-like-its-cuda-kernel/1266 +@lazy_compile(dynamic=True) +def _roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + orig_dtype = input.dtype + + input = maybe_cast(input) + rois = maybe_cast(rois) + + _, _, height, width = input.size() + + ph = torch.arange(pooled_height, device=input.device) # [PH] + pw = torch.arange(pooled_width, device=input.device) # [PW] + + # input: [N, C, H, W] + # rois: [K, 5] + + roi_batch_ind = rois[:, 0].int() # [K] + offset = 0.5 if aligned else 0.0 + roi_start_w = rois[:, 1] * spatial_scale - offset # [K] + roi_start_h = rois[:, 2] * spatial_scale - offset # [K] + roi_end_w = rois[:, 3] * spatial_scale - offset # [K] + roi_end_h = rois[:, 4] * spatial_scale - offset # [K] + + roi_width = roi_end_w - roi_start_w # [K] + roi_height = roi_end_h - roi_start_h # [K] + if not aligned: + roi_width = torch.clamp(roi_width, min=1.0) # [K] + roi_height = torch.clamp(roi_height, min=1.0) # [K] + + bin_size_h = roi_height / pooled_height # [K] + bin_size_w = roi_width / pooled_width # [K] + + exact_sampling = sampling_ratio > 0 + + roi_bin_grid_h = sampling_ratio if exact_sampling else torch.ceil(roi_height / pooled_height) # scalar or [K] + roi_bin_grid_w = sampling_ratio if exact_sampling else torch.ceil(roi_width / pooled_width) # scalar or [K] + + """ + iy, ix = dims(2) + """ + + if exact_sampling: + count = max(roi_bin_grid_h * roi_bin_grid_w, 1) # scalar + iy = torch.arange(roi_bin_grid_h, device=input.device) # [IY] + ix = torch.arange(roi_bin_grid_w, device=input.device) # [IX] + ymask = None + xmask = None + else: + count = torch.clamp(roi_bin_grid_h * roi_bin_grid_w, min=1) # [K] + # When doing adaptive sampling, the number of samples we need to do + # is data-dependent based on how big the ROIs are. This is a bit + # awkward because first-class dims can't actually handle this. + # So instead, we inefficiently suppose that we needed to sample ALL + # the points and mask out things that turned out to be unnecessary + iy = torch.arange(height, device=input.device) # [IY] + ix = torch.arange(width, device=input.device) # [IX] + ymask = iy[None, :] < roi_bin_grid_h[:, None] # [K, IY] + xmask = ix[None, :] < roi_bin_grid_w[:, None] # [K, IX] + + def from_K(t): + return t[:, None, None] + + y = ( + from_K(roi_start_h) + + ph[None, :, None] * from_K(bin_size_h) + + (iy[None, None, :] + 0.5).to(input.dtype) * from_K(bin_size_h / roi_bin_grid_h) + ) # [K, PH, IY] + x = ( + from_K(roi_start_w) + + pw[None, :, None] * from_K(bin_size_w) + + (ix[None, None, :] + 0.5).to(input.dtype) * from_K(bin_size_w / roi_bin_grid_w) + ) # [K, PW, IX] + val = _bilinear_interpolate(input, roi_batch_ind, y, x, ymask, xmask) # [K, C, PH, PW, IY, IX] + + # Mask out samples that weren't actually adaptively needed + if not exact_sampling: + val = torch.where(ymask[:, None, None, None, :, None], val, 0) + val = torch.where(xmask[:, None, None, None, None, :], val, 0) + + output = val.sum((-1, -2)) # remove IY, IX ~> [K, C, PH, PW] + if isinstance(count, torch.Tensor): + output /= count[:, None, None, None] + else: + output /= count + + output = output.to(orig_dtype) + + return output + + +@torch.fx.wrap +def roi_align( + input: Tensor, + boxes: Union[Tensor, list[Tensor]], + output_size: BroadcastingList2[int], + spatial_scale: float = 1.0, + sampling_ratio: int = -1, + aligned: bool = False, +) -> Tensor: + """ + Performs Region of Interest (RoI) Align operator with average pooling, as described in Mask R-CNN. + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + If the tensor is quantized, we expect a batch size of ``N == 1``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling + is performed, as (height, width). + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + sampling_ratio (int): number of sampling points in the interpolation grid + used to compute the output value of each pooled output bin. If > 0, + then exactly ``sampling_ratio x sampling_ratio`` sampling points per bin are used. If + <= 0, then an adaptive number of grid points are used (computed as + ``ceil(roi_width / output_width)``, and likewise for height). Default: -1 + aligned (bool): If False, use the legacy implementation. + If True, pixel shift the box coordinates it by -0.5 for a better alignment with the two + neighboring pixel indices. This version is used in Detectron2 + + Returns: + Tensor[K, C, output_size[0], output_size[1]]: The pooled RoIs. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(roi_align) + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + if not torch.jit.is_scripting(): + if ( + not _has_ops() + or (torch.are_deterministic_algorithms_enabled() and (input.is_cuda or input.is_mps or input.is_xpu)) + ) and is_compile_supported(input.device.type): + return _roi_align(input, rois, spatial_scale, output_size[0], output_size[1], sampling_ratio, aligned) + _assert_has_ops() + return torch.ops.torchvision.roi_align( + input, rois, spatial_scale, output_size[0], output_size[1], sampling_ratio, aligned + ) + + +class RoIAlign(nn.Module): + """ + See :func:`roi_align`. + """ + + def __init__( + self, + output_size: BroadcastingList2[int], + spatial_scale: float, + sampling_ratio: int, + aligned: bool = False, + ): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + self.sampling_ratio = sampling_ratio + self.aligned = aligned + + def forward(self, input: Tensor, rois: Union[Tensor, list[Tensor]]) -> Tensor: + return roi_align(input, rois, self.output_size, self.spatial_scale, self.sampling_ratio, self.aligned) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"output_size={self.output_size}" + f", spatial_scale={self.spatial_scale}" + f", sampling_ratio={self.sampling_ratio}" + f", aligned={self.aligned}" + f")" + ) + return s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/roi_pool.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/roi_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4bb95c0f3e49da94ef46d9f85f9f449531b632 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/roi_pool.py @@ -0,0 +1,72 @@ +from typing import Union + +import torch +import torch.fx +from torch import nn, Tensor +from torch.jit.annotations import BroadcastingList2 +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +@torch.fx.wrap +def roi_pool( + input: Tensor, + boxes: Union[Tensor, list[Tensor]], + output_size: BroadcastingList2[int], + spatial_scale: float = 1.0, +) -> Tensor: + """ + Performs Region of Interest (RoI) Pool operator described in Fast R-CNN + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output after the cropping + is performed, as (height, width) + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + + Returns: + Tensor[K, C, output_size[0], output_size[1]]: The pooled RoIs. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(roi_pool) + _assert_has_ops() + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + output, _ = torch.ops.torchvision.roi_pool(input, rois, spatial_scale, output_size[0], output_size[1]) + return output + + +class RoIPool(nn.Module): + """ + See :func:`roi_pool`. + """ + + def __init__(self, output_size: BroadcastingList2[int], spatial_scale: float): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + + def forward(self, input: Tensor, rois: Union[Tensor, list[Tensor]]) -> Tensor: + return roi_pool(input, rois, self.output_size, self.spatial_scale) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(output_size={self.output_size}, spatial_scale={self.spatial_scale})" + return s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/stochastic_depth.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/stochastic_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8167b2315e941f7e31a0626eeec270d350a710 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/ops/stochastic_depth.py @@ -0,0 +1,66 @@ +import torch +import torch.fx +from torch import nn, Tensor + +from ..utils import _log_api_usage_once + + +def stochastic_depth(input: Tensor, p: float, mode: str, training: bool = True) -> Tensor: + """ + Implements the Stochastic Depth from `"Deep Networks with Stochastic Depth" + `_ used for randomly dropping residual + branches of residual architectures. + + Args: + input (Tensor[N, ...]): The input tensor or arbitrary dimensions with the first one + being its batch i.e. a batch with ``N`` rows. + p (float): probability of the input to be zeroed. + mode (str): ``"batch"`` or ``"row"``. + ``"batch"`` randomly zeroes the entire input, ``"row"`` zeroes + randomly selected rows from the batch. + training: apply stochastic depth if is ``True``. Default: ``True`` + + Returns: + Tensor[N, ...]: The randomly zeroed tensor. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(stochastic_depth) + if p < 0.0 or p > 1.0: + raise ValueError(f"drop probability has to be between 0 and 1, but got {p}") + if mode not in ["batch", "row"]: + raise ValueError(f"mode has to be either 'batch' or 'row', but got {mode}") + if not training or p == 0.0: + return input + + survival_rate = 1.0 - p + if mode == "row": + size = [input.shape[0]] + [1] * (input.ndim - 1) + else: + size = [1] * input.ndim + noise = torch.empty(size, dtype=input.dtype, device=input.device) + noise = noise.bernoulli_(survival_rate) + if survival_rate > 0.0: + noise.div_(survival_rate) + return input * noise + + +torch.fx.wrap("stochastic_depth") + + +class StochasticDepth(nn.Module): + """ + See :func:`stochastic_depth`. + """ + + def __init__(self, p: float, mode: str) -> None: + super().__init__() + _log_api_usage_once(self) + self.p = p + self.mode = mode + + def forward(self, input: Tensor) -> Tensor: + return stochastic_depth(input, self.p, self.mode, self.training) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(p={self.p}, mode={self.mode})" + return s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77680a14f0d0599f4004a2ce5c299c0f5e13a0d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/__init__.py @@ -0,0 +1,2 @@ +from .transforms import * +from .autoaugment import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_pil.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_pil.py new file mode 100644 index 0000000000000000000000000000000000000000..56b806cf6edfe7657cce7a67562b53cf494ba814 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_pil.py @@ -0,0 +1,396 @@ +import numbers +from collections.abc import Sequence +from typing import Any, Literal, Optional, Union + +import numpy as np +import torch +from PIL import Image, ImageEnhance, ImageOps + +from ..utils import _Image_fromarray + +try: + import accimage +except ImportError: + accimage = None + + +@torch.jit.unused +def _is_pil_image(img: Any) -> bool: + if accimage is not None: + return isinstance(img, (Image.Image, accimage.Image)) + else: + return isinstance(img, Image.Image) + + +@torch.jit.unused +def get_dimensions(img: Any) -> list[int]: + if _is_pil_image(img): + if hasattr(img, "getbands"): + channels = len(img.getbands()) + else: + channels = img.channels + width, height = img.size + return [channels, height, width] + raise TypeError(f"Unexpected type {type(img)}") + + +@torch.jit.unused +def get_image_size(img: Any) -> list[int]: + if _is_pil_image(img): + return list(img.size) + raise TypeError(f"Unexpected type {type(img)}") + + +@torch.jit.unused +def get_image_num_channels(img: Any) -> int: + if _is_pil_image(img): + if hasattr(img, "getbands"): + return len(img.getbands()) + else: + return img.channels + raise TypeError(f"Unexpected type {type(img)}") + + +@torch.jit.unused +def hflip(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + return img.transpose(Image.FLIP_LEFT_RIGHT) + + +@torch.jit.unused +def vflip(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + return img.transpose(Image.FLIP_TOP_BOTTOM) + + +@torch.jit.unused +def adjust_brightness(img: Image.Image, brightness_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Brightness(img) + img = enhancer.enhance(brightness_factor) + return img + + +@torch.jit.unused +def adjust_contrast(img: Image.Image, contrast_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Contrast(img) + img = enhancer.enhance(contrast_factor) + return img + + +@torch.jit.unused +def adjust_saturation(img: Image.Image, saturation_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Color(img) + img = enhancer.enhance(saturation_factor) + return img + + +@torch.jit.unused +def adjust_hue(img: Image.Image, hue_factor: float) -> Image.Image: + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + input_mode = img.mode + if input_mode in {"L", "1", "I", "F"}: + return img + + h, s, v = img.convert("HSV").split() + + np_h = np.array(h, dtype=np.uint8) + # This will over/underflow, as desired + np_h += np.int32(hue_factor * 255).astype(np.uint8) + + h = _Image_fromarray(np_h, "L") + + img = Image.merge("HSV", (h, s, v)).convert(input_mode) + return img + + +@torch.jit.unused +def adjust_gamma( + img: Image.Image, + gamma: float, + gain: float = 1.0, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number") + + input_mode = img.mode + img = img.convert("RGB") + gamma_map = [int((255 + 1 - 1e-3) * gain * pow(ele / 255.0, gamma)) for ele in range(256)] * 3 + img = img.point(gamma_map) # use PIL's point-function to accelerate this part + + img = img.convert(input_mode) + return img + + +@torch.jit.unused +def pad( + img: Image.Image, + padding: Union[int, list[int], tuple[int, ...]], + fill: Optional[Union[float, list[float], tuple[float, ...]]] = 0, + padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant", +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + if not isinstance(padding, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate padding arg") + if fill is not None and not isinstance(fill, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate fill arg") + if not isinstance(padding_mode, str): + raise TypeError("Got inappropriate padding_mode arg") + + if isinstance(padding, list): + padding = tuple(padding) + + if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]: + raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple") + + if isinstance(padding, tuple) and len(padding) == 1: + # Compatibility with `functional_tensor.pad` + padding = padding[0] + + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + if padding_mode == "constant": + opts = _parse_fill(fill, img, name="fill") + if img.mode == "P": + palette = img.getpalette() + image = ImageOps.expand(img, border=padding, **opts) + image.putpalette(palette) + return image + + return ImageOps.expand(img, border=padding, **opts) + else: + if isinstance(padding, int): + pad_left = pad_right = pad_top = pad_bottom = padding + if isinstance(padding, tuple) and len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + if isinstance(padding, tuple) and len(padding) == 4: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + p = [pad_left, pad_top, pad_right, pad_bottom] + cropping = -np.minimum(p, 0) + + if cropping.any(): + crop_left, crop_top, crop_right, crop_bottom = cropping + img = img.crop((crop_left, crop_top, img.width - crop_right, img.height - crop_bottom)) + + pad_left, pad_top, pad_right, pad_bottom = np.maximum(p, 0) + + if img.mode == "P": + palette = img.getpalette() + img = np.asarray(img) + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), mode=padding_mode) + img = Image.fromarray(img) + img.putpalette(palette) + return img + + img = np.asarray(img) + # RGB image + if len(img.shape) == 3: + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode) + # Grayscale image + if len(img.shape) == 2: + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode) + + return Image.fromarray(img) + + +@torch.jit.unused +def crop( + img: Image.Image, + top: int, + left: int, + height: int, + width: int, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + return img.crop((left, top, left + width, top + height)) + + +@torch.jit.unused +def resize( + img: Image.Image, + size: Union[list[int], int], + interpolation: int = Image.BILINEAR, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + if not (isinstance(size, list) and len(size) == 2): + raise TypeError(f"Got inappropriate size arg: {size}") + + return img.resize(tuple(size[::-1]), interpolation) + + +@torch.jit.unused +def _parse_fill( + fill: Optional[Union[float, list[float], tuple[float, ...]]], + img: Image.Image, + name: str = "fillcolor", +) -> dict[str, Optional[Union[float, list[float], tuple[float, ...]]]]: + + # Process fill color for affine transforms + num_channels = get_image_num_channels(img) + if fill is None: + fill = 0 + if isinstance(fill, (int, float)) and num_channels > 1: + fill = tuple([fill] * num_channels) + if isinstance(fill, (list, tuple)): + if len(fill) == 1: + fill = fill * num_channels + elif len(fill) != num_channels: + msg = "The number of elements in 'fill' does not match the number of channels of the image ({} != {})" + raise ValueError(msg.format(len(fill), num_channels)) + + fill = tuple(fill) # type: ignore[arg-type] + + if img.mode != "F": + if isinstance(fill, (list, tuple)): + fill = tuple(int(x) for x in fill) + else: + fill = int(fill) + + return {name: fill} + + +@torch.jit.unused +def affine( + img: Image.Image, + matrix: list[float], + interpolation: int = Image.NEAREST, + fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + output_size = img.size + opts = _parse_fill(fill, img) + return img.transform(output_size, Image.AFFINE, matrix, interpolation, **opts) + + +@torch.jit.unused +def rotate( + img: Image.Image, + angle: float, + interpolation: int = Image.NEAREST, + expand: bool = False, + center: Optional[tuple[int, int]] = None, + fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + opts = _parse_fill(fill, img) + return img.rotate(angle, interpolation, expand, center, **opts) + + +@torch.jit.unused +def perspective( + img: Image.Image, + perspective_coeffs: list[float], + interpolation: int = Image.BICUBIC, + fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + opts = _parse_fill(fill, img) + + return img.transform(img.size, Image.PERSPECTIVE, perspective_coeffs, interpolation, **opts) + + +@torch.jit.unused +def to_grayscale(img: Image.Image, num_output_channels: int) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + if num_output_channels == 1: + img = img.convert("L") + elif num_output_channels == 3: + img = img.convert("L") + np_img = np.array(img, dtype=np.uint8) + np_img = np.dstack([np_img, np_img, np_img]) + img = _Image_fromarray(np_img, "RGB") + else: + raise ValueError("num_output_channels should be either 1 or 3") + + return img + + +@torch.jit.unused +def invert(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.invert(img) + + +@torch.jit.unused +def posterize(img: Image.Image, bits: int) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.posterize(img, bits) + + +@torch.jit.unused +def solarize(img: Image.Image, threshold: int) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.solarize(img, threshold) + + +@torch.jit.unused +def adjust_sharpness(img: Image.Image, sharpness_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Sharpness(img) + img = enhancer.enhance(sharpness_factor) + return img + + +@torch.jit.unused +def autocontrast(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.autocontrast(img) + + +@torch.jit.unused +def equalize(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.equalize(img) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..71409c40af31fa76debcced5211284437d2f1bdd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_tensor.py @@ -0,0 +1,962 @@ +import warnings +from typing import Optional, Union + +import torch +from torch import Tensor +from torch.nn.functional import conv2d, grid_sample, interpolate, pad as torch_pad + + +def _is_tensor_a_torch_image(x: Tensor) -> bool: + return x.ndim >= 2 + + +def _assert_image_tensor(img: Tensor) -> None: + if not _is_tensor_a_torch_image(img): + raise TypeError("Tensor is not a torch image.") + + +def get_dimensions(img: Tensor) -> list[int]: + _assert_image_tensor(img) + channels = 1 if img.ndim == 2 else img.shape[-3] + height, width = img.shape[-2:] + return [channels, height, width] + + +def get_image_size(img: Tensor) -> list[int]: + # Returns (w, h) of tensor image + _assert_image_tensor(img) + return [img.shape[-1], img.shape[-2]] + + +def get_image_num_channels(img: Tensor) -> int: + _assert_image_tensor(img) + if img.ndim == 2: + return 1 + elif img.ndim > 2: + return img.shape[-3] + + raise TypeError(f"Input ndim should be 2 or more. Got {img.ndim}") + + +def _max_value(dtype: torch.dtype) -> int: + if dtype == torch.uint8: + return 255 + elif dtype == torch.int8: + return 127 + elif dtype == torch.int16: + return 32767 + elif dtype == torch.uint16: + return 65535 + elif dtype == torch.int32: + return 2147483647 + elif dtype == torch.int64: + return 9223372036854775807 + else: + # This is only here for completeness. This value is implicitly assumed in a lot of places so changing it is not + # easy. + return 1 + + +def _assert_channels(img: Tensor, permitted: list[int]) -> None: + c = get_dimensions(img)[0] + if c not in permitted: + raise TypeError(f"Input image tensor permitted channel values are {permitted}, but found {c}") + + +def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor: + if image.dtype == dtype: + return image + + if image.is_floating_point(): + + # TODO: replace with dtype.is_floating_point when torchscript supports it + if torch.tensor(0, dtype=dtype).is_floating_point(): + return image.to(dtype) + + # float to int + if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or ( + image.dtype == torch.float64 and dtype == torch.int64 + ): + msg = f"The cast from {image.dtype} to {dtype} cannot be performed safely." + raise RuntimeError(msg) + + # https://github.com/pytorch/vision/pull/2078#issuecomment-612045321 + # For data in the range 0-1, (float * 255).to(uint) is only 255 + # when float is exactly 1.0. + # `max + 1 - epsilon` provides more evenly distributed mapping of + # ranges of floats to ints. + eps = 1e-3 + max_val = float(_max_value(dtype)) + result = image.mul(max_val + 1.0 - eps) + return result.to(dtype) + else: + input_max = float(_max_value(image.dtype)) + + # int to float + # TODO: replace with dtype.is_floating_point when torchscript supports it + if torch.tensor(0, dtype=dtype).is_floating_point(): + image = image.to(dtype) + return image / input_max + + output_max = float(_max_value(dtype)) + + # int to int + if input_max > output_max: + # factor should be forced to int for torch jit script + # otherwise factor is a float and image // factor can produce different results + factor = int((input_max + 1) // (output_max + 1)) + image = torch.div(image, factor, rounding_mode="floor") + return image.to(dtype) + else: + # factor should be forced to int for torch jit script + # otherwise factor is a float and image * factor can produce different results + factor = int((output_max + 1) // (input_max + 1)) + image = image.to(dtype) + return image * factor + + +def vflip(img: Tensor) -> Tensor: + _assert_image_tensor(img) + + return img.flip(-2) + + +def hflip(img: Tensor) -> Tensor: + _assert_image_tensor(img) + + return img.flip(-1) + + +def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: + _assert_image_tensor(img) + + _, h, w = get_dimensions(img) + right = left + width + bottom = top + height + + if left < 0 or top < 0 or right > w or bottom > h: + padding_ltrb = [ + max(-left + min(0, right), 0), + max(-top + min(0, bottom), 0), + max(right - max(w, left), 0), + max(bottom - max(h, top), 0), + ] + return pad(img[..., max(top, 0) : bottom, max(left, 0) : right], padding_ltrb, fill=0) + return img[..., top:bottom, left:right] + + +def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor: + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + _assert_channels(img, [1, 3]) + + if num_output_channels not in (1, 3): + raise ValueError("num_output_channels should be either 1 or 3") + + if img.shape[-3] == 3: + r, g, b = img.unbind(dim=-3) + # This implementation closely follows the TF one: + # https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/ops/image_ops_impl.py#L2105-L2138 + l_img = (0.2989 * r + 0.587 * g + 0.114 * b).to(img.dtype) + l_img = l_img.unsqueeze(dim=-3) + else: + l_img = img.clone() + + if num_output_channels == 3: + return l_img.expand(img.shape) + + return l_img + + +def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor: + if brightness_factor < 0: + raise ValueError(f"brightness_factor ({brightness_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + return _blend(img, torch.zeros_like(img), brightness_factor) + + +def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor: + if contrast_factor < 0: + raise ValueError(f"contrast_factor ({contrast_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [3, 1]) + c = get_dimensions(img)[0] + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + if c == 3: + mean = torch.mean(rgb_to_grayscale(img).to(dtype), dim=(-3, -2, -1), keepdim=True) + else: + mean = torch.mean(img.to(dtype), dim=(-3, -2, -1), keepdim=True) + + return _blend(img, mean, contrast_factor) + + +def adjust_hue(img: Tensor, hue_factor: float) -> Tensor: + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") + + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor image") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + if get_dimensions(img)[0] == 1: # Match PIL behaviour + return img + + orig_dtype = img.dtype + img = convert_image_dtype(img, torch.float32) + + img = _rgb2hsv(img) + h, s, v = img.unbind(dim=-3) + h = (h + hue_factor) % 1.0 + img = torch.stack((h, s, v), dim=-3) + img_hue_adj = _hsv2rgb(img) + + return convert_image_dtype(img_hue_adj, orig_dtype) + + +def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor: + if saturation_factor < 0: + raise ValueError(f"saturation_factor ({saturation_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + if get_dimensions(img)[0] == 1: # Match PIL behaviour + return img + + return _blend(img, rgb_to_grayscale(img), saturation_factor) + + +def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor: + if not isinstance(img, torch.Tensor): + raise TypeError("Input img should be a Tensor.") + + _assert_channels(img, [1, 3]) + + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number") + + result = img + dtype = img.dtype + if not torch.is_floating_point(img): + result = convert_image_dtype(result, torch.float32) + + result = (gain * result**gamma).clamp(0, 1) + + result = convert_image_dtype(result, dtype) + return result + + +def _blend(img1: Tensor, img2: Tensor, ratio: float) -> Tensor: + ratio = float(ratio) + bound = _max_value(img1.dtype) + return (ratio * img1 + (1.0 - ratio) * img2).clamp(0, bound).to(img1.dtype) + + +def _rgb2hsv(img: Tensor) -> Tensor: + r, g, b = img.unbind(dim=-3) + + # Implementation is based on https://github.com/python-pillow/Pillow/blob/4174d4267616897df3746d315d5a2d0f82c656ee/ + # src/libImaging/Convert.c#L330 + maxc = torch.max(img, dim=-3).values + minc = torch.min(img, dim=-3).values + + # The algorithm erases S and H channel where `maxc = minc`. This avoids NaN + # from happening in the results, because + # + S channel has division by `maxc`, which is zero only if `maxc = minc` + # + H channel has division by `(maxc - minc)`. + # + # Instead of overwriting NaN afterwards, we just prevent it from occurring, so + # we don't need to deal with it in case we save the NaN in a buffer in + # backprop, if it is ever supported, but it doesn't hurt to do so. + eqc = maxc == minc + + cr = maxc - minc + # Since `eqc => cr = 0`, replacing denominator with 1 when `eqc` is fine. + ones = torch.ones_like(maxc) + s = cr / torch.where(eqc, ones, maxc) + # Note that `eqc => maxc = minc = r = g = b`. So the following calculation + # of `h` would reduce to `bc - gc + 2 + rc - bc + 4 + rc - bc = 6` so it + # would not matter what values `rc`, `gc`, and `bc` have here, and thus + # replacing denominator with 1 when `eqc` is fine. + cr_divisor = torch.where(eqc, ones, cr) + rc = (maxc - r) / cr_divisor + gc = (maxc - g) / cr_divisor + bc = (maxc - b) / cr_divisor + + hr = (maxc == r) * (bc - gc) + hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc) + hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc) + h = hr + hg + hb + h = torch.fmod((h / 6.0 + 1.0), 1.0) + return torch.stack((h, s, maxc), dim=-3) + + +def _hsv2rgb(img: Tensor) -> Tensor: + h, s, v = img.unbind(dim=-3) + i = torch.floor(h * 6.0) + f = (h * 6.0) - i + i = i.to(dtype=torch.int32) + + p = torch.clamp((v * (1.0 - s)), 0.0, 1.0) + q = torch.clamp((v * (1.0 - s * f)), 0.0, 1.0) + t = torch.clamp((v * (1.0 - s * (1.0 - f))), 0.0, 1.0) + i = i % 6 + + mask = i.unsqueeze(dim=-3) == torch.arange(6, device=i.device).view(-1, 1, 1) + + a1 = torch.stack((v, q, p, p, t, v), dim=-3) + a2 = torch.stack((t, v, v, q, p, p), dim=-3) + a3 = torch.stack((p, p, t, v, v, q), dim=-3) + a4 = torch.stack((a1, a2, a3), dim=-4) + + return torch.einsum("...ijk, ...xijk -> ...xjk", mask.to(dtype=img.dtype), a4) + + +def _pad_symmetric(img: Tensor, padding: list[int]) -> Tensor: + # padding is left, right, top, bottom + + # crop if needed + if padding[0] < 0 or padding[1] < 0 or padding[2] < 0 or padding[3] < 0: + neg_min_padding = [-min(x, 0) for x in padding] + crop_left, crop_right, crop_top, crop_bottom = neg_min_padding + img = img[..., crop_top : img.shape[-2] - crop_bottom, crop_left : img.shape[-1] - crop_right] + padding = [max(x, 0) for x in padding] + + in_sizes = img.size() + + _x_indices = [i for i in range(in_sizes[-1])] # [0, 1, 2, 3, ...] + left_indices = [i for i in range(padding[0] - 1, -1, -1)] # e.g. [3, 2, 1, 0] + right_indices = [-(i + 1) for i in range(padding[1])] # e.g. [-1, -2, -3] + x_indices = torch.tensor(left_indices + _x_indices + right_indices, device=img.device) + + _y_indices = [i for i in range(in_sizes[-2])] + top_indices = [i for i in range(padding[2] - 1, -1, -1)] + bottom_indices = [-(i + 1) for i in range(padding[3])] + y_indices = torch.tensor(top_indices + _y_indices + bottom_indices, device=img.device) + + ndim = img.ndim + if ndim == 3: + return img[:, y_indices[:, None], x_indices[None, :]] + elif ndim == 4: + return img[:, :, y_indices[:, None], x_indices[None, :]] + else: + raise RuntimeError("Symmetric padding of N-D tensors are not supported yet") + + +def _parse_pad_padding(padding: Union[int, list[int]]) -> list[int]: + if isinstance(padding, int): + if torch.jit.is_scripting(): + # This maybe unreachable + raise ValueError("padding can't be an int while torchscripting, set it as a list [value, ]") + pad_left = pad_right = pad_top = pad_bottom = padding + elif len(padding) == 1: + pad_left = pad_right = pad_top = pad_bottom = padding[0] + elif len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + else: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + return [pad_left, pad_right, pad_top, pad_bottom] + + +def pad( + img: Tensor, padding: Union[int, list[int]], fill: Optional[Union[int, float]] = 0, padding_mode: str = "constant" +) -> Tensor: + _assert_image_tensor(img) + + if fill is None: + fill = 0 + + if not isinstance(padding, (int, tuple, list)): + raise TypeError("Got inappropriate padding arg") + if not isinstance(fill, (int, float)): + raise TypeError("Got inappropriate fill arg") + if not isinstance(padding_mode, str): + raise TypeError("Got inappropriate padding_mode arg") + + if isinstance(padding, tuple): + padding = list(padding) + + if isinstance(padding, list): + # TODO: Jit is failing on loading this op when scripted and saved + # https://github.com/pytorch/pytorch/issues/81100 + if len(padding) not in [1, 2, 4]: + raise ValueError( + f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple" + ) + + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + p = _parse_pad_padding(padding) + + if padding_mode == "edge": + # remap padding_mode str + padding_mode = "replicate" + elif padding_mode == "symmetric": + # route to another implementation + return _pad_symmetric(img, p) + + need_squeeze = False + if img.ndim < 4: + img = img.unsqueeze(dim=0) + need_squeeze = True + + out_dtype = img.dtype + need_cast = False + if (padding_mode != "constant") and img.dtype not in (torch.float32, torch.float64): + # Here we temporarily cast input tensor to float + # until pytorch issue is resolved : + # https://github.com/pytorch/pytorch/issues/40763 + need_cast = True + img = img.to(torch.float32) + + if padding_mode in ("reflect", "replicate"): + img = torch_pad(img, p, mode=padding_mode) + else: + img = torch_pad(img, p, mode=padding_mode, value=float(fill)) + + if need_squeeze: + img = img.squeeze(dim=0) + + if need_cast: + img = img.to(out_dtype) + + return img + + +def resize( + img: Tensor, + size: list[int], + interpolation: str = "bilinear", + antialias: Optional[bool] = True, +) -> Tensor: + _assert_image_tensor(img) + + if isinstance(size, tuple): + size = list(size) + + if antialias is None: + antialias = False + + if antialias and interpolation not in ["bilinear", "bicubic"]: + # We manually set it to False to avoid an error downstream in interpolate() + # This behaviour is documented: the parameter is irrelevant for modes + # that are not bilinear or bicubic. We used to raise an error here, but + # now we don't as True is the default. + antialias = False + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [torch.float32, torch.float64]) + + # Define align_corners to avoid warnings + align_corners = False if interpolation in ["bilinear", "bicubic"] else None + + img = interpolate(img, size=size, mode=interpolation, align_corners=align_corners, antialias=antialias) + + if interpolation == "bicubic" and out_dtype == torch.uint8: + img = img.clamp(min=0, max=255) + + img = _cast_squeeze_out(img, need_cast=need_cast, need_squeeze=need_squeeze, out_dtype=out_dtype) + + return img + + +def _assert_grid_transform_inputs( + img: Tensor, + matrix: Optional[list[float]], + interpolation: str, + fill: Optional[Union[int, float, list[float]]], + supported_interpolation_modes: list[str], + coeffs: Optional[list[float]] = None, +) -> None: + + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor") + + _assert_image_tensor(img) + + if matrix is not None and not isinstance(matrix, list): + raise TypeError("Argument matrix should be a list") + + if matrix is not None and len(matrix) != 6: + raise ValueError("Argument matrix should have 6 float values") + + if coeffs is not None and len(coeffs) != 8: + raise ValueError("Argument coeffs should have 8 float values") + + if fill is not None and not isinstance(fill, (int, float, tuple, list)): + warnings.warn("Argument fill should be either int, float, tuple or list") + + # Check fill + num_channels = get_dimensions(img)[0] + if fill is not None and isinstance(fill, (tuple, list)) and len(fill) > 1 and len(fill) != num_channels: + msg = ( + "The number of elements in 'fill' cannot broadcast to match the number of " + "channels of the image ({} != {})" + ) + raise ValueError(msg.format(len(fill), num_channels)) + + if interpolation not in supported_interpolation_modes: + raise ValueError(f"Interpolation mode '{interpolation}' is unsupported with Tensor input") + + +def _cast_squeeze_in(img: Tensor, req_dtypes: list[torch.dtype]) -> tuple[Tensor, bool, bool, torch.dtype]: + need_squeeze = False + # make image NCHW + if img.ndim < 4: + img = img.unsqueeze(dim=0) + need_squeeze = True + + out_dtype = img.dtype + need_cast = False + if out_dtype not in req_dtypes: + need_cast = True + req_dtype = req_dtypes[0] + img = img.to(req_dtype) + return img, need_cast, need_squeeze, out_dtype + + +def _cast_squeeze_out(img: Tensor, need_cast: bool, need_squeeze: bool, out_dtype: torch.dtype) -> Tensor: + if need_squeeze: + img = img.squeeze(dim=0) + + if need_cast: + if out_dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64): + # it is better to round before cast + img = torch.round(img) + img = img.to(out_dtype) + + return img + + +def _apply_grid_transform( + img: Tensor, grid: Tensor, mode: str, fill: Optional[Union[int, float, list[float]]] +) -> Tensor: + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [grid.dtype]) + + if img.shape[0] > 1: + # Apply same grid to a batch of images + grid = grid.expand(img.shape[0], grid.shape[1], grid.shape[2], grid.shape[3]) + + # Append a dummy mask for customized fill colors, should be faster than grid_sample() twice + if fill is not None: + mask = torch.ones((img.shape[0], 1, img.shape[2], img.shape[3]), dtype=img.dtype, device=img.device) + img = torch.cat((img, mask), dim=1) + + img = grid_sample(img, grid, mode=mode, padding_mode="zeros", align_corners=False) + + # Fill with required color + if fill is not None: + mask = img[:, -1:, :, :] # N * 1 * H * W + img = img[:, :-1, :, :] # N * C * H * W + mask = mask.expand_as(img) + fill_list, len_fill = (fill, len(fill)) if isinstance(fill, (tuple, list)) else ([float(fill)], 1) + fill_img = torch.tensor(fill_list, dtype=img.dtype, device=img.device).view(1, len_fill, 1, 1).expand_as(img) + if mode == "nearest": + mask = mask < 0.5 + img[mask] = fill_img[mask] + else: # 'bilinear' + img = img * mask + (1.0 - mask) * fill_img + + img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype) + return img + + +def _gen_affine_grid( + theta: Tensor, + w: int, + h: int, + ow: int, + oh: int, +) -> Tensor: + # https://github.com/pytorch/pytorch/blob/74b65c32be68b15dc7c9e8bb62459efbfbde33d8/aten/src/ATen/native/ + # AffineGridGenerator.cpp#L18 + # Difference with AffineGridGenerator is that: + # 1) we normalize grid values after applying theta + # 2) we can normalize by other image size, such that it covers "extend" option like in PIL.Image.rotate + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=theta.dtype, device=theta.device) + x_grid = torch.linspace(-ow * 0.5 + d, ow * 0.5 + d - 1, steps=ow, device=theta.device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(-oh * 0.5 + d, oh * 0.5 + d - 1, steps=oh, device=theta.device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta = theta.transpose(1, 2) / torch.tensor([0.5 * w, 0.5 * h], dtype=theta.dtype, device=theta.device) + output_grid = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta) + return output_grid.view(1, oh, ow, 2) + + +def affine( + img: Tensor, + matrix: list[float], + interpolation: str = "nearest", + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"]) + + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3) + shape = img.shape + # grid will be generated on the same device as theta and img + grid = _gen_affine_grid(theta, w=shape[-1], h=shape[-2], ow=shape[-1], oh=shape[-2]) + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _compute_affine_output_size(matrix: list[float], w: int, h: int) -> tuple[int, int]: + + # Inspired of PIL implementation: + # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054 + + # pts are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + # Points are shifted due to affine matrix torch convention about + # the center point. Center is (0, 0) for image center pivot point (w * 0.5, h * 0.5) + pts = torch.tensor( + [ + [-0.5 * w, -0.5 * h, 1.0], + [-0.5 * w, 0.5 * h, 1.0], + [0.5 * w, 0.5 * h, 1.0], + [0.5 * w, -0.5 * h, 1.0], + ] + ) + theta = torch.tensor(matrix, dtype=torch.float).view(2, 3) + new_pts = torch.matmul(pts, theta.T) + min_vals, _ = new_pts.min(dim=0) + max_vals, _ = new_pts.max(dim=0) + + # shift points to [0, w] and [0, h] interval to match PIL results + min_vals += torch.tensor((w * 0.5, h * 0.5)) + max_vals += torch.tensor((w * 0.5, h * 0.5)) + + # Truncate precision to 1e-4 to avoid ceil of Xe-15 to 1.0 + tol = 1e-4 + cmax = torch.ceil((max_vals / tol).trunc_() * tol) + cmin = torch.floor((min_vals / tol).trunc_() * tol) + size = cmax - cmin + return int(size[0]), int(size[1]) # w, h + + +def rotate( + img: Tensor, + matrix: list[float], + interpolation: str = "nearest", + expand: bool = False, + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"]) + w, h = img.shape[-1], img.shape[-2] + ow, oh = _compute_affine_output_size(matrix, w, h) if expand else (w, h) + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3) + # grid will be generated on the same device as theta and img + grid = _gen_affine_grid(theta, w=w, h=h, ow=ow, oh=oh) + + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _perspective_grid(coeffs: list[float], ow: int, oh: int, dtype: torch.dtype, device: torch.device) -> Tensor: + # https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/ + # src/libImaging/Geometry.c#L394 + + # + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + # + theta1 = torch.tensor( + [[[coeffs[0], coeffs[1], coeffs[2]], [coeffs[3], coeffs[4], coeffs[5]]]], dtype=dtype, device=device + ) + theta2 = torch.tensor([[[coeffs[6], coeffs[7], 1.0], [coeffs[6], coeffs[7], 1.0]]], dtype=dtype, device=device) + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device) + x_grid = torch.linspace(d, ow * 1.0 + d - 1.0, steps=ow, device=device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(d, oh * 1.0 + d - 1.0, steps=oh, device=device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta1 = theta1.transpose(1, 2) / torch.tensor([0.5 * ow, 0.5 * oh], dtype=dtype, device=device) + output_grid1 = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta1) + output_grid2 = base_grid.view(1, oh * ow, 3).bmm(theta2.transpose(1, 2)) + + output_grid = output_grid1 / output_grid2 - 1.0 + return output_grid.view(1, oh, ow, 2) + + +def perspective( + img: Tensor, + perspective_coeffs: list[float], + interpolation: str = "bilinear", + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor.") + + _assert_image_tensor(img) + + _assert_grid_transform_inputs( + img, + matrix=None, + interpolation=interpolation, + fill=fill, + supported_interpolation_modes=["nearest", "bilinear"], + coeffs=perspective_coeffs, + ) + + ow, oh = img.shape[-1], img.shape[-2] + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + grid = _perspective_grid(perspective_coeffs, ow=ow, oh=oh, dtype=dtype, device=img.device) + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _get_gaussian_kernel1d(kernel_size: int, sigma: float, dtype: torch.dtype, device: torch.device) -> Tensor: + ksize_half = (kernel_size - 1) * 0.5 + + x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size, dtype=dtype, device=device) + pdf = torch.exp(-0.5 * (x / sigma).pow(2)) + kernel1d = pdf / pdf.sum() + + return kernel1d + + +def _get_gaussian_kernel2d( + kernel_size: list[int], sigma: list[float], dtype: torch.dtype, device: torch.device +) -> Tensor: + kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0], dtype, device) + kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1], dtype, device) + kernel2d = torch.mm(kernel1d_y[:, None], kernel1d_x[None, :]) + return kernel2d + + +def gaussian_blur(img: Tensor, kernel_size: list[int], sigma: list[float]) -> Tensor: + if not (isinstance(img, torch.Tensor)): + raise TypeError(f"img should be Tensor. Got {type(img)}") + + _assert_image_tensor(img) + + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype, device=img.device) + kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype]) + + # padding = (left, right, top, bottom) + padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2] + img = torch_pad(img, padding, mode="reflect") + img = conv2d(img, kernel, groups=img.shape[-3]) + + img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype) + return img + + +def invert(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + return _max_value(img.dtype) - img + + +def posterize(img: Tensor, bits: int) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + if img.dtype != torch.uint8: + raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}") + + _assert_channels(img, [1, 3]) + mask = -int(2 ** (8 - bits)) # JIT-friendly for: ~(2 ** (8 - bits) - 1) + return img & mask + + +def solarize(img: Tensor, threshold: float) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + if threshold > _max_value(img.dtype): + raise TypeError("Threshold should be less than bound of img.") + + inverted_img = invert(img) + return torch.where(img >= threshold, inverted_img, img) + + +def _blurred_degenerate_image(img: Tensor) -> Tensor: + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + + kernel = torch.ones((3, 3), dtype=dtype, device=img.device) + kernel[1, 1] = 5.0 + kernel /= kernel.sum() + kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + result_tmp, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype]) + result_tmp = conv2d(result_tmp, kernel, groups=result_tmp.shape[-3]) + result_tmp = _cast_squeeze_out(result_tmp, need_cast, need_squeeze, out_dtype) + + result = img.clone() + result[..., 1:-1, 1:-1] = result_tmp + + return result + + +def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor: + if sharpness_factor < 0: + raise ValueError(f"sharpness_factor ({sharpness_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + if img.size(-1) <= 2 or img.size(-2) <= 2: + return img + + return _blend(img, _blurred_degenerate_image(img), sharpness_factor) + + +def autocontrast(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + bound = _max_value(img.dtype) + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + + minimum = img.amin(dim=(-2, -1), keepdim=True).to(dtype) + maximum = img.amax(dim=(-2, -1), keepdim=True).to(dtype) + scale = bound / (maximum - minimum) + eq_idxs = torch.isfinite(scale).logical_not() + minimum[eq_idxs] = 0 + scale[eq_idxs] = 1 + + return ((img - minimum) * scale).clamp(0, bound).to(img.dtype) + + +def _scale_channel(img_chan: Tensor) -> Tensor: + # TODO: we should expect bincount to always be faster than histc, but this + # isn't always the case. Once + # https://github.com/pytorch/pytorch/issues/53194 is fixed, remove the if + # block and only use bincount. + if img_chan.is_cuda: + hist = torch.histc(img_chan.to(torch.float32), bins=256, min=0, max=255) + else: + hist = torch.bincount(img_chan.reshape(-1), minlength=256) + + nonzero_hist = hist[hist != 0] + step = torch.div(nonzero_hist[:-1].sum(), 255, rounding_mode="floor") + if step == 0: + return img_chan + + lut = torch.div(torch.cumsum(hist, 0) + torch.div(step, 2, rounding_mode="floor"), step, rounding_mode="floor") + lut = torch.nn.functional.pad(lut, [1, 0])[:-1].clamp(0, 255) + + return lut[img_chan.to(torch.int64)].to(torch.uint8) + + +def _equalize_single_image(img: Tensor) -> Tensor: + return torch.stack([_scale_channel(img[c]) for c in range(img.size(0))]) + + +def equalize(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if not (3 <= img.ndim <= 4): + raise TypeError(f"Input image tensor should have 3 or 4 dimensions, but found {img.ndim}") + if img.dtype != torch.uint8: + raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}") + + _assert_channels(img, [1, 3]) + + if img.ndim == 3: + return _equalize_single_image(img) + + return torch.stack([_equalize_single_image(x) for x in img]) + + +def normalize(tensor: Tensor, mean: list[float], std: list[float], inplace: bool = False) -> Tensor: + _assert_image_tensor(tensor) + + if not tensor.is_floating_point(): + raise TypeError(f"Input tensor should be a float tensor. Got {tensor.dtype}.") + + if tensor.ndim < 3: + raise ValueError( + f"Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = {tensor.size()}" + ) + + if not inplace: + tensor = tensor.clone() + + dtype = tensor.dtype + mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device) + std = torch.as_tensor(std, dtype=dtype, device=tensor.device) + if (std == 0).any(): + raise ValueError(f"std evaluated to zero after conversion to {dtype}, leading to division by zero.") + if mean.ndim == 1: + mean = mean.view(-1, 1, 1) + if std.ndim == 1: + std = std.view(-1, 1, 1) + return tensor.sub_(mean).div_(std) + + +def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor: + _assert_image_tensor(img) + + if not inplace: + img = img.clone() + + img[..., i : i + h, j : j + w] = v + return img + + +def _create_identity_grid(size: list[int]) -> Tensor: + hw_space = [torch.linspace((-s + 1) / s, (s - 1) / s, s) for s in size] + grid_y, grid_x = torch.meshgrid(hw_space, indexing="ij") + return torch.stack([grid_x, grid_y], -1).unsqueeze(0) # 1 x H x W x 2 + + +def elastic_transform( + img: Tensor, + displacement: Tensor, + interpolation: str = "bilinear", + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + + if not (isinstance(img, torch.Tensor)): + raise TypeError(f"img should be Tensor. Got {type(img)}") + + size = list(img.shape[-2:]) + displacement = displacement.to(img.device) + + identity_grid = _create_identity_grid(size) + grid = identity_grid.to(img.device) + displacement + return _apply_grid_transform(img, grid, interpolation, fill) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_video.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_video.py new file mode 100644 index 0000000000000000000000000000000000000000..91df7d42cd71fc554aba51fcf5e90db30e3c3851 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_functional_video.py @@ -0,0 +1,114 @@ +import warnings + +import torch + + +warnings.warn( + "The 'torchvision.transforms._functional_video' module is deprecated since 0.12 and will be removed in the future. " + "Please use the 'torchvision.transforms.functional' module instead." +) + + +def _is_tensor_video_clip(clip): + if not torch.is_tensor(clip): + raise TypeError("clip should be Tensor. Got %s" % type(clip)) + + if not clip.ndimension() == 4: + raise ValueError("clip should be 4D. Got %dD" % clip.dim()) + + return True + + +def crop(clip, i, j, h, w): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + """ + if len(clip.size()) != 4: + raise ValueError("clip should be a 4D tensor") + return clip[..., i : i + h, j : j + w] + + +def resize(clip, target_size, interpolation_mode): + if len(target_size) != 2: + raise ValueError(f"target size should be tuple (height, width), instead got {target_size}") + return torch.nn.functional.interpolate(clip, size=target_size, mode=interpolation_mode, align_corners=False) + + +def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"): + """ + Do spatial cropping and resizing to the video clip + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + i (int): i in (i,j) i.e coordinates of the upper left corner. + j (int): j in (i,j) i.e coordinates of the upper left corner. + h (int): Height of the cropped region. + w (int): Width of the cropped region. + size (tuple(int, int)): height and width of resized clip + Returns: + clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W) + """ + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + clip = crop(clip, i, j, h, w) + clip = resize(clip, size, interpolation_mode) + return clip + + +def center_crop(clip, crop_size): + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + h, w = clip.size(-2), clip.size(-1) + th, tw = crop_size + if h < th or w < tw: + raise ValueError("height and width must be no smaller than crop_size") + + i = int(round((h - th) / 2.0)) + j = int(round((w - tw) / 2.0)) + return crop(clip, i, j, th, tw) + + +def to_tensor(clip): + """ + Convert tensor data type from uint8 to float, divide value by 255.0 and + permute the dimensions of clip tensor + Args: + clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C) + Return: + clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) + """ + _is_tensor_video_clip(clip) + if not clip.dtype == torch.uint8: + raise TypeError("clip tensor should have data type uint8. Got %s" % str(clip.dtype)) + return clip.float().permute(3, 0, 1, 2) / 255.0 + + +def normalize(clip, mean, std, inplace=False): + """ + Args: + clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W) + mean (tuple): pixel RGB mean. Size is (3) + std (tuple): pixel standard deviation. Size is (3) + Returns: + normalized clip (torch.tensor): Size is (C, T, H, W) + """ + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + if not inplace: + clip = clip.clone() + mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device) + std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device) + clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None]) + return clip + + +def hflip(clip): + """ + Args: + clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W) + Returns: + flipped clip (torch.tensor): Size is (C, T, H, W) + """ + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + return clip.flip(-1) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_presets.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_presets.py new file mode 100644 index 0000000000000000000000000000000000000000..a7eba6721c789625da9b5a4e8ed7372c6efbcd4d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_presets.py @@ -0,0 +1,217 @@ +""" +This file is part of the private API. Please do not use directly these classes as they will be modified on +future versions without warning. The classes should be accessed only via the transforms argument of Weights. +""" + +from typing import Optional, Union + +import torch +from torch import nn, Tensor + +from . import functional as F, InterpolationMode + + +__all__ = [ + "ObjectDetection", + "ImageClassification", + "VideoClassification", + "SemanticSegmentation", + "OpticalFlow", +] + + +class ObjectDetection(nn.Module): + def forward(self, img: Tensor) -> Tensor: + if not isinstance(img, Tensor): + img = F.pil_to_tensor(img) + return F.convert_image_dtype(img, torch.float) + + def __repr__(self) -> str: + return self.__class__.__name__ + "()" + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + "The images are rescaled to ``[0.0, 1.0]``." + ) + + +class ImageClassification(nn.Module): + def __init__( + self, + *, + crop_size: int, + resize_size: int = 256, + mean: tuple[float, ...] = (0.485, 0.456, 0.406), + std: tuple[float, ...] = (0.229, 0.224, 0.225), + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.crop_size = [crop_size] + self.resize_size = [resize_size] + self.mean = list(mean) + self.std = list(std) + self.interpolation = interpolation + self.antialias = antialias + + def forward(self, img: Tensor) -> Tensor: + img = F.resize(img, self.resize_size, interpolation=self.interpolation, antialias=self.antialias) + img = F.center_crop(img, self.crop_size) + if not isinstance(img, Tensor): + img = F.pil_to_tensor(img) + img = F.convert_image_dtype(img, torch.float) + img = F.normalize(img, mean=self.mean, std=self.std) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n crop_size={self.crop_size}" + format_string += f"\n resize_size={self.resize_size}" + format_string += f"\n mean={self.mean}" + format_string += f"\n std={self.std}" + format_string += f"\n interpolation={self.interpolation}" + format_string += "\n)" + return format_string + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + f"The images are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``, " + f"followed by a central crop of ``crop_size={self.crop_size}``. Finally the values are first rescaled to " + f"``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and ``std={self.std}``." + ) + + +class VideoClassification(nn.Module): + def __init__( + self, + *, + crop_size: tuple[int, int], + resize_size: Union[tuple[int], tuple[int, int]], + mean: tuple[float, ...] = (0.43216, 0.394666, 0.37645), + std: tuple[float, ...] = (0.22803, 0.22145, 0.216989), + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + ) -> None: + super().__init__() + self.crop_size = list(crop_size) + self.resize_size = list(resize_size) + self.mean = list(mean) + self.std = list(std) + self.interpolation = interpolation + + def forward(self, vid: Tensor) -> Tensor: + need_squeeze = False + if vid.ndim < 5: + vid = vid.unsqueeze(dim=0) + need_squeeze = True + + N, T, C, H, W = vid.shape + vid = vid.view(-1, C, H, W) + # We hard-code antialias=False to preserve results after we changed + # its default from None to True (see + # https://github.com/pytorch/vision/pull/7160) + # TODO: we could re-train the video models with antialias=True? + vid = F.resize(vid, self.resize_size, interpolation=self.interpolation, antialias=False) + vid = F.center_crop(vid, self.crop_size) + vid = F.convert_image_dtype(vid, torch.float) + vid = F.normalize(vid, mean=self.mean, std=self.std) + H, W = self.crop_size + vid = vid.view(N, T, C, H, W) + vid = vid.permute(0, 2, 1, 3, 4) # (N, T, C, H, W) => (N, C, T, H, W) + + if need_squeeze: + vid = vid.squeeze(dim=0) + return vid + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n crop_size={self.crop_size}" + format_string += f"\n resize_size={self.resize_size}" + format_string += f"\n mean={self.mean}" + format_string += f"\n std={self.std}" + format_string += f"\n interpolation={self.interpolation}" + format_string += "\n)" + return format_string + + def describe(self) -> str: + return ( + "Accepts batched ``(B, T, C, H, W)`` and single ``(T, C, H, W)`` video frame ``torch.Tensor`` objects. " + f"The frames are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``, " + f"followed by a central crop of ``crop_size={self.crop_size}``. Finally the values are first rescaled to " + f"``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and ``std={self.std}``. Finally the output " + "dimensions are permuted to ``(..., C, T, H, W)`` tensors." + ) + + +class SemanticSegmentation(nn.Module): + def __init__( + self, + *, + resize_size: Optional[int], + mean: tuple[float, ...] = (0.485, 0.456, 0.406), + std: tuple[float, ...] = (0.229, 0.224, 0.225), + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.resize_size = [resize_size] if resize_size is not None else None + self.mean = list(mean) + self.std = list(std) + self.interpolation = interpolation + self.antialias = antialias + + def forward(self, img: Tensor) -> Tensor: + if isinstance(self.resize_size, list): + img = F.resize(img, self.resize_size, interpolation=self.interpolation, antialias=self.antialias) + if not isinstance(img, Tensor): + img = F.pil_to_tensor(img) + img = F.convert_image_dtype(img, torch.float) + img = F.normalize(img, mean=self.mean, std=self.std) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n resize_size={self.resize_size}" + format_string += f"\n mean={self.mean}" + format_string += f"\n std={self.std}" + format_string += f"\n interpolation={self.interpolation}" + format_string += "\n)" + return format_string + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + f"The images are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``. " + f"Finally the values are first rescaled to ``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and " + f"``std={self.std}``." + ) + + +class OpticalFlow(nn.Module): + def forward(self, img1: Tensor, img2: Tensor) -> tuple[Tensor, Tensor]: + if not isinstance(img1, Tensor): + img1 = F.pil_to_tensor(img1) + if not isinstance(img2, Tensor): + img2 = F.pil_to_tensor(img2) + + img1 = F.convert_image_dtype(img1, torch.float) + img2 = F.convert_image_dtype(img2, torch.float) + + # map [0, 1] into [-1, 1] + img1 = F.normalize(img1, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + img2 = F.normalize(img2, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + img1 = img1.contiguous() + img2 = img2.contiguous() + + return img1, img2 + + def __repr__(self) -> str: + return self.__class__.__name__ + "()" + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + "The images are rescaled to ``[-1.0, 1.0]``." + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_transforms_video.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_transforms_video.py new file mode 100644 index 0000000000000000000000000000000000000000..a04da4f74849805641e4c470f6b6b8d5f7000e3a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/_transforms_video.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 + +import numbers +import random +import warnings + +from torchvision.transforms import RandomCrop, RandomResizedCrop + +from . import _functional_video as F + + +__all__ = [ + "RandomCropVideo", + "RandomResizedCropVideo", + "CenterCropVideo", + "NormalizeVideo", + "ToTensorVideo", + "RandomHorizontalFlipVideo", +] + + +warnings.warn( + "The 'torchvision.transforms._transforms_video' module is deprecated since 0.12 and will be removed in the future. " + "Please use the 'torchvision.transforms' module instead." +) + + +class RandomCropVideo(RandomCrop): + def __init__(self, size): + if isinstance(size, numbers.Number): + self.size = (int(size), int(size)) + else: + self.size = size + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: randomly cropped/resized video clip. + size is (C, T, OH, OW) + """ + i, j, h, w = self.get_params(clip, self.size) + return F.crop(clip, i, j, h, w) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size})" + + +class RandomResizedCropVideo(RandomResizedCrop): + def __init__( + self, + size, + scale=(0.08, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), + interpolation_mode="bilinear", + ): + if isinstance(size, tuple): + if len(size) != 2: + raise ValueError(f"size should be tuple (height, width), instead got {size}") + self.size = size + else: + self.size = (size, size) + + self.interpolation_mode = interpolation_mode + self.scale = scale + self.ratio = ratio + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: randomly cropped/resized video clip. + size is (C, T, H, W) + """ + i, j, h, w = self.get_params(clip, self.scale, self.ratio) + return F.resized_crop(clip, i, j, h, w, self.size, self.interpolation_mode) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}, scale={self.scale}, ratio={self.ratio})" + + +class CenterCropVideo: + def __init__(self, crop_size): + if isinstance(crop_size, numbers.Number): + self.crop_size = (int(crop_size), int(crop_size)) + else: + self.crop_size = crop_size + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: central cropping of video clip. Size is + (C, T, crop_size, crop_size) + """ + return F.center_crop(clip, self.crop_size) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(crop_size={self.crop_size})" + + +class NormalizeVideo: + """ + Normalize the video clip by mean subtraction and division by standard deviation + Args: + mean (3-tuple): pixel RGB mean + std (3-tuple): pixel RGB standard deviation + inplace (boolean): whether do in-place normalization + """ + + def __init__(self, mean, std, inplace=False): + self.mean = mean + self.std = std + self.inplace = inplace + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): video clip to be normalized. Size is (C, T, H, W) + """ + return F.normalize(clip, self.mean, self.std, self.inplace) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})" + + +class ToTensorVideo: + """ + Convert tensor data type from uint8 to float, divide value by 255.0 and + permute the dimensions of clip tensor + """ + + def __init__(self): + pass + + def __call__(self, clip): + """ + Args: + clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C) + Return: + clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) + """ + return F.to_tensor(clip) + + def __repr__(self) -> str: + return self.__class__.__name__ + + +class RandomHorizontalFlipVideo: + """ + Flip the video clip along the horizontal direction with a given probability + Args: + p (float): probability of the clip being flipped. Default value is 0.5 + """ + + def __init__(self, p=0.5): + self.p = p + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Size is (C, T, H, W) + Return: + clip (torch.tensor): Size is (C, T, H, W) + """ + if random.random() < self.p: + clip = F.hflip(clip) + return clip + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/autoaugment.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/autoaugment.py new file mode 100644 index 0000000000000000000000000000000000000000..20291d09b9432b99a94f2241d2c2af76f4fde526 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/autoaugment.py @@ -0,0 +1,615 @@ +import math +from enum import Enum +from typing import Optional + +import torch +from torch import Tensor + +from . import functional as F, InterpolationMode + +__all__ = ["AutoAugmentPolicy", "AutoAugment", "RandAugment", "TrivialAugmentWide", "AugMix"] + + +def _apply_op( + img: Tensor, op_name: str, magnitude: float, interpolation: InterpolationMode, fill: Optional[list[float]] +): + if op_name == "ShearX": + # magnitude should be arctan(magnitude) + # official autoaug: (1, level, 0, 0, 1, 0) + # https://github.com/tensorflow/models/blob/dd02069717128186b88afa8d857ce57d17957f03/research/autoaugment/augmentation_transforms.py#L290 + # compared to + # torchvision: (1, tan(level), 0, 0, 1, 0) + # https://github.com/pytorch/vision/blob/0c2373d0bba3499e95776e7936e207d8a1676e65/torchvision/transforms/functional.py#L976 + img = F.affine( + img, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[math.degrees(math.atan(magnitude)), 0.0], + interpolation=interpolation, + fill=fill, + center=[0, 0], + ) + elif op_name == "ShearY": + # magnitude should be arctan(magnitude) + # See above + img = F.affine( + img, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[0.0, math.degrees(math.atan(magnitude))], + interpolation=interpolation, + fill=fill, + center=[0, 0], + ) + elif op_name == "TranslateX": + img = F.affine( + img, + angle=0.0, + translate=[int(magnitude), 0], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill, + ) + elif op_name == "TranslateY": + img = F.affine( + img, + angle=0.0, + translate=[0, int(magnitude)], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill, + ) + elif op_name == "Rotate": + img = F.rotate(img, magnitude, interpolation=interpolation, fill=fill) + elif op_name == "Brightness": + img = F.adjust_brightness(img, 1.0 + magnitude) + elif op_name == "Color": + img = F.adjust_saturation(img, 1.0 + magnitude) + elif op_name == "Contrast": + img = F.adjust_contrast(img, 1.0 + magnitude) + elif op_name == "Sharpness": + img = F.adjust_sharpness(img, 1.0 + magnitude) + elif op_name == "Posterize": + img = F.posterize(img, int(magnitude)) + elif op_name == "Solarize": + img = F.solarize(img, magnitude) + elif op_name == "AutoContrast": + img = F.autocontrast(img) + elif op_name == "Equalize": + img = F.equalize(img) + elif op_name == "Invert": + img = F.invert(img) + elif op_name == "Identity": + pass + else: + raise ValueError(f"The provided operator {op_name} is not recognized.") + return img + + +class AutoAugmentPolicy(Enum): + """AutoAugment policies learned on different datasets. + Available policies are IMAGENET, CIFAR10 and SVHN. + """ + + IMAGENET = "imagenet" + CIFAR10 = "cifar10" + SVHN = "svhn" + + +# FIXME: Eliminate copy-pasted code for fill standardization and _augmentation_space() by moving stuff on a base class +class AutoAugment(torch.nn.Module): + r"""AutoAugment data augmentation method based on + `"AutoAugment: Learning Augmentation Strategies from Data" `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + policy (AutoAugmentPolicy): Desired policy enum defined by + :class:`torchvision.transforms.autoaugment.AutoAugmentPolicy`. Default is ``AutoAugmentPolicy.IMAGENET``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + policy: AutoAugmentPolicy = AutoAugmentPolicy.IMAGENET, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.policy = policy + self.interpolation = interpolation + self.fill = fill + self.policies = self._get_policies(policy) + + def _get_policies( + self, policy: AutoAugmentPolicy + ) -> list[tuple[tuple[str, float, Optional[int]], tuple[str, float, Optional[int]]]]: + if policy == AutoAugmentPolicy.IMAGENET: + return [ + (("Posterize", 0.4, 8), ("Rotate", 0.6, 9)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + (("Posterize", 0.6, 7), ("Posterize", 0.6, 6)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Equalize", 0.4, None), ("Rotate", 0.8, 8)), + (("Solarize", 0.6, 3), ("Equalize", 0.6, None)), + (("Posterize", 0.8, 5), ("Equalize", 1.0, None)), + (("Rotate", 0.2, 3), ("Solarize", 0.6, 8)), + (("Equalize", 0.6, None), ("Posterize", 0.4, 6)), + (("Rotate", 0.8, 8), ("Color", 0.4, 0)), + (("Rotate", 0.4, 9), ("Equalize", 0.6, None)), + (("Equalize", 0.0, None), ("Equalize", 0.8, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Rotate", 0.8, 8), ("Color", 1.0, 2)), + (("Color", 0.8, 8), ("Solarize", 0.8, 7)), + (("Sharpness", 0.4, 7), ("Invert", 0.6, None)), + (("ShearX", 0.6, 5), ("Equalize", 1.0, None)), + (("Color", 0.4, 0), ("Equalize", 0.6, None)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + ] + elif policy == AutoAugmentPolicy.CIFAR10: + return [ + (("Invert", 0.1, None), ("Contrast", 0.2, 6)), + (("Rotate", 0.7, 2), ("TranslateX", 0.3, 9)), + (("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)), + (("ShearY", 0.5, 8), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.5, None), ("Equalize", 0.9, None)), + (("ShearY", 0.2, 7), ("Posterize", 0.3, 7)), + (("Color", 0.4, 3), ("Brightness", 0.6, 7)), + (("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)), + (("Equalize", 0.6, None), ("Equalize", 0.5, None)), + (("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)), + (("Color", 0.7, 7), ("TranslateX", 0.5, 8)), + (("Equalize", 0.3, None), ("AutoContrast", 0.4, None)), + (("TranslateY", 0.4, 3), ("Sharpness", 0.2, 6)), + (("Brightness", 0.9, 6), ("Color", 0.2, 8)), + (("Solarize", 0.5, 2), ("Invert", 0.0, None)), + (("Equalize", 0.2, None), ("AutoContrast", 0.6, None)), + (("Equalize", 0.2, None), ("Equalize", 0.6, None)), + (("Color", 0.9, 9), ("Equalize", 0.6, None)), + (("AutoContrast", 0.8, None), ("Solarize", 0.2, 8)), + (("Brightness", 0.1, 3), ("Color", 0.7, 0)), + (("Solarize", 0.4, 5), ("AutoContrast", 0.9, None)), + (("TranslateY", 0.9, 9), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.9, None), ("Solarize", 0.8, 3)), + (("Equalize", 0.8, None), ("Invert", 0.1, None)), + (("TranslateY", 0.7, 9), ("AutoContrast", 0.9, None)), + ] + elif policy == AutoAugmentPolicy.SVHN: + return [ + (("ShearX", 0.9, 4), ("Invert", 0.2, None)), + (("ShearY", 0.9, 8), ("Invert", 0.7, None)), + (("Equalize", 0.6, None), ("Solarize", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("AutoContrast", 0.8, None)), + (("ShearY", 0.9, 8), ("Invert", 0.4, None)), + (("ShearY", 0.9, 5), ("Solarize", 0.2, 6)), + (("Invert", 0.9, None), ("AutoContrast", 0.8, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("Solarize", 0.3, 3)), + (("ShearY", 0.8, 8), ("Invert", 0.7, None)), + (("Equalize", 0.9, None), ("TranslateY", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Contrast", 0.3, 3), ("Rotate", 0.8, 4)), + (("Invert", 0.8, None), ("TranslateY", 0.0, 2)), + (("ShearY", 0.7, 6), ("Solarize", 0.4, 8)), + (("Invert", 0.6, None), ("Rotate", 0.8, 4)), + (("ShearY", 0.3, 7), ("TranslateX", 0.9, 3)), + (("ShearX", 0.1, 6), ("Invert", 0.6, None)), + (("Solarize", 0.7, 2), ("TranslateY", 0.6, 7)), + (("ShearY", 0.8, 4), ("Invert", 0.8, None)), + (("ShearX", 0.7, 9), ("TranslateY", 0.8, 3)), + (("ShearY", 0.8, 5), ("AutoContrast", 0.7, None)), + (("ShearX", 0.7, 2), ("Invert", 0.1, None)), + ] + else: + raise ValueError(f"The provided policy {policy} is not recognized.") + + def _augmentation_space(self, num_bins: int, image_size: tuple[int, int]) -> dict[str, tuple[Tensor, bool]]: + return { + # op_name: (magnitudes, signed) + "ShearX": (torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (torch.linspace(0.0, 150.0 / 331.0 * image_size[1], num_bins), True), + "TranslateY": (torch.linspace(0.0, 150.0 / 331.0 * image_size[0], num_bins), True), + "Rotate": (torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (torch.linspace(0.0, 0.9, num_bins), True), + "Color": (torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + "Invert": (torch.tensor(0.0), False), + } + + @staticmethod + def get_params(transform_num: int) -> tuple[int, Tensor, Tensor]: + """Get parameters for autoaugment transformation + + Returns: + params required by the autoaugment transformation + """ + policy_id = int(torch.randint(transform_num, (1,)).item()) + probs = torch.rand((2,)) + signs = torch.randint(2, (2,)) + + return policy_id, probs, signs + + def forward(self, img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: AutoAugmented image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + + transform_id, probs, signs = self.get_params(len(self.policies)) + + op_meta = self._augmentation_space(10, (height, width)) + for i, (op_name, p, magnitude_id) in enumerate(self.policies[transform_id]): + if probs[i] <= p: + magnitudes, signed = op_meta[op_name] + magnitude = float(magnitudes[magnitude_id].item()) if magnitude_id is not None else 0.0 + if signed and signs[i] == 0: + magnitude *= -1.0 + img = _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill) + + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(policy={self.policy}, fill={self.fill})" + + +class RandAugment(torch.nn.Module): + r"""RandAugment data augmentation method based on + `"RandAugment: Practical automated data augmentation with a reduced search space" + `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_ops (int): Number of augmentation transformations to apply sequentially. + magnitude (int): Magnitude for all the transformations. + num_magnitude_bins (int): The number of different magnitude values. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + num_ops: int = 2, + magnitude: int = 9, + num_magnitude_bins: int = 31, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.num_ops = num_ops + self.magnitude = magnitude + self.num_magnitude_bins = num_magnitude_bins + self.interpolation = interpolation + self.fill = fill + + def _augmentation_space(self, num_bins: int, image_size: tuple[int, int]) -> dict[str, tuple[Tensor, bool]]: + return { + # op_name: (magnitudes, signed) + "Identity": (torch.tensor(0.0), False), + "ShearX": (torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (torch.linspace(0.0, 150.0 / 331.0 * image_size[1], num_bins), True), + "TranslateY": (torch.linspace(0.0, 150.0 / 331.0 * image_size[0], num_bins), True), + "Rotate": (torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (torch.linspace(0.0, 0.9, num_bins), True), + "Color": (torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + } + + def forward(self, img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + + op_meta = self._augmentation_space(self.num_magnitude_bins, (height, width)) + for _ in range(self.num_ops): + op_index = int(torch.randint(len(op_meta), (1,)).item()) + op_name = list(op_meta.keys())[op_index] + magnitudes, signed = op_meta[op_name] + magnitude = float(magnitudes[self.magnitude].item()) if magnitudes.ndim > 0 else 0.0 + if signed and torch.randint(2, (1,)): + magnitude *= -1.0 + img = _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill) + + return img + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"num_ops={self.num_ops}" + f", magnitude={self.magnitude}" + f", num_magnitude_bins={self.num_magnitude_bins}" + f", interpolation={self.interpolation}" + f", fill={self.fill}" + f")" + ) + return s + + +class TrivialAugmentWide(torch.nn.Module): + r"""Dataset-independent data-augmentation with TrivialAugment Wide, as described in + `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_magnitude_bins (int): The number of different magnitude values. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + num_magnitude_bins: int = 31, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.num_magnitude_bins = num_magnitude_bins + self.interpolation = interpolation + self.fill = fill + + def _augmentation_space(self, num_bins: int) -> dict[str, tuple[Tensor, bool]]: + return { + # op_name: (magnitudes, signed) + "Identity": (torch.tensor(0.0), False), + "ShearX": (torch.linspace(0.0, 0.99, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.99, num_bins), True), + "TranslateX": (torch.linspace(0.0, 32.0, num_bins), True), + "TranslateY": (torch.linspace(0.0, 32.0, num_bins), True), + "Rotate": (torch.linspace(0.0, 135.0, num_bins), True), + "Brightness": (torch.linspace(0.0, 0.99, num_bins), True), + "Color": (torch.linspace(0.0, 0.99, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.99, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.99, num_bins), True), + "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 6)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + } + + def forward(self, img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + + op_meta = self._augmentation_space(self.num_magnitude_bins) + op_index = int(torch.randint(len(op_meta), (1,)).item()) + op_name = list(op_meta.keys())[op_index] + magnitudes, signed = op_meta[op_name] + magnitude = ( + float(magnitudes[torch.randint(len(magnitudes), (1,), dtype=torch.long)].item()) + if magnitudes.ndim > 0 + else 0.0 + ) + if signed and torch.randint(2, (1,)): + magnitude *= -1.0 + + return _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"num_magnitude_bins={self.num_magnitude_bins}" + f", interpolation={self.interpolation}" + f", fill={self.fill}" + f")" + ) + return s + + +class AugMix(torch.nn.Module): + r"""AugMix data augmentation method based on + `"AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty" `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + severity (int): The severity of base augmentation operators. Default is ``3``. + mixture_width (int): The number of augmentation chains. Default is ``3``. + chain_depth (int): The depth of augmentation chains. A negative value denotes stochastic depth sampled from the interval [1, 3]. + Default is ``-1``. + alpha (float): The hyperparameter for the probability distributions. Default is ``1.0``. + all_ops (bool): Use all operations (including brightness, contrast, color and sharpness). Default is ``True``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + severity: int = 3, + mixture_width: int = 3, + chain_depth: int = -1, + alpha: float = 1.0, + all_ops: bool = True, + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self._PARAMETER_MAX = 10 + if not (1 <= severity <= self._PARAMETER_MAX): + raise ValueError(f"The severity must be between [1, {self._PARAMETER_MAX}]. Got {severity} instead.") + self.severity = severity + self.mixture_width = mixture_width + self.chain_depth = chain_depth + self.alpha = alpha + self.all_ops = all_ops + self.interpolation = interpolation + self.fill = fill + + def _augmentation_space(self, num_bins: int, image_size: tuple[int, int]) -> dict[str, tuple[Tensor, bool]]: + s = { + # op_name: (magnitudes, signed) + "ShearX": (torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (torch.linspace(0.0, image_size[1] / 3.0, num_bins), True), + "TranslateY": (torch.linspace(0.0, image_size[0] / 3.0, num_bins), True), + "Rotate": (torch.linspace(0.0, 30.0, num_bins), True), + "Posterize": (4 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + } + if self.all_ops: + s.update( + { + "Brightness": (torch.linspace(0.0, 0.9, num_bins), True), + "Color": (torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True), + } + ) + return s + + @torch.jit.unused + def _pil_to_tensor(self, img) -> Tensor: + return F.pil_to_tensor(img) + + @torch.jit.unused + def _tensor_to_pil(self, img: Tensor): + return F.to_pil_image(img) + + def _sample_dirichlet(self, params: Tensor) -> Tensor: + # Must be on a separate method so that we can overwrite it in tests. + return torch._sample_dirichlet(params) + + def forward(self, orig_img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(orig_img) + if isinstance(orig_img, Tensor): + img = orig_img + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + else: + img = self._pil_to_tensor(orig_img) + + op_meta = self._augmentation_space(self._PARAMETER_MAX, (height, width)) + + orig_dims = list(img.shape) + batch = img.view([1] * max(4 - img.ndim, 0) + orig_dims) + batch_dims = [batch.size(0)] + [1] * (batch.ndim - 1) + + # Sample the beta weights for combining the original and augmented image. To get Beta, we use a Dirichlet + # with 2 parameters. The 1st column stores the weights of the original and the 2nd the ones of augmented image. + m = self._sample_dirichlet( + torch.tensor([self.alpha, self.alpha], device=batch.device).expand(batch_dims[0], -1) + ) + + # Sample the mixing weights and combine them with the ones sampled from Beta for the augmented images. + combined_weights = self._sample_dirichlet( + torch.tensor([self.alpha] * self.mixture_width, device=batch.device).expand(batch_dims[0], -1) + ) * m[:, 1].view([batch_dims[0], -1]) + + mix = m[:, 0].view(batch_dims) * batch + for i in range(self.mixture_width): + aug = batch + depth = self.chain_depth if self.chain_depth > 0 else int(torch.randint(low=1, high=4, size=(1,)).item()) + for _ in range(depth): + op_index = int(torch.randint(len(op_meta), (1,)).item()) + op_name = list(op_meta.keys())[op_index] + magnitudes, signed = op_meta[op_name] + magnitude = ( + float(magnitudes[torch.randint(self.severity, (1,), dtype=torch.long)].item()) + if magnitudes.ndim > 0 + else 0.0 + ) + if signed and torch.randint(2, (1,)): + magnitude *= -1.0 + aug = _apply_op(aug, op_name, magnitude, interpolation=self.interpolation, fill=fill) + mix.add_(combined_weights[:, i].view(batch_dims) * aug) + mix = mix.view(orig_dims).to(dtype=img.dtype) + + if not isinstance(orig_img, Tensor): + return self._tensor_to_pil(mix) + return mix + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"severity={self.severity}" + f", mixture_width={self.mixture_width}" + f", chain_depth={self.chain_depth}" + f", alpha={self.alpha}" + f", all_ops={self.all_ops}" + f", interpolation={self.interpolation}" + f", fill={self.fill}" + f")" + ) + return s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/functional.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..7b950b0c45b53f82949d3fe14850a3d1c17f24d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/functional.py @@ -0,0 +1,1586 @@ +import math +import numbers +import sys +import warnings +from enum import Enum +from typing import Any, Optional, Union + +import numpy as np +import torch +from PIL import Image +from PIL.Image import Image as PILImage +from torch import Tensor + +try: + import accimage +except ImportError: + accimage = None + +from ..utils import _Image_fromarray, _log_api_usage_once +from . import _functional_pil as F_pil, _functional_tensor as F_t + + +class InterpolationMode(Enum): + """Interpolation modes + Available interpolation methods are ``nearest``, ``nearest-exact``, ``bilinear``, ``bicubic``, ``box``, ``hamming``, + and ``lanczos``. + """ + + NEAREST = "nearest" + NEAREST_EXACT = "nearest-exact" + BILINEAR = "bilinear" + BICUBIC = "bicubic" + # For PIL compatibility + BOX = "box" + HAMMING = "hamming" + LANCZOS = "lanczos" + + +# TODO: Once torchscript supports Enums with staticmethod +# this can be put into InterpolationMode as staticmethod +def _interpolation_modes_from_int(i: int) -> InterpolationMode: + inverse_modes_mapping = { + 0: InterpolationMode.NEAREST, + 2: InterpolationMode.BILINEAR, + 3: InterpolationMode.BICUBIC, + 4: InterpolationMode.BOX, + 5: InterpolationMode.HAMMING, + 1: InterpolationMode.LANCZOS, + } + return inverse_modes_mapping[i] + + +pil_modes_mapping = { + InterpolationMode.NEAREST: 0, + InterpolationMode.BILINEAR: 2, + InterpolationMode.BICUBIC: 3, + InterpolationMode.NEAREST_EXACT: 0, + InterpolationMode.BOX: 4, + InterpolationMode.HAMMING: 5, + InterpolationMode.LANCZOS: 1, +} + +_is_pil_image = F_pil._is_pil_image + + +def get_dimensions(img: Tensor) -> list[int]: + """Returns the dimensions of an image as [channels, height, width]. + + Args: + img (PIL Image or Tensor): The image to be checked. + + Returns: + List[int]: The image dimensions. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(get_dimensions) + if isinstance(img, torch.Tensor): + return F_t.get_dimensions(img) + + return F_pil.get_dimensions(img) + + +def get_image_size(img: Tensor) -> list[int]: + """Returns the size of an image as [width, height]. + + Args: + img (PIL Image or Tensor): The image to be checked. + + Returns: + List[int]: The image size. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(get_image_size) + if isinstance(img, torch.Tensor): + return F_t.get_image_size(img) + + return F_pil.get_image_size(img) + + +def get_image_num_channels(img: Tensor) -> int: + """Returns the number of channels of an image. + + Args: + img (PIL Image or Tensor): The image to be checked. + + Returns: + int: The number of channels. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(get_image_num_channels) + if isinstance(img, torch.Tensor): + return F_t.get_image_num_channels(img) + + return F_pil.get_image_num_channels(img) + + +@torch.jit.unused +def _is_numpy(img: Any) -> bool: + return isinstance(img, np.ndarray) + + +@torch.jit.unused +def _is_numpy_image(img: Any) -> bool: + return img.ndim in {2, 3} + + +def to_tensor(pic: Union[PILImage, np.ndarray]) -> Tensor: + """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. + This function does not support torchscript. + + See :class:`~torchvision.transforms.ToTensor` for more details. + + Args: + pic (PIL Image or numpy.ndarray): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(to_tensor) + if not (F_pil._is_pil_image(pic) or _is_numpy(pic)): + raise TypeError(f"pic should be PIL Image or ndarray. Got {type(pic)}") + + if _is_numpy(pic) and not _is_numpy_image(pic): + raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.") + + default_float_dtype = torch.get_default_dtype() + + if isinstance(pic, np.ndarray): + # handle numpy array + if pic.ndim == 2: + pic = pic[:, :, None] + + img = torch.from_numpy(pic.transpose((2, 0, 1))).contiguous() + # backward compatibility + if isinstance(img, torch.ByteTensor): + return img.to(dtype=default_float_dtype).div(255) + else: + return img + + if accimage is not None and isinstance(pic, accimage.Image): + nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) + pic.copyto(nppic) + return torch.from_numpy(nppic).to(dtype=default_float_dtype) + + # handle PIL Image + mode_to_nptype = {"I": np.int32, "I;16" if sys.byteorder == "little" else "I;16B": np.int16, "F": np.float32} + img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True)) + + if pic.mode == "1": + img = 255 * img + img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic)) + # put it from HWC to CHW format + img = img.permute((2, 0, 1)).contiguous() + if isinstance(img, torch.ByteTensor): + return img.to(dtype=default_float_dtype).div(255) + else: + return img + + +def pil_to_tensor(pic: Any) -> Tensor: + """Convert a ``PIL Image`` to a tensor of the same type. + This function does not support torchscript. + + See :class:`~torchvision.transforms.PILToTensor` for more details. + + .. note:: + + A deep copy of the underlying array is performed. + + Args: + pic (PIL Image): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(pil_to_tensor) + if not F_pil._is_pil_image(pic): + raise TypeError(f"pic should be PIL Image. Got {type(pic)}") + + if accimage is not None and isinstance(pic, accimage.Image): + # accimage format is always uint8 internally, so always return uint8 here + nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.uint8) + pic.copyto(nppic) + return torch.as_tensor(nppic) + + # handle PIL Image + img = torch.as_tensor(np.array(pic, copy=True)) + img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic)) + # put it from HWC to CHW format + img = img.permute((2, 0, 1)) + return img + + +def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor: + """Convert a tensor image to the given ``dtype`` and scale the values accordingly + This function does not support PIL Image. + + Args: + image (torch.Tensor): Image to be converted + dtype (torch.dtype): Desired data type of the output + + Returns: + Tensor: Converted image + + .. note:: + + When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. + If converted back and forth, this mismatch has no effect. + + Raises: + RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as + well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to + overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range + of the integer ``dtype``. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(convert_image_dtype) + if not isinstance(image, torch.Tensor): + raise TypeError("Input img should be Tensor Image") + + return F_t.convert_image_dtype(image, dtype) + + +def to_pil_image(pic, mode=None): + """Convert a tensor or an ndarray to PIL Image. This function does not support torchscript. + + See :class:`~torchvision.transforms.ToPILImage` for more details. + + Args: + pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. + mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). + + .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes + + Returns: + PIL Image: Image converted to PIL Image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(to_pil_image) + + if isinstance(pic, torch.Tensor): + if pic.ndim == 3: + pic = pic.permute((1, 2, 0)) + pic = pic.numpy(force=True) + elif not isinstance(pic, np.ndarray): + raise TypeError(f"pic should be Tensor or ndarray. Got {type(pic)}.") + + if pic.ndim == 2: + # if 2D image, add channel dimension (HWC) + pic = np.expand_dims(pic, 2) + if pic.ndim != 3: + raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.") + + if pic.shape[-1] > 4: + raise ValueError(f"pic should not have > 4 channels. Got {pic.shape[-1]} channels.") + + npimg = pic + + if np.issubdtype(npimg.dtype, np.floating) and mode != "F": + npimg = (npimg * 255).astype(np.uint8) + + if npimg.shape[2] == 1: + expected_mode = None + npimg = npimg[:, :, 0] + if npimg.dtype == np.uint8: + expected_mode = "L" + elif npimg.dtype == np.int16: + expected_mode = "I;16" if sys.byteorder == "little" else "I;16B" + elif npimg.dtype == np.int32: + expected_mode = "I" + elif npimg.dtype == np.float32: + expected_mode = "F" + if mode is not None and mode != expected_mode: + raise ValueError(f"Incorrect mode ({mode}) supplied for input type {np.dtype}. Should be {expected_mode}") + mode = expected_mode + + elif npimg.shape[2] == 2: + permitted_2_channel_modes = ["LA"] + if mode is not None and mode not in permitted_2_channel_modes: + raise ValueError(f"Only modes {permitted_2_channel_modes} are supported for 2D inputs") + + if mode is None and npimg.dtype == np.uint8: + mode = "LA" + + elif npimg.shape[2] == 4: + permitted_4_channel_modes = ["RGBA", "CMYK", "RGBX"] + if mode is not None and mode not in permitted_4_channel_modes: + raise ValueError(f"Only modes {permitted_4_channel_modes} are supported for 4D inputs") + + if mode is None and npimg.dtype == np.uint8: + mode = "RGBA" + else: + permitted_3_channel_modes = ["RGB", "YCbCr", "HSV"] + if mode is not None and mode not in permitted_3_channel_modes: + raise ValueError(f"Only modes {permitted_3_channel_modes} are supported for 3D inputs") + if mode is None and npimg.dtype == np.uint8: + mode = "RGB" + + if mode is None: + raise TypeError(f"Input type {npimg.dtype} is not supported") + + return _Image_fromarray(npimg, mode=mode) + + +def normalize(tensor: Tensor, mean: list[float], std: list[float], inplace: bool = False) -> Tensor: + """Normalize a float tensor image with mean and standard deviation. + This transform does not support PIL Image. + + .. note:: + This transform acts out of place by default, i.e., it does not mutates the input tensor. + + See :class:`~torchvision.transforms.Normalize` for more details. + + Args: + tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized. + mean (sequence): Sequence of means for each channel. + std (sequence): Sequence of standard deviations for each channel. + inplace(bool,optional): Bool to make this operation inplace. + + Returns: + Tensor: Normalized Tensor image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(normalize) + if not isinstance(tensor, torch.Tensor): + raise TypeError(f"img should be Tensor Image. Got {type(tensor)}") + + return F_t.normalize(tensor, mean=mean, std=std, inplace=inplace) + + +def _compute_resized_output_size( + image_size: tuple[int, int], + size: Optional[list[int]], + max_size: Optional[int] = None, + allow_size_none: bool = False, # only True in v2 +) -> list[int]: + h, w = image_size + short, long = (w, h) if w <= h else (h, w) + if size is None: + if not allow_size_none: + raise ValueError("This should never happen!!") + if not isinstance(max_size, int): + raise ValueError(f"max_size must be an integer when size is None, but got {max_size} instead.") + new_short, new_long = int(max_size * short / long), max_size + new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short) + elif len(size) == 1: # specified size only for the smallest edge + requested_new_short = size if isinstance(size, int) else size[0] + new_short, new_long = requested_new_short, int(requested_new_short * long / short) + + if max_size is not None: + if max_size <= requested_new_short: + raise ValueError( + f"max_size = {max_size} must be strictly greater than the requested " + f"size for the smaller edge size = {size}" + ) + if new_long > max_size: + new_short, new_long = int(max_size * new_short / new_long), max_size + + new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short) + else: # specified both h and w + new_w, new_h = size[1], size[0] + return [new_h, new_w] + + +def resize( + img: Tensor, + size: list[int], + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> Tensor: + r"""Resize the input image to the given size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + img (PIL Image or Tensor): Image to be resized. + size (sequence or int): Desired output size. If size is a sequence like + (h, w), the output size will be matched to this. If size is an int, + the smaller edge of the image will be matched to this number maintaining + the aspect ratio. i.e, if height > width, then image will be rescaled to + :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`. + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. + Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, + ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are + supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + max_size (int, optional): The maximum allowed for the longer edge of + the resized image. If the longer edge of the image is greater + than ``max_size`` after being resized according to ``size``, + ``size`` will be overruled so that the longer edge is equal to + ``max_size``. + As a result, the smaller edge may be shorter than ``size``. This + is only supported if ``size`` is an int (or a sequence of length + 1 in torchscript mode). + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + + Returns: + PIL Image or Tensor: Resized image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(resize) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if isinstance(size, (list, tuple)): + if len(size) not in [1, 2]: + raise ValueError( + f"Size must be an int or a 1 or 2 element tuple/list, not a {len(size)} element tuple/list" + ) + if max_size is not None and len(size) != 1: + raise ValueError( + "max_size should only be passed if size specifies the length of the smaller edge, " + "i.e. size should be an int or a sequence of length 1 in torchscript mode." + ) + + _, image_height, image_width = get_dimensions(img) + if isinstance(size, int): + size = [size] + output_size = _compute_resized_output_size((image_height, image_width), size, max_size) + + if [image_height, image_width] == output_size: + return img + + if not isinstance(img, torch.Tensor): + if antialias is False: + warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.") + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.resize(img, size=output_size, interpolation=pil_interpolation) + + return F_t.resize(img, size=output_size, interpolation=interpolation.value, antialias=antialias) + + +def pad(img: Tensor, padding: list[int], fill: Union[int, float] = 0, padding_mode: str = "constant") -> Tensor: + r"""Pad the given image on all sides with the given "pad" value. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, + at most 3 leading dimensions for mode edge, + and an arbitrary number of leading dimensions for mode constant + + Args: + img (PIL Image or Tensor): Image to be padded. + padding (int or sequence): Padding on each border. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + fill (number or tuple): Pixel fill value for constant fill. Default is 0. + If a tuple of length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + Only number is supported for torch Tensor. + Only int or tuple value is supported for PIL Image. + padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + + Returns: + PIL Image or Tensor: Padded image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(pad) + if not isinstance(img, torch.Tensor): + return F_pil.pad(img, padding=padding, fill=fill, padding_mode=padding_mode) + + return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode) + + +def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: + """Crop the given image at specified location and output size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + If image size is smaller than output size along any edge, image is padded with 0 and then cropped. + + Args: + img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + + Returns: + PIL Image or Tensor: Cropped image. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(crop) + if not isinstance(img, torch.Tensor): + return F_pil.crop(img, top, left, height, width) + + return F_t.crop(img, top, left, height, width) + + +def center_crop(img: Tensor, output_size: list[int]) -> Tensor: + """Crops the given image at the center. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. + + Args: + img (PIL Image or Tensor): Image to be cropped. + output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int, + it is used for both directions. + + Returns: + PIL Image or Tensor: Cropped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(center_crop) + if isinstance(output_size, numbers.Number): + output_size = (int(output_size), int(output_size)) + elif isinstance(output_size, (tuple, list)) and len(output_size) == 1: + output_size = (output_size[0], output_size[0]) + + _, image_height, image_width = get_dimensions(img) + crop_height, crop_width = output_size + + if crop_width > image_width or crop_height > image_height: + padding_ltrb = [ + (crop_width - image_width) // 2 if crop_width > image_width else 0, + (crop_height - image_height) // 2 if crop_height > image_height else 0, + (crop_width - image_width + 1) // 2 if crop_width > image_width else 0, + (crop_height - image_height + 1) // 2 if crop_height > image_height else 0, + ] + img = pad(img, padding_ltrb, fill=0) # PIL uses fill value 0 + _, image_height, image_width = get_dimensions(img) + if crop_width == image_width and crop_height == image_height: + return img + + crop_top = int(round((image_height - crop_height) / 2.0)) + crop_left = int(round((image_width - crop_width) / 2.0)) + return crop(img, crop_top, crop_left, crop_height, crop_width) + + +def resized_crop( + img: Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> Tensor: + """Crop the given image and resize it to desired size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. + + Args: + img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + size (sequence or int): Desired output size. Same semantics as ``resize``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. + Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, + ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are + supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + Returns: + PIL Image or Tensor: Cropped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(resized_crop) + img = crop(img, top, left, height, width) + img = resize(img, size, interpolation, antialias=antialias) + return img + + +def hflip(img: Tensor) -> Tensor: + """Horizontally flip the given image. + + Args: + img (PIL Image or Tensor): Image to be flipped. If img + is a Tensor, it is expected to be in [..., H, W] format, + where ... means it can have an arbitrary number of leading + dimensions. + + Returns: + PIL Image or Tensor: Horizontally flipped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(hflip) + if not isinstance(img, torch.Tensor): + return F_pil.hflip(img) + + return F_t.hflip(img) + + +def _get_perspective_coeffs(startpoints: list[list[int]], endpoints: list[list[int]]) -> list[float]: + """Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms. + + In Perspective Transform each pixel (x, y) in the original image gets transformed as, + (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) ) + + Args: + startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. + endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. + + Returns: + octuple (a, b, c, d, e, f, g, h) for transforming each pixel. + """ + if len(startpoints) != 4 or len(endpoints) != 4: + raise ValueError( + f"Please provide exactly four corners, got {len(startpoints)} startpoints and {len(endpoints)} endpoints." + ) + a_matrix = torch.zeros(2 * len(startpoints), 8, dtype=torch.float64) + + for i, (p1, p2) in enumerate(zip(endpoints, startpoints)): + a_matrix[2 * i, :] = torch.tensor([p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1]]) + a_matrix[2 * i + 1, :] = torch.tensor([0, 0, 0, p1[0], p1[1], 1, -p2[1] * p1[0], -p2[1] * p1[1]]) + + b_matrix = torch.tensor(startpoints, dtype=torch.float64).view(8) + # do least squares in double precision to prevent numerical issues + res = torch.linalg.lstsq(a_matrix, b_matrix, driver="gels").solution.to(torch.float32) + + output: list[float] = res.tolist() + return output + + +def perspective( + img: Tensor, + startpoints: list[list[int]], + endpoints: list[list[int]], + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + fill: Optional[list[float]] = None, +) -> Tensor: + """Perform perspective transform of the given image. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + img (PIL Image or Tensor): Image to be transformed. + startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. + endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + + .. note:: + In torchscript mode single int/float value is not supported, please use a sequence + of length 1: ``[value, ]``. + + Returns: + PIL Image or Tensor: transformed Image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(perspective) + + coeffs = _get_perspective_coeffs(startpoints, endpoints) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if not isinstance(img, torch.Tensor): + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.perspective(img, coeffs, interpolation=pil_interpolation, fill=fill) + + return F_t.perspective(img, coeffs, interpolation=interpolation.value, fill=fill) + + +def vflip(img: Tensor) -> Tensor: + """Vertically flip the given image. + + Args: + img (PIL Image or Tensor): Image to be flipped. If img + is a Tensor, it is expected to be in [..., H, W] format, + where ... means it can have an arbitrary number of leading + dimensions. + + Returns: + PIL Image or Tensor: Vertically flipped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(vflip) + if not isinstance(img, torch.Tensor): + return F_pil.vflip(img) + + return F_t.vflip(img) + + +def five_crop(img: Tensor, size: list[int]) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: + """Crop the given image into four corners and the central crop. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + .. Note:: + This transform returns a tuple of images and there may be a + mismatch in the number of inputs and targets your ``Dataset`` returns. + + Args: + img (PIL Image or Tensor): Image to be cropped. + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + Returns: + tuple: tuple (tl, tr, bl, br, center) + Corresponding top left, top right, bottom left, bottom right and center crop. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(five_crop) + if isinstance(size, numbers.Number): + size = (int(size), int(size)) + elif isinstance(size, (tuple, list)) and len(size) == 1: + size = (size[0], size[0]) + + if len(size) != 2: + raise ValueError("Please provide only two dimensions (h, w) for size.") + + _, image_height, image_width = get_dimensions(img) + crop_height, crop_width = size + if crop_width > image_width or crop_height > image_height: + msg = "Requested crop size {} is bigger than input size {}" + raise ValueError(msg.format(size, (image_height, image_width))) + + tl = crop(img, 0, 0, crop_height, crop_width) + tr = crop(img, 0, image_width - crop_width, crop_height, crop_width) + bl = crop(img, image_height - crop_height, 0, crop_height, crop_width) + br = crop(img, image_height - crop_height, image_width - crop_width, crop_height, crop_width) + + center = center_crop(img, [crop_height, crop_width]) + + return tl, tr, bl, br, center + + +def ten_crop( + img: Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: + """Generate ten cropped images from the given image. + Crop the given image into four corners and the central crop plus the + flipped version of these (horizontal flipping is used by default). + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + .. Note:: + This transform returns a tuple of images and there may be a + mismatch in the number of inputs and targets your ``Dataset`` returns. + + Args: + img (PIL Image or Tensor): Image to be cropped. + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + vertical_flip (bool): Use vertical flipping instead of horizontal + + Returns: + tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip) + Corresponding top left, top right, bottom left, bottom right and + center crop and same for the flipped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(ten_crop) + if isinstance(size, numbers.Number): + size = (int(size), int(size)) + elif isinstance(size, (tuple, list)) and len(size) == 1: + size = (size[0], size[0]) + + if len(size) != 2: + raise ValueError("Please provide only two dimensions (h, w) for size.") + + first_five = five_crop(img, size) + + if vertical_flip: + img = vflip(img) + else: + img = hflip(img) + + second_five = five_crop(img, size) + return first_five + second_five + + +def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor: + """Adjust brightness of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + brightness_factor (float): How much to adjust the brightness. Can be + any non-negative number. 0 gives a black image, 1 gives the + original image while 2 increases the brightness by a factor of 2. + + Returns: + PIL Image or Tensor: Brightness adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_brightness) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_brightness(img, brightness_factor) + + return F_t.adjust_brightness(img, brightness_factor) + + +def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor: + """Adjust contrast of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + contrast_factor (float): How much to adjust the contrast. Can be any + non-negative number. 0 gives a solid gray image, 1 gives the + original image while 2 increases the contrast by a factor of 2. + + Returns: + PIL Image or Tensor: Contrast adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_contrast) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_contrast(img, contrast_factor) + + return F_t.adjust_contrast(img, contrast_factor) + + +def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor: + """Adjust color saturation of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + saturation_factor (float): How much to adjust the saturation. 0 will + give a black and white image, 1 will give the original image while + 2 will enhance the saturation by a factor of 2. + + Returns: + PIL Image or Tensor: Saturation adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_saturation) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_saturation(img, saturation_factor) + + return F_t.adjust_saturation(img, saturation_factor) + + +def adjust_hue(img: Tensor, hue_factor: float) -> Tensor: + """Adjust hue of an image. + + The image hue is adjusted by converting the image to HSV and + cyclically shifting the intensities in the hue channel (H). + The image is then converted back to original image mode. + + `hue_factor` is the amount of shift in H channel and must be in the + interval `[-0.5, 0.5]`. + + See `Hue`_ for more details. + + .. _Hue: https://en.wikipedia.org/wiki/Hue + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image mode "1", "I", "F" and modes with transparency (alpha channel) are not supported. + Note: the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + hue_factor (float): How much to shift the hue channel. Should be in + [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in + HSV space in positive and negative direction respectively. + 0 means no shift. Therefore, both -0.5 and 0.5 will give an image + with complementary colors while 0 gives the original image. + + Returns: + PIL Image or Tensor: Hue adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_hue) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_hue(img, hue_factor) + + return F_t.adjust_hue(img, hue_factor) + + +def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor: + r"""Perform gamma correction on an image. + + Also known as Power Law Transform. Intensities in RGB mode are adjusted + based on the following equation: + + .. math:: + I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma} + + See `Gamma Correction`_ for more details. + + .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction + + Args: + img (PIL Image or Tensor): PIL Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, modes with transparency (alpha channel) are not supported. + gamma (float): Non negative real number, same as :math:`\gamma` in the equation. + gamma larger than 1 make the shadows darker, + while gamma smaller than 1 make dark regions lighter. + gain (float): The constant multiplier. + Returns: + PIL Image or Tensor: Gamma correction adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_gamma) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_gamma(img, gamma, gain) + + return F_t.adjust_gamma(img, gamma, gain) + + +def _get_inverse_affine_matrix( + center: list[float], angle: float, translate: list[float], scale: float, shear: list[float], inverted: bool = True +) -> list[float]: + # Helper method to compute inverse matrix for affine transformation + + # Pillow requires inverse affine transformation matrix: + # Affine matrix is : M = T * C * RotateScaleShear * C^-1 + # + # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] + # C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1] + # RotateScaleShear is rotation with scale and shear matrix + # + # RotateScaleShear(a, s, (sx, sy)) = + # = R(a) * S(s) * SHy(sy) * SHx(sx) + # = [ s*cos(a - sy)/cos(sy), s*(-cos(a - sy)*tan(sx)/cos(sy) - sin(a)), 0 ] + # [ s*sin(a - sy)/cos(sy), s*(-sin(a - sy)*tan(sx)/cos(sy) + cos(a)), 0 ] + # [ 0 , 0 , 1 ] + # where R is a rotation matrix, S is a scaling matrix, and SHx and SHy are the shears: + # SHx(s) = [1, -tan(s)] and SHy(s) = [1 , 0] + # [0, 1 ] [-tan(s), 1] + # + # Thus, the inverse is M^-1 = C * RotateScaleShear^-1 * C^-1 * T^-1 + + rot = math.radians(angle) + sx = math.radians(shear[0]) + sy = math.radians(shear[1]) + + cx, cy = center + tx, ty = translate + + # RSS without scaling + a = math.cos(rot - sy) / math.cos(sy) + b = -math.cos(rot - sy) * math.tan(sx) / math.cos(sy) - math.sin(rot) + c = math.sin(rot - sy) / math.cos(sy) + d = -math.sin(rot - sy) * math.tan(sx) / math.cos(sy) + math.cos(rot) + + if inverted: + # Inverted rotation matrix with scale and shear + # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1 + matrix = [d, -b, 0.0, -c, a, 0.0] + matrix = [x / scale for x in matrix] + # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1 + matrix[2] += matrix[0] * (-cx - tx) + matrix[1] * (-cy - ty) + matrix[5] += matrix[3] * (-cx - tx) + matrix[4] * (-cy - ty) + # Apply center translation: C * RSS^-1 * C^-1 * T^-1 + matrix[2] += cx + matrix[5] += cy + else: + matrix = [a, b, 0.0, c, d, 0.0] + matrix = [x * scale for x in matrix] + # Apply inverse of center translation: RSS * C^-1 + matrix[2] += matrix[0] * (-cx) + matrix[1] * (-cy) + matrix[5] += matrix[3] * (-cx) + matrix[4] * (-cy) + # Apply translation and center : T * C * RSS * C^-1 + matrix[2] += cx + tx + matrix[5] += cy + ty + + return matrix + + +def rotate( + img: Tensor, + angle: float, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[int]] = None, + fill: Optional[list[float]] = None, +) -> Tensor: + """Rotate the image by angle. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + img (PIL Image or Tensor): image to be rotated. + angle (number): rotation angle value in degrees, counter-clockwise. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + expand (bool, optional): Optional expansion flag. + If true, expands the output image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (sequence, optional): Optional center of rotation. Origin is the upper left corner. + Default is the center of the image. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + + .. note:: + In torchscript mode single int/float value is not supported, please use a sequence + of length 1: ``[value, ]``. + Returns: + PIL Image or Tensor: Rotated image. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(rotate) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if not isinstance(angle, (int, float)): + raise TypeError("Argument angle should be int or float") + + if center is not None and not isinstance(center, (list, tuple)): + raise TypeError("Argument center should be a sequence") + + if not isinstance(img, torch.Tensor): + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.rotate(img, angle=angle, interpolation=pil_interpolation, expand=expand, center=center, fill=fill) + + center_f = [0.0, 0.0] + if center is not None: + _, height, width = get_dimensions(img) + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])] + + # due to current incoherence of rotation angle direction between affine and rotate implementations + # we need to set -angle. + matrix = _get_inverse_affine_matrix(center_f, -angle, [0.0, 0.0], 1.0, [0.0, 0.0]) + return F_t.rotate(img, matrix=matrix, interpolation=interpolation.value, expand=expand, fill=fill) + + +def affine( + img: Tensor, + angle: float, + translate: list[int], + scale: float, + shear: list[float], + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + center: Optional[list[int]] = None, +) -> Tensor: + """Apply affine transformation on the image keeping image center invariant. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + img (PIL Image or Tensor): image to transform. + angle (number): rotation angle in degrees between -180 and 180, clockwise direction. + translate (sequence of integers): horizontal and vertical translations (post-rotation translation) + scale (float): overall scale + shear (float or sequence): shear angle value in degrees between -180 to 180, clockwise direction. + If a sequence is specified, the first value corresponds to a shear parallel to the x-axis, while + the second value corresponds to a shear parallel to the y-axis. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + + .. note:: + In torchscript mode single int/float value is not supported, please use a sequence + of length 1: ``[value, ]``. + center (sequence, optional): Optional center of rotation. Origin is the upper left corner. + Default is the center of the image. + + Returns: + PIL Image or Tensor: Transformed image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(affine) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if not isinstance(angle, (int, float)): + raise TypeError("Argument angle should be int or float") + + if not isinstance(translate, (list, tuple)): + raise TypeError("Argument translate should be a sequence") + + if len(translate) != 2: + raise ValueError("Argument translate should be a sequence of length 2") + + if scale <= 0.0: + raise ValueError("Argument scale should be positive") + + if not isinstance(shear, (numbers.Number, (list, tuple))): + raise TypeError("Shear should be either a single value or a sequence of two values") + + if isinstance(angle, int): + angle = float(angle) + + if isinstance(translate, tuple): + translate = list(translate) + + if isinstance(shear, numbers.Number): + shear = [shear, 0.0] + + if isinstance(shear, tuple): + shear = list(shear) + + if len(shear) == 1: + shear = [shear[0], shear[0]] + + if len(shear) != 2: + raise ValueError(f"Shear should be a sequence containing two values. Got {shear}") + + if center is not None and not isinstance(center, (list, tuple)): + raise TypeError("Argument center should be a sequence") + + _, height, width = get_dimensions(img) + if not isinstance(img, torch.Tensor): + # center = (width * 0.5 + 0.5, height * 0.5 + 0.5) + # it is visually better to estimate the center without 0.5 offset + # otherwise image rotated by 90 degrees is shifted vs output image of torch.rot90 or F_t.affine + if center is None: + center = [width * 0.5, height * 0.5] + matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.affine(img, matrix=matrix, interpolation=pil_interpolation, fill=fill) + + center_f = [0.0, 0.0] + if center is not None: + _, height, width = get_dimensions(img) + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])] + + translate_f = [1.0 * t for t in translate] + matrix = _get_inverse_affine_matrix(center_f, angle, translate_f, scale, shear) + return F_t.affine(img, matrix=matrix, interpolation=interpolation.value, fill=fill) + + +# Looks like to_grayscale() is a stand-alone functional that is never called +# from the transform classes. Perhaps it's still here for BC? I can't be +# bothered to dig. +@torch.jit.unused +def to_grayscale(img, num_output_channels=1): + """Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image. + This transform does not support torch Tensor. + + Args: + img (PIL Image): PIL Image to be converted to grayscale. + num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default is 1. + + Returns: + PIL Image: Grayscale version of the image. + + - if num_output_channels = 1 : returned image is single channel + - if num_output_channels = 3 : returned image is 3 channel with r = g = b + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(to_grayscale) + if isinstance(img, Image.Image): + return F_pil.to_grayscale(img, num_output_channels) + + raise TypeError("Input should be PIL Image") + + +def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor: + """Convert RGB image to grayscale version of image. + If the image is torch Tensor, it is expected + to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions + + Note: + Please, note that this method supports only RGB images as input. For inputs in other color spaces, + please, consider using :meth:`~torchvision.transforms.functional.to_grayscale` with PIL Image. + + Args: + img (PIL Image or Tensor): RGB Image to be converted to grayscale. + num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1. + + Returns: + PIL Image or Tensor: Grayscale version of the image. + + - if num_output_channels = 1 : returned image is single channel + - if num_output_channels = 3 : returned image is 3 channel with r = g = b + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(rgb_to_grayscale) + if not isinstance(img, torch.Tensor): + return F_pil.to_grayscale(img, num_output_channels) + + return F_t.rgb_to_grayscale(img, num_output_channels) + + +def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor: + """Erase the input Tensor Image with given value. + This transform does not support PIL Image. + + Args: + img (Tensor Image): Tensor image of size (C, H, W) to be erased + i (int): i in (i,j) i.e coordinates of the upper left corner. + j (int): j in (i,j) i.e coordinates of the upper left corner. + h (int): Height of the erased region. + w (int): Width of the erased region. + v: Erasing value. + inplace(bool, optional): For in-place operations. By default, is set False. + + Returns: + Tensor Image: Erased image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(erase) + if not isinstance(img, torch.Tensor): + raise TypeError(f"img should be Tensor Image. Got {type(img)}") + + return F_t.erase(img, i, j, h, w, v, inplace=inplace) + + +def gaussian_blur(img: Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None) -> Tensor: + """Performs Gaussian blurring on the image by given kernel + + The convolution will be using reflection padding corresponding to the kernel size, to maintain the input shape. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means at most one leading dimension. + + Args: + img (PIL Image or Tensor): Image to be blurred + kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers + like ``(kx, ky)`` or a single integer for square kernels. + + .. note:: + In torchscript mode kernel_size as single int is not supported, use a sequence of + length 1: ``[ksize, ]``. + sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a + sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the + same sigma in both X/Y directions. If None, then it is computed using + ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``. + Default, None. + + .. note:: + In torchscript mode sigma as single float is + not supported, use a sequence of length 1: ``[sigma, ]``. + + Returns: + PIL Image or Tensor: Gaussian Blurred version of the image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(gaussian_blur) + if not isinstance(kernel_size, (int, list, tuple)): + raise TypeError(f"kernel_size should be int or a sequence of integers. Got {type(kernel_size)}") + if isinstance(kernel_size, int): + kernel_size = [kernel_size, kernel_size] + if len(kernel_size) != 2: + raise ValueError(f"If kernel_size is a sequence its length should be 2. Got {len(kernel_size)}") + for ksize in kernel_size: + if ksize % 2 == 0 or ksize < 0: + raise ValueError(f"kernel_size should have odd and positive integers. Got {kernel_size}") + + if sigma is None: + sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size] + + if sigma is not None and not isinstance(sigma, (int, float, list, tuple)): + raise TypeError(f"sigma should be either float or sequence of floats. Got {type(sigma)}") + if isinstance(sigma, (int, float)): + sigma = [float(sigma), float(sigma)] + if isinstance(sigma, (list, tuple)) and len(sigma) == 1: + sigma = [sigma[0], sigma[0]] + if len(sigma) != 2: + raise ValueError(f"If sigma is a sequence, its length should be 2. Got {len(sigma)}") + for s in sigma: + if s <= 0.0: + raise ValueError(f"sigma should have positive values. Got {sigma}") + + t_img = img + if not isinstance(img, torch.Tensor): + if not F_pil._is_pil_image(img): + raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}") + + t_img = pil_to_tensor(img) + + output = F_t.gaussian_blur(t_img, kernel_size, sigma) + + if not isinstance(img, torch.Tensor): + output = to_pil_image(output, mode=img.mode) + return output + + +def invert(img: Tensor) -> Tensor: + """Invert the colors of an RGB/grayscale image. + + Args: + img (PIL Image or Tensor): Image to have its colors inverted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Returns: + PIL Image or Tensor: Color inverted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(invert) + if not isinstance(img, torch.Tensor): + return F_pil.invert(img) + + return F_t.invert(img) + + +def posterize(img: Tensor, bits: int) -> Tensor: + """Posterize an image by reducing the number of bits for each color channel. + + Args: + img (PIL Image or Tensor): Image to have its colors posterized. + If img is torch Tensor, it should be of type torch.uint8, and + it is expected to be in [..., 1 or 3, H, W] format, where ... means + it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + bits (int): The number of bits to keep for each channel (0-8). + Returns: + PIL Image or Tensor: Posterized image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(posterize) + if not (0 <= bits <= 8): + raise ValueError(f"The number if bits should be between 0 and 8. Got {bits}") + + if not isinstance(img, torch.Tensor): + return F_pil.posterize(img, bits) + + return F_t.posterize(img, bits) + + +def solarize(img: Tensor, threshold: float) -> Tensor: + """Solarize an RGB/grayscale image by inverting all pixel values above a threshold. + + Args: + img (PIL Image or Tensor): Image to have its colors inverted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + threshold (float): All pixels equal or above this value are inverted. + Returns: + PIL Image or Tensor: Solarized image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(solarize) + if not isinstance(img, torch.Tensor): + return F_pil.solarize(img, threshold) + + return F_t.solarize(img, threshold) + + +def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor: + """Adjust the sharpness of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + sharpness_factor (float): How much to adjust the sharpness. Can be + any non-negative number. 0 gives a blurred image, 1 gives the + original image while 2 increases the sharpness by a factor of 2. + + Returns: + PIL Image or Tensor: Sharpness adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_sharpness) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_sharpness(img, sharpness_factor) + + return F_t.adjust_sharpness(img, sharpness_factor) + + +def autocontrast(img: Tensor) -> Tensor: + """Maximize contrast of an image by remapping its + pixels per channel so that the lowest becomes black and the lightest + becomes white. + + Args: + img (PIL Image or Tensor): Image on which autocontrast is applied. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Returns: + PIL Image or Tensor: An image that was autocontrasted. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(autocontrast) + if not isinstance(img, torch.Tensor): + return F_pil.autocontrast(img) + + return F_t.autocontrast(img) + + +def equalize(img: Tensor) -> Tensor: + """Equalize the histogram of an image by applying + a non-linear mapping to the input in order to create a uniform + distribution of grayscale values in the output. + + Args: + img (PIL Image or Tensor): Image on which equalize is applied. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + The tensor dtype must be ``torch.uint8`` and values are expected to be in ``[0, 255]``. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + + Returns: + PIL Image or Tensor: An image that was equalized. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(equalize) + if not isinstance(img, torch.Tensor): + return F_pil.equalize(img) + + return F_t.equalize(img) + + +def elastic_transform( + img: Tensor, + displacement: Tensor, + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + fill: Optional[list[float]] = None, +) -> Tensor: + """Transform a tensor image with elastic transformations. + Given alpha and sigma, it will generate displacement + vectors for all pixels based on random offsets. Alpha controls the strength + and sigma controls the smoothness of the displacements. + The displacements are added to an identity grid and the resulting grid is + used to grid_sample from the image. + + Applications: + Randomly transforms the morphology of objects in images and produces a + see-through-water-like effect. + + Args: + img (PIL Image or Tensor): Image on which elastic_transform is applied. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + displacement (Tensor): The displacement field. Expected shape is [1, H, W, 2]. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. + Default is ``InterpolationMode.BILINEAR``. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or str or tuple): Pixel fill value for constant fill. Default is 0. + If a tuple of length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(elastic_transform) + # Backward compatibility with integer value + if isinstance(interpolation, int): + warnings.warn( + "Argument interpolation should be of type InterpolationMode instead of int. " + "Please, use InterpolationMode enum." + ) + interpolation = _interpolation_modes_from_int(interpolation) + + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + + t_img = img + if not isinstance(img, torch.Tensor): + if not F_pil._is_pil_image(img): + raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}") + t_img = pil_to_tensor(img) + + shape = t_img.shape + shape = (1,) + shape[-2:] + (2,) + if shape != displacement.shape: + raise ValueError(f"Argument displacement shape should be {shape}, but given {displacement.shape}") + + # TODO: if image shape is [N1, N2, ..., C, H, W] and + # displacement is [1, H, W, 2] we need to reshape input image + # such grid_sampler takes internal code for 4D input + + output = F_t.elastic_transform( + t_img, + displacement, + interpolation=interpolation.value, + fill=fill, + ) + + if not isinstance(img, torch.Tensor): + output = to_pil_image(output, mode=img.mode) + return output diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/transforms.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..c6595a3402ee970e8751e1ecb2068db5b91805c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/transforms.py @@ -0,0 +1,2161 @@ +import math +import numbers +import random +import warnings +from collections.abc import Sequence +from typing import Optional, Union + +import torch +from torch import Tensor + +try: + import accimage +except ImportError: + accimage = None + +from ..utils import _log_api_usage_once +from . import functional as F +from .functional import _interpolation_modes_from_int, InterpolationMode + +__all__ = [ + "Compose", + "ToTensor", + "PILToTensor", + "ConvertImageDtype", + "ToPILImage", + "Normalize", + "Resize", + "CenterCrop", + "Pad", + "Lambda", + "RandomApply", + "RandomChoice", + "RandomOrder", + "RandomCrop", + "RandomHorizontalFlip", + "RandomVerticalFlip", + "RandomResizedCrop", + "FiveCrop", + "TenCrop", + "LinearTransformation", + "ColorJitter", + "RandomRotation", + "RandomAffine", + "Grayscale", + "RandomGrayscale", + "RandomPerspective", + "RandomErasing", + "GaussianBlur", + "InterpolationMode", + "RandomInvert", + "RandomPosterize", + "RandomSolarize", + "RandomAdjustSharpness", + "RandomAutocontrast", + "RandomEqualize", + "ElasticTransform", +] + + +class Compose: + """Composes several transforms together. This transform does not support torchscript. + Please, see the note below. + + Args: + transforms (list of ``Transform`` objects): list of transforms to compose. + + Example: + >>> transforms.Compose([ + >>> transforms.CenterCrop(10), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> ]) + + .. note:: + In order to script the transformations, please use ``torch.nn.Sequential`` as below. + + >>> transforms = torch.nn.Sequential( + >>> transforms.CenterCrop(10), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> ) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + """ + + def __init__(self, transforms): + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(self) + self.transforms = transforms + + def __call__(self, img): + for t in self.transforms: + img = t(img) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + for t in self.transforms: + format_string += "\n" + format_string += f" {t}" + format_string += "\n)" + return format_string + + +class ToTensor: + """Convert a PIL Image or ndarray to tensor and scale the values accordingly. + + This transform does not support torchscript. + + Converts a PIL Image or numpy.ndarray (H x W x C) in the range + [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] + if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1) + or if the numpy.ndarray has dtype = np.uint8 + + In the other cases, tensors are returned without scaling. + + .. note:: + Because the input image is scaled to [0.0, 1.0], this transformation should not be used when + transforming target image masks. See the `references`_ for implementing the transforms for image masks. + + .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation + """ + + def __init__(self) -> None: + _log_api_usage_once(self) + + def __call__(self, pic): + """ + Args: + pic (PIL Image or numpy.ndarray): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + return F.to_tensor(pic) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + +class PILToTensor: + """Convert a PIL Image to a tensor of the same type - this does not scale values. + + This transform does not support torchscript. + + Convert a PIL Image with H height, W width, and C channels to a Tensor of shape (C x H x W). + + Example: + >>> from PIL import Image + >>> import torchvision.transforms as T + >>> img = Image.new("RGB", (320, 240)) # size (W=320, H=240) + >>> tensor = T.PILToTensor()(img) + >>> print(tensor.shape) + torch.Size([3, 240, 320]) + """ + + def __init__(self) -> None: + _log_api_usage_once(self) + + def __call__(self, pic): + """ + .. note:: + + A deep copy of the underlying array is performed. + + Args: + pic (PIL Image): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + return F.pil_to_tensor(pic) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + +class ConvertImageDtype(torch.nn.Module): + """Convert a tensor image to the given ``dtype`` and scale the values accordingly. + + This function does not support PIL Image. + + Args: + dtype (torch.dtype): Desired data type of the output + + .. note:: + + When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. + If converted back and forth, this mismatch has no effect. + + Raises: + RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as + well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to + overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range + of the integer ``dtype``. + """ + + def __init__(self, dtype: torch.dtype) -> None: + super().__init__() + _log_api_usage_once(self) + self.dtype = dtype + + def forward(self, image): + return F.convert_image_dtype(image, self.dtype) + + +class ToPILImage: + """Convert a tensor or an ndarray to PIL Image + + This transform does not support torchscript. + + Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape + H x W x C to a PIL Image while adjusting the value range depending on the ``mode``. + + Args: + mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). + If ``mode`` is ``None`` (default) there are some assumptions made about the input data: + + - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``. + - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``. + - If the input has 2 channels, the ``mode`` is assumed to be ``LA``. + - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, ``short``). + + .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes + """ + + def __init__(self, mode=None): + _log_api_usage_once(self) + self.mode = mode + + def __call__(self, pic): + """ + Args: + pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. + + Returns: + PIL Image: Image converted to PIL Image. + + """ + return F.to_pil_image(pic, self.mode) + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + if self.mode is not None: + format_string += f"mode={self.mode}" + format_string += ")" + return format_string + + +class Normalize(torch.nn.Module): + """Normalize a tensor image with mean and standard deviation. + This transform does not support PIL Image. + Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n`` + channels, this transform will normalize each channel of the input + ``torch.*Tensor`` i.e., + ``output[channel] = (input[channel] - mean[channel]) / std[channel]`` + + .. note:: + This transform acts out of place, i.e., it does not mutate the input tensor. + + Args: + mean (sequence): Sequence of means for each channel. + std (sequence): Sequence of standard deviations for each channel. + inplace(bool,optional): Bool to make this operation in-place. + + """ + + def __init__(self, mean, std, inplace=False): + super().__init__() + _log_api_usage_once(self) + self.mean = mean + self.std = std + self.inplace = inplace + + def forward(self, tensor: Tensor) -> Tensor: + """ + Args: + tensor (Tensor): Tensor image to be normalized. + + Returns: + Tensor: Normalized Tensor image. + """ + return F.normalize(tensor, self.mean, self.std, self.inplace) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(mean={self.mean}, std={self.std})" + + +class Resize(torch.nn.Module): + """Resize the input image to the given size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means a maximum of two leading dimensions + + Args: + size (sequence or int): Desired output size. If size is a sequence like + (h, w), output size will be matched to this. If size is an int, + smaller edge of the image will be matched to this number. + i.e, if height > width, then image will be rescaled to + (size * height / width, size). + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + max_size (int, optional): The maximum allowed for the longer edge of + the resized image. If the longer edge of the image is greater + than ``max_size`` after being resized according to ``size``, + ``size`` will be overruled so that the longer edge is equal to + ``max_size``. + As a result, the smaller edge may be shorter than ``size``. This + is only supported if ``size`` is an int (or a sequence of length + 1 in torchscript mode). + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__(self, size, interpolation=InterpolationMode.BILINEAR, max_size=None, antialias=True): + super().__init__() + _log_api_usage_once(self) + if not isinstance(size, (int, Sequence)): + raise TypeError(f"Size should be int or sequence. Got {type(size)}") + if isinstance(size, Sequence) and len(size) not in (1, 2): + raise ValueError("If size is a sequence, it should have 1 or 2 values") + self.size = size + self.max_size = max_size + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.interpolation = interpolation + self.antialias = antialias + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be scaled. + + Returns: + PIL Image or Tensor: Rescaled image. + """ + return F.resize(img, self.size, self.interpolation, self.max_size, self.antialias) + + def __repr__(self) -> str: + detail = f"(size={self.size}, interpolation={self.interpolation.value}, max_size={self.max_size}, antialias={self.antialias})" + return f"{self.__class__.__name__}{detail}" + + +class CenterCrop(torch.nn.Module): + """Crops the given image at the center. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + """ + + def __init__(self, size): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + PIL Image or Tensor: Cropped image. + """ + return F.center_crop(img, self.size) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size})" + + +class Pad(torch.nn.Module): + """Pad the given image on all sides with the given "pad" value. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, + at most 3 leading dimensions for mode edge, + and an arbitrary number of leading dimensions for mode constant + + Args: + padding (int or sequence): Padding on each border. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + Only number is supported for torch Tensor. + Only int or tuple value is supported for PIL Image. + padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + def __init__(self, padding, fill=0, padding_mode="constant"): + super().__init__() + _log_api_usage_once(self) + if not isinstance(padding, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate padding arg") + + if not isinstance(fill, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate fill arg") + + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + if isinstance(padding, Sequence) and len(padding) not in [1, 2, 4]: + raise ValueError( + f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple" + ) + + self.padding = padding + self.fill = fill + self.padding_mode = padding_mode + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be padded. + + Returns: + PIL Image or Tensor: Padded image. + """ + return F.pad(img, self.padding, self.fill, self.padding_mode) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(padding={self.padding}, fill={self.fill}, padding_mode={self.padding_mode})" + + +class Lambda: + """Apply a user-defined lambda as a transform. This transform does not support torchscript. + + Args: + lambd (function): Lambda/function to be used for transform. + """ + + def __init__(self, lambd): + _log_api_usage_once(self) + if not callable(lambd): + raise TypeError(f"Argument lambd should be callable, got {repr(type(lambd).__name__)}") + self.lambd = lambd + + def __call__(self, img): + return self.lambd(img) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + +class RandomTransforms: + """Base class for a list of transformations with randomness + + Args: + transforms (sequence): list of transformations + """ + + def __init__(self, transforms): + _log_api_usage_once(self) + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence") + self.transforms = transforms + + def __call__(self, *args, **kwargs): + raise NotImplementedError() + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + for t in self.transforms: + format_string += "\n" + format_string += f" {t}" + format_string += "\n)" + return format_string + + +class RandomApply(torch.nn.Module): + """Apply randomly a list of transformations with a given probability. + + .. note:: + In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of + transforms as shown below: + + >>> transforms = transforms.RandomApply(torch.nn.ModuleList([ + >>> transforms.ColorJitter(), + >>> ]), p=0.3) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + p (float): probability + """ + + def __init__(self, transforms, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.transforms = transforms + self.p = p + + def forward(self, img): + if self.p < torch.rand(1): + return img + for t in self.transforms: + img = t(img) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n p={self.p}" + for t in self.transforms: + format_string += "\n" + format_string += f" {t}" + format_string += "\n)" + return format_string + + +class RandomOrder(RandomTransforms): + """Apply a list of transformations in a random order. This transform does not support torchscript.""" + + def __call__(self, img): + order = list(range(len(self.transforms))) + random.shuffle(order) + for i in order: + img = self.transforms[i](img) + return img + + +class RandomChoice(RandomTransforms): + """Apply single transformation randomly picked from a list. This transform does not support torchscript.""" + + def __init__(self, transforms, p=None): + super().__init__(transforms) + if p is not None and not isinstance(p, Sequence): + raise TypeError("Argument p should be a sequence") + self.p = p + + def __call__(self, *args): + t = random.choices(self.transforms, weights=self.p)[0] + return t(*args) + + def __repr__(self) -> str: + return f"{super().__repr__()}(p={self.p})" + + +class RandomCrop(torch.nn.Module): + """Crop the given image at a random location. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions, + but if non-constant padding is used, the input is expected to have at most 2 leading dimensions + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + padding (int or sequence, optional): Optional padding on each border + of the image, applied before cropping. Default is None. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + pad_if_needed (boolean): It will pad the image if smaller than the + desired size to avoid raising an exception. Since cropping is done + after padding, the padding seems to be done at a random offset. + fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + Only number is supported for torch Tensor. + Only int or tuple value is supported for PIL Image. + padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + @staticmethod + def get_params(img: Tensor, output_size: tuple[int, int]) -> tuple[int, int, int, int]: + """Get parameters for ``crop`` for a random crop. + + Args: + img (PIL Image or Tensor): Image to be cropped. + output_size (tuple): Expected output size of the crop. + + Returns: + tuple: params (i, j, h, w) to be passed to ``crop`` for random crop. + """ + _, h, w = F.get_dimensions(img) + th, tw = output_size + + if h < th or w < tw: + raise ValueError(f"Required crop size {(th, tw)} is larger than input image size {(h, w)}") + + if w == tw and h == th: + return 0, 0, h, w + + i = torch.randint(0, h - th + 1, size=(1,)).item() + j = torch.randint(0, w - tw + 1, size=(1,)).item() + return i, j, th, tw + + def __init__(self, size, padding=None, pad_if_needed=False, fill=0, padding_mode="constant"): + super().__init__() + _log_api_usage_once(self) + + self.size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")) + + self.padding = padding + self.pad_if_needed = pad_if_needed + self.fill = fill + self.padding_mode = padding_mode + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + PIL Image or Tensor: Cropped image. + """ + if self.padding is not None: + img = F.pad(img, self.padding, self.fill, self.padding_mode) + + _, height, width = F.get_dimensions(img) + # pad the width if needed + if self.pad_if_needed and width < self.size[1]: + padding = [self.size[1] - width, 0] + img = F.pad(img, padding, self.fill, self.padding_mode) + # pad the height if needed + if self.pad_if_needed and height < self.size[0]: + padding = [0, self.size[0] - height] + img = F.pad(img, padding, self.fill, self.padding_mode) + + i, j, h, w = self.get_params(img, self.size) + + return F.crop(img, i, j, h, w) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size}, padding={self.padding})" + + +class RandomHorizontalFlip(torch.nn.Module): + """Horizontally flip the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + Args: + p (float): probability of the image being flipped. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be flipped. + + Returns: + PIL Image or Tensor: Randomly flipped image. + """ + if torch.rand(1) < self.p: + return F.hflip(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomVerticalFlip(torch.nn.Module): + """Vertically flip the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + Args: + p (float): probability of the image being flipped. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be flipped. + + Returns: + PIL Image or Tensor: Randomly flipped image. + """ + if torch.rand(1) < self.p: + return F.vflip(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomPerspective(torch.nn.Module): + """Performs a random perspective transformation of the given image with a given probability. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1. + Default is 0.5. + p (float): probability of the image being transformed. Default is 0.5. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number): Pixel fill value for the area outside the transformed + image. Default is ``0``. If given a number, the value is used for all bands respectively. + """ + + def __init__(self, distortion_scale=0.5, p=0.5, interpolation=InterpolationMode.BILINEAR, fill=0): + super().__init__() + _log_api_usage_once(self) + self.p = p + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.interpolation = interpolation + self.distortion_scale = distortion_scale + + if fill is None: + fill = 0 + elif not isinstance(fill, (Sequence, numbers.Number)): + raise TypeError("Fill should be either a sequence or a number.") + + self.fill = fill + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be Perspectively transformed. + + Returns: + PIL Image or Tensor: Randomly transformed image. + """ + + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + else: + fill = [float(f) for f in fill] + + if torch.rand(1) < self.p: + startpoints, endpoints = self.get_params(width, height, self.distortion_scale) + return F.perspective(img, startpoints, endpoints, self.interpolation, fill) + return img + + @staticmethod + def get_params(width: int, height: int, distortion_scale: float) -> tuple[list[list[int]], list[list[int]]]: + """Get parameters for ``perspective`` for a random perspective transform. + + Args: + width (int): width of the image. + height (int): height of the image. + distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1. + + Returns: + List containing [top-left, top-right, bottom-right, bottom-left] of the original image, + List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image. + """ + half_height = height // 2 + half_width = width // 2 + topleft = [ + int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()), + int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()), + ] + topright = [ + int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()), + int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()), + ] + botright = [ + int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()), + int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()), + ] + botleft = [ + int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()), + int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()), + ] + startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]] + endpoints = [topleft, topright, botright, botleft] + return startpoints, endpoints + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomResizedCrop(torch.nn.Module): + """Crop a random portion of image and resize it to a given size. + + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + A crop of the original image is made: the crop has a random area (H * W) + and a random aspect ratio. This crop is finally resized to the given + size. This is popularly used to train the Inception networks. + + Args: + size (int or sequence): expected output size of the crop, for each edge. If size is an + int instead of sequence like (h, w), a square output size ``(size, size)`` is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + scale (tuple of float): Specifies the lower and upper bounds for the random area of the crop, + before resizing. The scale is defined with respect to the area of the original image. + ratio (tuple of float): lower and upper bounds for the random aspect ratio of the crop, before + resizing. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + size, + scale=(0.08, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), + interpolation=InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + if not isinstance(scale, Sequence): + raise TypeError("Scale should be a sequence") + if not isinstance(ratio, Sequence): + raise TypeError("Ratio should be a sequence") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.interpolation = interpolation + self.antialias = antialias + self.scale = scale + self.ratio = ratio + + @staticmethod + def get_params(img: Tensor, scale: list[float], ratio: list[float]) -> tuple[int, int, int, int]: + """Get parameters for ``crop`` for a random sized crop. + + Args: + img (PIL Image or Tensor): Input image. + scale (list): range of scale of the origin size cropped + ratio (list): range of aspect ratio of the origin aspect ratio cropped + + Returns: + tuple: params (i, j, h, w) to be passed to ``crop`` for a random + sized crop. + """ + _, height, width = F.get_dimensions(img) + area = height * width + + log_ratio = torch.log(torch.tensor(ratio)) + for _ in range(10): + target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item() + aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item() + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + if 0 < w <= width and 0 < h <= height: + i = torch.randint(0, height - h + 1, size=(1,)).item() + j = torch.randint(0, width - w + 1, size=(1,)).item() + return i, j, h, w + + # Fallback to central crop + in_ratio = float(width) / float(height) + if in_ratio < min(ratio): + w = width + h = int(round(w / min(ratio))) + elif in_ratio > max(ratio): + h = height + w = int(round(h * max(ratio))) + else: # whole image + w = width + h = height + i = (height - h) // 2 + j = (width - w) // 2 + return i, j, h, w + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped and resized. + + Returns: + PIL Image or Tensor: Randomly cropped and resized image. + """ + i, j, h, w = self.get_params(img, self.scale, self.ratio) + return F.resized_crop(img, i, j, h, w, self.size, self.interpolation, antialias=self.antialias) + + def __repr__(self) -> str: + interpolate_str = self.interpolation.value + format_string = self.__class__.__name__ + f"(size={self.size}" + format_string += f", scale={tuple(round(s, 4) for s in self.scale)}" + format_string += f", ratio={tuple(round(r, 4) for r in self.ratio)}" + format_string += f", interpolation={interpolate_str}" + format_string += f", antialias={self.antialias})" + return format_string + + +class FiveCrop(torch.nn.Module): + """Crop the given image into four corners and the central crop. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an ``int`` + instead of sequence like (h, w), a square crop of size (size, size) is made. + If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + Example: + >>> transform = Compose([ + >>> FiveCrop(size), # this is a list of PIL Images + >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor + >>> ]) + >>> #In your test loop you can do the following: + >>> input, target = batch # input is a 5d tensor, target is 2d + >>> bs, ncrops, c, h, w = input.size() + >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops + >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops + """ + + def __init__(self, size): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + tuple of 5 images. Image can be PIL Image or Tensor + """ + return F.five_crop(img, self.size) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size})" + + +class TenCrop(torch.nn.Module): + """Crop the given image into four corners and the central crop plus the flipped version of + these (horizontal flipping is used by default). + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + vertical_flip (bool): Use vertical flipping instead of horizontal + + Example: + >>> transform = Compose([ + >>> TenCrop(size), # this is a tuple of PIL Images + >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor + >>> ]) + >>> #In your test loop you can do the following: + >>> input, target = batch # input is a 5d tensor, target is 2d + >>> bs, ncrops, c, h, w = input.size() + >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops + >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops + """ + + def __init__(self, size, vertical_flip=False): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + self.vertical_flip = vertical_flip + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + tuple of 10 images. Image can be PIL Image or Tensor + """ + return F.ten_crop(img, self.size, self.vertical_flip) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size}, vertical_flip={self.vertical_flip})" + + +class LinearTransformation(torch.nn.Module): + """Transform a tensor image with a square transformation matrix and a mean_vector computed + offline. + This transform does not support PIL Image. + Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and + subtract mean_vector from it which is then followed by computing the dot + product with the transformation matrix and then reshaping the tensor to its + original shape. + + Applications: + whitening transformation: Suppose X is a column vector zero-centered data. + Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X), + perform SVD on this matrix and pass it as transformation_matrix. + + Args: + transformation_matrix (Tensor): tensor [D x D], D = C x H x W + mean_vector (Tensor): tensor [D], D = C x H x W + """ + + def __init__(self, transformation_matrix, mean_vector): + super().__init__() + _log_api_usage_once(self) + if transformation_matrix.size(0) != transformation_matrix.size(1): + raise ValueError( + "transformation_matrix should be square. Got " + f"{tuple(transformation_matrix.size())} rectangular matrix." + ) + + if mean_vector.size(0) != transformation_matrix.size(0): + raise ValueError( + f"mean_vector should have the same length {mean_vector.size(0)}" + f" as any one of the dimensions of the transformation_matrix [{tuple(transformation_matrix.size())}]" + ) + + if transformation_matrix.device != mean_vector.device: + raise ValueError( + f"Input tensors should be on the same device. Got {transformation_matrix.device} and {mean_vector.device}" + ) + + if transformation_matrix.dtype != mean_vector.dtype: + raise ValueError( + f"Input tensors should have the same dtype. Got {transformation_matrix.dtype} and {mean_vector.dtype}" + ) + + self.transformation_matrix = transformation_matrix + self.mean_vector = mean_vector + + def forward(self, tensor: Tensor) -> Tensor: + """ + Args: + tensor (Tensor): Tensor image to be whitened. + + Returns: + Tensor: Transformed image. + """ + shape = tensor.shape + n = shape[-3] * shape[-2] * shape[-1] + if n != self.transformation_matrix.shape[0]: + raise ValueError( + "Input tensor and transformation matrix have incompatible shape." + + f"[{shape[-3]} x {shape[-2]} x {shape[-1]}] != " + + f"{self.transformation_matrix.shape[0]}" + ) + + if tensor.device.type != self.mean_vector.device.type: + raise ValueError( + "Input tensor should be on the same device as transformation matrix and mean vector. " + f"Got {tensor.device} vs {self.mean_vector.device}" + ) + + flat_tensor = tensor.view(-1, n) - self.mean_vector + transformation_matrix = self.transformation_matrix.to(flat_tensor.dtype) + transformed_tensor = torch.mm(flat_tensor, transformation_matrix) + tensor = transformed_tensor.view(shape) + return tensor + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(transformation_matrix=" + f"{self.transformation_matrix.tolist()}" + f", mean_vector={self.mean_vector.tolist()})" + ) + return s + + +class ColorJitter(torch.nn.Module): + """Randomly change the brightness, contrast, saturation and hue of an image. + If the image is torch Tensor, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported. + + Args: + brightness (float or tuple of float (min, max)): How much to jitter brightness. + brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness] + or the given [min, max]. Should be non negative numbers. + contrast (float or tuple of float (min, max)): How much to jitter contrast. + contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast] + or the given [min, max]. Should be non-negative numbers. + saturation (float or tuple of float (min, max)): How much to jitter saturation. + saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation] + or the given [min, max]. Should be non negative numbers. + hue (float or tuple of float (min, max)): How much to jitter hue. + hue_factor is chosen uniformly from [-hue, hue] or the given [min, max]. + Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5. + To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + """ + + def __init__( + self, + brightness: Union[float, tuple[float, float]] = 0, + contrast: Union[float, tuple[float, float]] = 0, + saturation: Union[float, tuple[float, float]] = 0, + hue: Union[float, tuple[float, float]] = 0, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.brightness = self._check_input(brightness, "brightness") + self.contrast = self._check_input(contrast, "contrast") + self.saturation = self._check_input(saturation, "saturation") + self.hue = self._check_input(hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False) + + @torch.jit.unused + def _check_input(self, value, name, center=1, bound=(0, float("inf")), clip_first_on_zero=True): + if isinstance(value, numbers.Number): + if value < 0: + raise ValueError(f"If {name} is a single number, it must be non negative.") + value = [center - float(value), center + float(value)] + if clip_first_on_zero: + value[0] = max(value[0], 0.0) + elif isinstance(value, (tuple, list)) and len(value) == 2: + value = [float(value[0]), float(value[1])] + else: + raise TypeError(f"{name} should be a single number or a list/tuple with length 2.") + + if not bound[0] <= value[0] <= value[1] <= bound[1]: + raise ValueError(f"{name} values should be between {bound}, but got {value}.") + + # if value is 0 or (1., 1.) for brightness/contrast/saturation + # or (0., 0.) for hue, do nothing + if value[0] == value[1] == center: + return None + else: + return tuple(value) + + @staticmethod + def get_params( + brightness: Optional[list[float]], + contrast: Optional[list[float]], + saturation: Optional[list[float]], + hue: Optional[list[float]], + ) -> tuple[Tensor, Optional[float], Optional[float], Optional[float], Optional[float]]: + """Get the parameters for the randomized transform to be applied on image. + + Args: + brightness (tuple of float (min, max), optional): The range from which the brightness_factor is chosen + uniformly. Pass None to turn off the transformation. + contrast (tuple of float (min, max), optional): The range from which the contrast_factor is chosen + uniformly. Pass None to turn off the transformation. + saturation (tuple of float (min, max), optional): The range from which the saturation_factor is chosen + uniformly. Pass None to turn off the transformation. + hue (tuple of float (min, max), optional): The range from which the hue_factor is chosen uniformly. + Pass None to turn off the transformation. + + Returns: + tuple: The parameters used to apply the randomized transform + along with their random order. + """ + fn_idx = torch.randperm(4) + + b = None if brightness is None else float(torch.empty(1).uniform_(brightness[0], brightness[1])) + c = None if contrast is None else float(torch.empty(1).uniform_(contrast[0], contrast[1])) + s = None if saturation is None else float(torch.empty(1).uniform_(saturation[0], saturation[1])) + h = None if hue is None else float(torch.empty(1).uniform_(hue[0], hue[1])) + + return fn_idx, b, c, s, h + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Input image. + + Returns: + PIL Image or Tensor: Color jittered image. + """ + fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor = self.get_params( + self.brightness, self.contrast, self.saturation, self.hue + ) + + for fn_id in fn_idx: + if fn_id == 0 and brightness_factor is not None: + img = F.adjust_brightness(img, brightness_factor) + elif fn_id == 1 and contrast_factor is not None: + img = F.adjust_contrast(img, contrast_factor) + elif fn_id == 2 and saturation_factor is not None: + img = F.adjust_saturation(img, saturation_factor) + elif fn_id == 3 and hue_factor is not None: + img = F.adjust_hue(img, hue_factor) + + return img + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"brightness={self.brightness}" + f", contrast={self.contrast}" + f", saturation={self.saturation}" + f", hue={self.hue})" + ) + return s + + +class RandomRotation(torch.nn.Module): + """Rotate the image by angle. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees). + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + expand (bool, optional): Optional expansion flag. + If true, expands the output to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + fill (sequence or number): Pixel fill value for the area outside the rotated + image. Default is ``0``. If given a number, the value is used for all bands respectively. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + def __init__(self, degrees, interpolation=InterpolationMode.NEAREST, expand=False, center=None, fill=0): + super().__init__() + _log_api_usage_once(self) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + self.interpolation = interpolation + self.expand = expand + + if fill is None: + fill = 0 + elif not isinstance(fill, (Sequence, numbers.Number)): + raise TypeError("Fill should be either a sequence or a number.") + + self.fill = fill + + @staticmethod + def get_params(degrees: list[float]) -> float: + """Get parameters for ``rotate`` for a random rotation. + + Returns: + float: angle parameter to be passed to ``rotate`` for random rotation. + """ + angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item()) + return angle + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be rotated. + + Returns: + PIL Image or Tensor: Rotated image. + """ + fill = self.fill + channels, _, _ = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + else: + fill = [float(f) for f in fill] + angle = self.get_params(self.degrees) + + return F.rotate(img, angle, self.interpolation, self.expand, self.center, fill) + + def __repr__(self) -> str: + interpolate_str = self.interpolation.value + format_string = self.__class__.__name__ + f"(degrees={self.degrees}" + format_string += f", interpolation={interpolate_str}" + format_string += f", expand={self.expand}" + if self.center is not None: + format_string += f", center={self.center}" + if self.fill is not None: + format_string += f", fill={self.fill}" + format_string += ")" + return format_string + + +class RandomAffine(torch.nn.Module): + """Random affine transformation of the image keeping center invariant. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees). Set to 0 to deactivate rotations. + translate (tuple, optional): tuple of maximum absolute fraction for horizontal + and vertical translations. For example translate=(a, b), then horizontal shift + is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is + randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default. + scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is + randomly sampled from the range a <= scale <= b. Will keep original scale by default. + shear (sequence or number, optional): Range of degrees to select from. + If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear) + will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the + range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values, + an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied. + Will not apply shear by default. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number): Pixel fill value for the area outside the transformed + image. Default is ``0``. If given a number, the value is used for all bands respectively. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + def __init__( + self, + degrees, + translate=None, + scale=None, + shear=None, + interpolation=InterpolationMode.NEAREST, + fill=0, + center=None, + ): + super().__init__() + _log_api_usage_once(self) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + + if translate is not None: + _check_sequence_input(translate, "translate", req_sizes=(2,)) + for t in translate: + if not (0.0 <= t <= 1.0): + raise ValueError("translation values should be between 0 and 1") + self.translate = translate + + if scale is not None: + _check_sequence_input(scale, "scale", req_sizes=(2,)) + for s in scale: + if s <= 0: + raise ValueError("scale values should be positive") + self.scale = scale + + if shear is not None: + self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4)) + else: + self.shear = shear + + self.interpolation = interpolation + + if fill is None: + fill = 0 + elif not isinstance(fill, (Sequence, numbers.Number)): + raise TypeError("Fill should be either a sequence or a number.") + + self.fill = fill + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + @staticmethod + def get_params( + degrees: list[float], + translate: Optional[list[float]], + scale_ranges: Optional[list[float]], + shears: Optional[list[float]], + img_size: list[int], + ) -> tuple[float, tuple[int, int], float, tuple[float, float]]: + """Get parameters for affine transformation + + Returns: + params to be passed to the affine transformation + """ + angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item()) + if translate is not None: + max_dx = float(translate[0] * img_size[0]) + max_dy = float(translate[1] * img_size[1]) + tx = int(round(torch.empty(1).uniform_(-max_dx, max_dx).item())) + ty = int(round(torch.empty(1).uniform_(-max_dy, max_dy).item())) + translations = (tx, ty) + else: + translations = (0, 0) + + if scale_ranges is not None: + scale = float(torch.empty(1).uniform_(scale_ranges[0], scale_ranges[1]).item()) + else: + scale = 1.0 + + shear_x = shear_y = 0.0 + if shears is not None: + shear_x = float(torch.empty(1).uniform_(shears[0], shears[1]).item()) + if len(shears) == 4: + shear_y = float(torch.empty(1).uniform_(shears[2], shears[3]).item()) + + shear = (shear_x, shear_y) + + return angle, translations, scale, shear + + def forward(self, img): + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Affine transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + else: + fill = [float(f) for f in fill] + + img_size = [width, height] # flip for keeping BC on get_params call + + ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img_size) + + return F.affine(img, *ret, interpolation=self.interpolation, fill=fill, center=self.center) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(degrees={self.degrees}" + s += f", translate={self.translate}" if self.translate is not None else "" + s += f", scale={self.scale}" if self.scale is not None else "" + s += f", shear={self.shear}" if self.shear is not None else "" + s += f", interpolation={self.interpolation.value}" if self.interpolation != InterpolationMode.NEAREST else "" + s += f", fill={self.fill}" if self.fill != 0 else "" + s += f", center={self.center}" if self.center is not None else "" + s += ")" + + return s + + +class Grayscale(torch.nn.Module): + """Convert image to grayscale. + If the image is torch Tensor, it is expected + to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + num_output_channels (int): (1 or 3) number of channels desired for output image + + Returns: + PIL Image: Grayscale version of the input. + + - If ``num_output_channels == 1`` : returned image is single channel + - If ``num_output_channels == 3`` : returned image is 3 channel with r == g == b + + """ + + def __init__(self, num_output_channels=1): + super().__init__() + _log_api_usage_once(self) + self.num_output_channels = num_output_channels + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be converted to grayscale. + + Returns: + PIL Image or Tensor: Grayscaled image. + """ + return F.rgb_to_grayscale(img, num_output_channels=self.num_output_channels) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(num_output_channels={self.num_output_channels})" + + +class RandomGrayscale(torch.nn.Module): + """Randomly convert image to grayscale with a probability of p (default 0.1). + If the image is torch Tensor, it is expected + to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + p (float): probability that image should be converted to grayscale. + + Returns: + PIL Image or Tensor: Grayscale version of the input image with probability p and unchanged + with probability (1-p). + - If input image is 1 channel: grayscale version is 1 channel + - If input image is 3 channel: grayscale version is 3 channel with r == g == b + + """ + + def __init__(self, p=0.1): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be converted to grayscale. + + Returns: + PIL Image or Tensor: Randomly grayscaled image. + """ + num_output_channels, _, _ = F.get_dimensions(img) + if torch.rand(1) < self.p: + return F.rgb_to_grayscale(img, num_output_channels=num_output_channels) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomErasing(torch.nn.Module): + """Randomly selects a rectangle region in a torch.Tensor image and erases its pixels. + This transform does not support PIL Image. + 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896 + + Args: + p: probability that the random erasing operation will be performed. + scale: range of proportion of erased area against input image. + ratio: range of aspect ratio of erased area. + value: erasing value. Default is 0. If a single int, it is used to + erase all pixels. If a tuple of length 3, it is used to erase + R, G, B channels respectively. + If a str of 'random', erasing each pixel with random values. + inplace: boolean to make this transform inplace. Default set to False. + + Returns: + Erased Image. + + Example: + >>> transform = transforms.Compose([ + >>> transforms.RandomHorizontalFlip(), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> transforms.RandomErasing(), + >>> ]) + """ + + def __init__(self, p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), value=0, inplace=False): + super().__init__() + _log_api_usage_once(self) + if not isinstance(value, (numbers.Number, str, tuple, list)): + raise TypeError("Argument value should be either a number or str or a sequence") + if isinstance(value, str) and value != "random": + raise ValueError("If value is str, it should be 'random'") + if not isinstance(scale, Sequence): + raise TypeError("Scale should be a sequence") + if not isinstance(ratio, Sequence): + raise TypeError("Ratio should be a sequence") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + if scale[0] < 0 or scale[1] > 1: + raise ValueError("Scale should be between 0 and 1") + if p < 0 or p > 1: + raise ValueError("Random erasing probability should be between 0 and 1") + + self.p = p + self.scale = scale + self.ratio = ratio + self.value = value + self.inplace = inplace + + @staticmethod + def get_params( + img: Tensor, scale: tuple[float, float], ratio: tuple[float, float], value: Optional[list[float]] = None + ) -> tuple[int, int, int, int, Tensor]: + """Get parameters for ``erase`` for a random erasing. + + Args: + img (Tensor): Tensor image to be erased. + scale (sequence): range of proportion of erased area against input image. + ratio (sequence): range of aspect ratio of erased area. + value (list, optional): erasing value. If None, it is interpreted as "random" + (erasing each pixel with random values). If ``len(value)`` is 1, it is interpreted as a number, + i.e. ``value[0]``. + + Returns: + tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erasing. + """ + img_c, img_h, img_w = img.shape[-3], img.shape[-2], img.shape[-1] + area = img_h * img_w + + log_ratio = torch.log(torch.tensor(ratio)) + for _ in range(10): + erase_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item() + aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item() + + h = int(round(math.sqrt(erase_area * aspect_ratio))) + w = int(round(math.sqrt(erase_area / aspect_ratio))) + if not (h < img_h and w < img_w): + continue + + if value is None: + v = torch.empty([img_c, h, w], dtype=torch.float32).normal_() + else: + v = torch.tensor(value)[:, None, None] + + i = torch.randint(0, img_h - h + 1, size=(1,)).item() + j = torch.randint(0, img_w - w + 1, size=(1,)).item() + return i, j, h, w, v + + # Return original image + return 0, 0, img_h, img_w, img + + def forward(self, img): + """ + Args: + img (Tensor): Tensor image to be erased. + + Returns: + img (Tensor): Erased Tensor image. + """ + if torch.rand(1) < self.p: + + # cast self.value to script acceptable type + if isinstance(self.value, (int, float)): + value = [float(self.value)] + elif isinstance(self.value, str): + value = None + elif isinstance(self.value, (list, tuple)): + value = [float(v) for v in self.value] + else: + value = self.value + + if value is not None and len(value) not in (1, img.shape[-3]): + raise ValueError( + "If value is a sequence, it should have either a single value or " + f"{img.shape[-3]} (number of input channels)" + ) + + x, y, h, w, v = self.get_params(img, scale=self.scale, ratio=self.ratio, value=value) + return F.erase(img, x, y, h, w, v, self.inplace) + return img + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}" + f"(p={self.p}, " + f"scale={self.scale}, " + f"ratio={self.ratio}, " + f"value={self.value}, " + f"inplace={self.inplace})" + ) + return s + + +class GaussianBlur(torch.nn.Module): + """Blurs image with randomly chosen Gaussian blur. + If the image is torch Tensor, it is expected + to have [..., C, H, W] shape, where ... means at most one leading dimension. + + Args: + kernel_size (int or sequence): Size of the Gaussian kernel. + sigma (float or tuple of float (min, max)): Standard deviation to be used for + creating kernel to perform blurring. If float, sigma is fixed. If it is tuple + of float (min, max), sigma is chosen uniformly at random to lie in the + given range. + + Returns: + PIL Image or Tensor: Gaussian blurred version of the input image. + + """ + + def __init__(self, kernel_size, sigma=(0.1, 2.0)): + super().__init__() + _log_api_usage_once(self) + self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers") + for ks in self.kernel_size: + if ks <= 0 or ks % 2 == 0: + raise ValueError("Kernel size value should be an odd and positive number.") + + if isinstance(sigma, numbers.Number): + if sigma <= 0: + raise ValueError("If sigma is a single number, it must be positive.") + sigma = (sigma, sigma) + elif isinstance(sigma, Sequence) and len(sigma) == 2: + if not 0.0 < sigma[0] <= sigma[1]: + raise ValueError("sigma values should be positive and of the form (min, max).") + else: + raise ValueError("sigma should be a single number or a list/tuple with length 2.") + + self.sigma = sigma + + @staticmethod + def get_params(sigma_min: float, sigma_max: float) -> float: + """Choose sigma for random gaussian blurring. + + Args: + sigma_min (float): Minimum standard deviation that can be chosen for blurring kernel. + sigma_max (float): Maximum standard deviation that can be chosen for blurring kernel. + + Returns: + float: Standard deviation to be passed to calculate kernel for gaussian blurring. + """ + return torch.empty(1).uniform_(sigma_min, sigma_max).item() + + def forward(self, img: Tensor) -> Tensor: + """ + Args: + img (PIL Image or Tensor): image to be blurred. + + Returns: + PIL Image or Tensor: Gaussian blurred image + """ + sigma = self.get_params(self.sigma[0], self.sigma[1]) + return F.gaussian_blur(img, self.kernel_size, [sigma, sigma]) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(kernel_size={self.kernel_size}, sigma={self.sigma})" + return s + + +def _setup_size(size, error_msg): + if isinstance(size, numbers.Number): + return int(size), int(size) + + if isinstance(size, Sequence) and len(size) == 1: + return size[0], size[0] + + if len(size) != 2: + raise ValueError(error_msg) + + return size + + +def _check_sequence_input(x, name, req_sizes): + msg = req_sizes[0] if len(req_sizes) < 2 else " or ".join([str(s) for s in req_sizes]) + if not isinstance(x, Sequence): + raise TypeError(f"{name} should be a sequence of length {msg}.") + if len(x) not in req_sizes: + raise ValueError(f"{name} should be a sequence of length {msg}.") + + +def _setup_angle(x, name, req_sizes=(2,)): + if isinstance(x, numbers.Number): + if x < 0: + raise ValueError(f"If {name} is a single number, it must be positive.") + x = [-x, x] + else: + _check_sequence_input(x, name, req_sizes) + + return [float(d) for d in x] + + +class RandomInvert(torch.nn.Module): + """Inverts the colors of the given image randomly with a given probability. + If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being color inverted. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be inverted. + + Returns: + PIL Image or Tensor: Randomly color inverted image. + """ + if torch.rand(1).item() < self.p: + return F.invert(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomPosterize(torch.nn.Module): + """Posterize the image randomly with a given probability by reducing the + number of bits for each color channel. If the image is torch Tensor, it should be of type torch.uint8, + and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + bits (int): number of bits to keep for each channel (0-8) + p (float): probability of the image being posterized. Default value is 0.5 + """ + + def __init__(self, bits, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.bits = bits + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be posterized. + + Returns: + PIL Image or Tensor: Randomly posterized image. + """ + if torch.rand(1).item() < self.p: + return F.posterize(img, self.bits) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(bits={self.bits},p={self.p})" + + +class RandomSolarize(torch.nn.Module): + """Solarize the image randomly with a given probability by inverting all pixel + values above a threshold. If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + threshold (float): all pixels equal or above this value are inverted. + p (float): probability of the image being solarized. Default value is 0.5 + """ + + def __init__(self, threshold, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.threshold = threshold + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be solarized. + + Returns: + PIL Image or Tensor: Randomly solarized image. + """ + if torch.rand(1).item() < self.p: + return F.solarize(img, self.threshold) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(threshold={self.threshold},p={self.p})" + + +class RandomAdjustSharpness(torch.nn.Module): + """Adjust the sharpness of the image randomly with a given probability. If the image is torch Tensor, + it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + sharpness_factor (float): How much to adjust the sharpness. Can be + any non-negative number. 0 gives a blurred image, 1 gives the + original image while 2 increases the sharpness by a factor of 2. + p (float): probability of the image being sharpened. Default value is 0.5 + """ + + def __init__(self, sharpness_factor, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.sharpness_factor = sharpness_factor + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be sharpened. + + Returns: + PIL Image or Tensor: Randomly sharpened image. + """ + if torch.rand(1).item() < self.p: + return F.adjust_sharpness(img, self.sharpness_factor) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(sharpness_factor={self.sharpness_factor},p={self.p})" + + +class RandomAutocontrast(torch.nn.Module): + """Autocontrast the pixels of the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being autocontrasted. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be autocontrasted. + + Returns: + PIL Image or Tensor: Randomly autocontrasted image. + """ + if torch.rand(1).item() < self.p: + return F.autocontrast(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomEqualize(torch.nn.Module): + """Equalize the histogram of the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + + Args: + p (float): probability of the image being equalized. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be equalized. + + Returns: + PIL Image or Tensor: Randomly equalized image. + """ + if torch.rand(1).item() < self.p: + return F.equalize(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class ElasticTransform(torch.nn.Module): + """Transform a tensor image with elastic transformations. + Given alpha and sigma, it will generate displacement + vectors for all pixels based on random offsets. Alpha controls the strength + and sigma controls the smoothness of the displacements. + The displacements are added to an identity grid and the resulting grid is + used to grid_sample from the image. + + Applications: + Randomly transforms the morphology of objects in images and produces a + see-through-water-like effect. + + Args: + alpha (float or sequence of floats): Magnitude of displacements. Default is 50.0. + sigma (float or sequence of floats): Smoothness of displacements. Default is 5.0. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number): Pixel fill value for the area outside the transformed + image. Default is ``0``. If given a number, the value is used for all bands respectively. + + """ + + def __init__(self, alpha=50.0, sigma=5.0, interpolation=InterpolationMode.BILINEAR, fill=0): + super().__init__() + _log_api_usage_once(self) + if not isinstance(alpha, (float, Sequence)): + raise TypeError(f"alpha should be float or a sequence of floats. Got {type(alpha)}") + if isinstance(alpha, Sequence) and len(alpha) != 2: + raise ValueError(f"If alpha is a sequence its length should be 2. Got {len(alpha)}") + if isinstance(alpha, Sequence): + for element in alpha: + if not isinstance(element, float): + raise TypeError(f"alpha should be a sequence of floats. Got {type(element)}") + + if isinstance(alpha, float): + alpha = [float(alpha), float(alpha)] + if isinstance(alpha, (list, tuple)) and len(alpha) == 1: + alpha = [alpha[0], alpha[0]] + + self.alpha = alpha + + if not isinstance(sigma, (float, Sequence)): + raise TypeError(f"sigma should be float or a sequence of floats. Got {type(sigma)}") + if isinstance(sigma, Sequence) and len(sigma) != 2: + raise ValueError(f"If sigma is a sequence its length should be 2. Got {len(sigma)}") + if isinstance(sigma, Sequence): + for element in sigma: + if not isinstance(element, float): + raise TypeError(f"sigma should be a sequence of floats. Got {type(element)}") + + if isinstance(sigma, float): + sigma = [float(sigma), float(sigma)] + if isinstance(sigma, (list, tuple)) and len(sigma) == 1: + sigma = [sigma[0], sigma[0]] + + self.sigma = sigma + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + self.interpolation = interpolation + + if isinstance(fill, (int, float)): + fill = [float(fill)] + elif isinstance(fill, (list, tuple)): + fill = [float(f) for f in fill] + else: + raise TypeError(f"fill should be int or float or a list or tuple of them. Got {type(fill)}") + self.fill = fill + + @staticmethod + def get_params(alpha: list[float], sigma: list[float], size: list[int]) -> Tensor: + dx = torch.rand([1, 1] + size) * 2 - 1 + if sigma[0] > 0.0: + kx = int(8 * sigma[0] + 1) + # if kernel size is even we have to make it odd + if kx % 2 == 0: + kx += 1 + dx = F.gaussian_blur(dx, [kx, kx], sigma) + dx = dx * alpha[0] / size[0] + + dy = torch.rand([1, 1] + size) * 2 - 1 + if sigma[1] > 0.0: + ky = int(8 * sigma[1] + 1) + # if kernel size is even we have to make it odd + if ky % 2 == 0: + ky += 1 + dy = F.gaussian_blur(dy, [ky, ky], sigma) + dy = dy * alpha[1] / size[1] + return torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2 + + def forward(self, tensor: Tensor) -> Tensor: + """ + Args: + tensor (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + _, height, width = F.get_dimensions(tensor) + displacement = self.get_params(self.alpha, self.sigma, [height, width]) + return F.elastic_transform(tensor, displacement, self.interpolation, self.fill) + + def __repr__(self): + format_string = self.__class__.__name__ + format_string += f"(alpha={self.alpha}" + format_string += f", sigma={self.sigma}" + format_string += f", interpolation={self.interpolation}" + format_string += f", fill={self.fill})" + return format_string diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..895bf6e2f711bb928934c45025f483e0fecb56d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/__init__.py @@ -0,0 +1,61 @@ +from torchvision.transforms import AutoAugmentPolicy, InterpolationMode # usort: skip + +from . import functional # usort: skip + +from ._transform import Transform # usort: skip + +from ._augment import CutMix, JPEG, MixUp, RandomErasing +from ._auto_augment import AugMix, AutoAugment, RandAugment, TrivialAugmentWide +from ._color import ( + ColorJitter, + Grayscale, + RandomAdjustSharpness, + RandomAutocontrast, + RandomChannelPermutation, + RandomEqualize, + RandomGrayscale, + RandomInvert, + RandomPhotometricDistort, + RandomPosterize, + RandomSolarize, + RGB, +) +from ._container import Compose, RandomApply, RandomChoice, RandomOrder +from ._geometry import ( + CenterCrop, + ElasticTransform, + FiveCrop, + Pad, + RandomAffine, + RandomCrop, + RandomHorizontalFlip, + RandomIoUCrop, + RandomPerspective, + RandomResize, + RandomResizedCrop, + RandomRotation, + RandomShortestSize, + RandomVerticalFlip, + RandomZoomOut, + Resize, + ScaleJitter, + TenCrop, +) +from ._meta import ClampBoundingBoxes, ClampKeyPoints, ConvertBoundingBoxFormat, SetClampingMode +from ._misc import ( + ConvertImageDtype, + GaussianBlur, + GaussianNoise, + Identity, + Lambda, + LinearTransformation, + Normalize, + SanitizeBoundingBoxes, + SanitizeKeyPoints, + ToDtype, +) +from ._temporal import UniformTemporalSubsample +from ._type_conversion import PILToTensor, ToImage, ToPILImage, ToPureTensor +from ._utils import check_type, get_bounding_boxes, get_keypoints, has_all, has_any, query_chw, query_size + +from ._deprecated import ToTensor # usort: skip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_augment.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_augment.py new file mode 100644 index 0000000000000000000000000000000000000000..c6da9aba98bece914509ce5a2651ea1af495a72b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_augment.py @@ -0,0 +1,374 @@ +import math +import numbers +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import PIL.Image +import torch +from torch.nn.functional import one_hot +from torch.utils._pytree import tree_flatten, tree_unflatten +from torchvision import transforms as _transforms, tv_tensors +from torchvision.transforms.v2 import functional as F + +from ._transform import _RandomApplyTransform, Transform +from ._utils import _check_sequence_input, _parse_labels_getter, has_any, is_pure_tensor, query_chw, query_size + + +class RandomErasing(_RandomApplyTransform): + """Randomly select a rectangle region in the input image or video and erase its pixels. + + This transform does not support PIL Image. + 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896 + + Args: + p (float, optional): probability that the random erasing operation will be performed. + scale (tuple of float, optional): range of proportion of erased area against input image. + ratio (tuple of float, optional): range of aspect ratio of erased area. + value (number or tuple of numbers): erasing value. Default is 0. If a single int, it is used to + erase all pixels. If a tuple of length 3, it is used to erase + R, G, B channels respectively. + If a str of 'random', erasing each pixel with random values. + inplace (bool, optional): boolean to make this transform inplace. Default set to False. + + Returns: + Erased input. + + Example: + >>> from torchvision.transforms import v2 as transforms + >>> + >>> transform = transforms.Compose([ + >>> transforms.RandomHorizontalFlip(), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> transforms.RandomErasing(), + >>> ]) + """ + + _v1_transform_cls = _transforms.RandomErasing + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + return dict( + super()._extract_params_for_v1_transform(), + value="random" if self.value is None else self.value, + ) + + def __init__( + self, + p: float = 0.5, + scale: Sequence[float] = (0.02, 0.33), + ratio: Sequence[float] = (0.3, 3.3), + value: float = 0.0, + inplace: bool = False, + ): + super().__init__(p=p) + if not isinstance(value, (numbers.Number, str, tuple, list)): + raise TypeError("Argument value should be either a number or str or a sequence") + if isinstance(value, str) and value != "random": + raise ValueError("If value is str, it should be 'random'") + if not isinstance(scale, Sequence): + raise TypeError("Scale should be a sequence") + if not isinstance(ratio, Sequence): + raise TypeError("Ratio should be a sequence") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + if scale[0] < 0 or scale[1] > 1: + raise ValueError("Scale should be between 0 and 1") + self.scale = scale + self.ratio = ratio + if isinstance(value, (int, float)): + self.value = [float(value)] + elif isinstance(value, str): + self.value = None + elif isinstance(value, (list, tuple)): + self.value = [float(v) for v in value] + else: + self.value = value + self.inplace = inplace + + self._log_ratio = torch.log(torch.tensor(self.ratio)) + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, tv_tensors.Mask)): + warnings.warn( + f"{type(self).__name__}() is currently passing through inputs of type " + f"tv_tensors.{type(inpt).__name__}. This will likely change in the future." + ) + return super()._call_kernel(functional, inpt, *args, **kwargs) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + img_c, img_h, img_w = query_chw(flat_inputs) + + if self.value is not None and len(self.value) not in (1, img_c): + raise ValueError( + f"If value is a sequence, it should have either a single value or {img_c} (number of inpt channels)" + ) + + area = img_h * img_w + + log_ratio = self._log_ratio + for _ in range(10): + erase_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item() + aspect_ratio = torch.exp( + torch.empty(1).uniform_( + log_ratio[0], # type: ignore[arg-type] + log_ratio[1], # type: ignore[arg-type] + ) + ).item() + + h = int(round(math.sqrt(erase_area * aspect_ratio))) + w = int(round(math.sqrt(erase_area / aspect_ratio))) + if not (h < img_h and w < img_w): + continue + + if self.value is None: + v = torch.empty([img_c, h, w], dtype=torch.float32).normal_() + else: + v = torch.tensor(self.value)[:, None, None] + + i = torch.randint(0, img_h - h + 1, size=(1,)).item() + j = torch.randint(0, img_w - w + 1, size=(1,)).item() + break + else: + i, j, h, w, v = 0, 0, img_h, img_w, None + + return dict(i=i, j=j, h=h, w=w, v=v) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if params["v"] is not None: + inpt = self._call_kernel(F.erase, inpt, **params, inplace=self.inplace) + + return inpt + + +class _BaseMixUpCutMix(Transform): + def __init__(self, *, alpha: float = 1.0, num_classes: Optional[int] = None, labels_getter="default") -> None: + super().__init__() + self.alpha = float(alpha) + self._dist = torch.distributions.Beta(torch.tensor([alpha]), torch.tensor([alpha])) + + self.num_classes = num_classes + + self._labels_getter = _parse_labels_getter(labels_getter) + + def forward(self, *inputs): + inputs = inputs if len(inputs) > 1 else inputs[0] + flat_inputs, spec = tree_flatten(inputs) + needs_transform_list = self._needs_transform_list(flat_inputs) + + if has_any(flat_inputs, PIL.Image.Image, tv_tensors.BoundingBoxes, tv_tensors.Mask, tv_tensors.KeyPoints): + raise ValueError( + f"{type(self).__name__}() does not support PIL images, bounding boxes, keypoints and masks." + ) + + labels = self._labels_getter(inputs) + if not isinstance(labels, torch.Tensor): + raise ValueError(f"The labels must be a tensor, but got {type(labels)} instead.") + if labels.ndim not in (1, 2): + raise ValueError( + f"labels should be index based with shape (batch_size,) " + f"or probability based with shape (batch_size, num_classes), " + f"but got a tensor of shape {labels.shape} instead." + ) + if labels.ndim == 2 and self.num_classes is not None and labels.shape[-1] != self.num_classes: + raise ValueError( + f"When passing 2D labels, " + f"the number of elements in last dimension must match num_classes: " + f"{labels.shape[-1]} != {self.num_classes}. " + f"You can Leave num_classes to None." + ) + if labels.ndim == 1 and self.num_classes is None: + raise ValueError("num_classes must be passed if the labels are index-based (1D)") + + params = { + "labels": labels, + "batch_size": labels.shape[0], + **self.make_params( + [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform] + ), + } + + # By default, the labels will be False inside needs_transform_list, since they are a torch.Tensor coming + # after an image or video. However, we need to handle them in _transform, so we make sure to set them to True + needs_transform_list[next(idx for idx, inpt in enumerate(flat_inputs) if inpt is labels)] = True + flat_outputs = [ + self.transform(inpt, params) if needs_transform else inpt + for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) + ] + + return tree_unflatten(flat_outputs, spec) + + def _check_image_or_video(self, inpt: torch.Tensor, *, batch_size: int): + expected_num_dims = 5 if isinstance(inpt, tv_tensors.Video) else 4 + if inpt.ndim != expected_num_dims: + raise ValueError( + f"Expected a batched input with {expected_num_dims} dims, but got {inpt.ndim} dimensions instead." + ) + if inpt.shape[0] != batch_size: + raise ValueError( + f"The batch size of the image or video does not match the batch size of the labels: " + f"{inpt.shape[0]} != {batch_size}." + ) + + def _mixup_label(self, label: torch.Tensor, *, lam: float) -> torch.Tensor: + if label.ndim == 1: + label = one_hot(label, num_classes=self.num_classes) # type: ignore[arg-type] + if not label.dtype.is_floating_point: + label = label.float() + return label.roll(1, 0).mul_(1.0 - lam).add_(label.mul(lam)) + + +class MixUp(_BaseMixUpCutMix): + """Apply MixUp to the provided batch of images and labels. + + Paper: `mixup: Beyond Empirical Risk Minimization `_. + + .. note:: + This transform is meant to be used on **batches** of samples, not + individual images. See + :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage + examples. + The sample pairing is deterministic and done by matching consecutive + samples in the batch, so the batch needs to be shuffled (this is an + implementation detail, not a guaranteed convention.) + + In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed + into a tensor of shape ``(batch_size, num_classes)``. + + Args: + alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1. + num_classes (int, optional): number of classes in the batch. Used for one-hot-encoding. + Can be None only if the labels are already one-hot-encoded. + labels_getter (callable or "default", optional): indicates how to identify the labels in the input. + By default, this will pick the second parameter as the labels if it's a tensor. This covers the most + common scenario where this transform is called as ``MixUp()(imgs_batch, labels_batch)``. + It can also be a callable that takes the same input as the transform, and returns the labels. + """ + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + return dict(lam=float(self._dist.sample(()))) # type: ignore[arg-type] + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + lam = params["lam"] + + if inpt is params["labels"]: + return self._mixup_label(inpt, lam=lam) + elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt): + self._check_image_or_video(inpt, batch_size=params["batch_size"]) + + output = inpt.roll(1, 0).mul_(1.0 - lam).add_(inpt.mul(lam)) + + if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + output = tv_tensors.wrap(output, like=inpt) + + return output + else: + return inpt + + +class CutMix(_BaseMixUpCutMix): + """Apply CutMix to the provided batch of images and labels. + + Paper: `CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features + `_. + + .. note:: + This transform is meant to be used on **batches** of samples, not + individual images. See + :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage + examples. + The sample pairing is deterministic and done by matching consecutive + samples in the batch, so the batch needs to be shuffled (this is an + implementation detail, not a guaranteed convention.) + + In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed + into a tensor of shape ``(batch_size, num_classes)``. + + Args: + alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1. + num_classes (int, optional): number of classes in the batch. Used for one-hot-encoding. + Can be None only if the labels are already one-hot-encoded. + labels_getter (callable or "default", optional): indicates how to identify the labels in the input. + By default, this will pick the second parameter as the labels if it's a tensor. This covers the most + common scenario where this transform is called as ``CutMix()(imgs_batch, labels_batch)``. + It can also be a callable that takes the same input as the transform, and returns the labels. + """ + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + lam = float(self._dist.sample(())) # type: ignore[arg-type] + + H, W = query_size(flat_inputs) + + r_x = torch.randint(W, size=(1,)) + r_y = torch.randint(H, size=(1,)) + + r = 0.5 * math.sqrt(1.0 - lam) + r_w_half = int(r * W) + r_h_half = int(r * H) + + x1 = int(torch.clamp(r_x - r_w_half, min=0)) + y1 = int(torch.clamp(r_y - r_h_half, min=0)) + x2 = int(torch.clamp(r_x + r_w_half, max=W)) + y2 = int(torch.clamp(r_y + r_h_half, max=H)) + box = (x1, y1, x2, y2) + + lam_adjusted = float(1.0 - (x2 - x1) * (y2 - y1) / (W * H)) + + return dict(box=box, lam_adjusted=lam_adjusted) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if inpt is params["labels"]: + return self._mixup_label(inpt, lam=params["lam_adjusted"]) + elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt): + self._check_image_or_video(inpt, batch_size=params["batch_size"]) + + x1, y1, x2, y2 = params["box"] + rolled = inpt.roll(1, 0) + output = inpt.clone() + output[..., y1:y2, x1:x2] = rolled[..., y1:y2, x1:x2] + + if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + output = tv_tensors.wrap(output, like=inpt) + + return output + else: + return inpt + + +class JPEG(Transform): + """Apply JPEG compression and decompression to the given images. + + If the input is a :class:`torch.Tensor`, it is expected + to be of dtype uint8, on CPU, and have [..., 3 or 1, H, W] shape, + where ... means an arbitrary number of leading dimensions. + + Args: + quality (sequence or number): JPEG quality, from 1 to 100. Lower means more compression. + If quality is a sequence like (min, max), it specifies the range of JPEG quality to + randomly select from (inclusive of both ends). + + Returns: + image with JPEG compression. + """ + + def __init__(self, quality: Union[int, Sequence[int]]): + super().__init__() + if isinstance(quality, int): + if isinstance(quality, bool): + raise TypeError("quality can't be bool") + quality = [quality, quality] + else: + _check_sequence_input(quality, "quality", req_sizes=(2,)) + + if not (1 <= quality[0] <= quality[1] <= 100 and isinstance(quality[0], int) and isinstance(quality[1], int)): + raise ValueError(f"quality must be an integer from 1 to 100, got {quality =}") + + self.quality = quality + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + quality = torch.randint(self.quality[0], self.quality[1] + 1, ()).item() + return dict(quality=quality) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.jpeg, inpt, quality=params["quality"]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_auto_augment.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_auto_augment.py new file mode 100644 index 0000000000000000000000000000000000000000..52707af1f2e8be5d3fbfe4570455beeb13560f6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_auto_augment.py @@ -0,0 +1,631 @@ +import math +from typing import Any, Callable, cast, Optional, Union + +import PIL.Image +import torch + +from torch.utils._pytree import tree_flatten, tree_unflatten, TreeSpec +from torchvision import transforms as _transforms, tv_tensors +from torchvision.transforms import _functional_tensor as _FT +from torchvision.transforms.v2 import AutoAugmentPolicy, functional as F, InterpolationMode, Transform +from torchvision.transforms.v2.functional._geometry import _check_interpolation +from torchvision.transforms.v2.functional._meta import get_size +from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT + +from ._utils import _get_fill, _setup_fill_arg, check_type, is_pure_tensor + + +ImageOrVideo = Union[torch.Tensor, PIL.Image.Image, tv_tensors.Image, tv_tensors.Video] + + +class _AutoAugmentBase(Transform): + def __init__( + self, + *, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__() + self.interpolation = _check_interpolation(interpolation) + self.fill = fill + self._fill = _setup_fill_arg(fill) + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + + if isinstance(params["fill"], dict): + raise ValueError(f"{type(self).__name__}() can not be scripted for when `fill` is a dictionary.") + + return params + + def _get_random_item(self, dct: dict[str, tuple[Callable, bool]]) -> tuple[str, tuple[Callable, bool]]: + keys = tuple(dct.keys()) + key = keys[int(torch.randint(len(keys), ()))] + return key, dct[key] + + def _flatten_and_extract_image_or_video( + self, + inputs: Any, + unsupported_types: tuple[type, ...] = (tv_tensors.BoundingBoxes, tv_tensors.Mask, tv_tensors.KeyPoints), + ) -> tuple[tuple[list[Any], TreeSpec, int], ImageOrVideo]: + flat_inputs, spec = tree_flatten(inputs if len(inputs) > 1 else inputs[0]) + needs_transform_list = self._needs_transform_list(flat_inputs) + + image_or_videos = [] + for idx, (inpt, needs_transform) in enumerate(zip(flat_inputs, needs_transform_list)): + if needs_transform and check_type( + inpt, + ( + tv_tensors.Image, + PIL.Image.Image, + is_pure_tensor, + tv_tensors.Video, + ), + ): + image_or_videos.append((idx, inpt)) + elif isinstance(inpt, unsupported_types): + raise TypeError(f"Inputs of type {type(inpt).__name__} are not supported by {type(self).__name__}()") + + if not image_or_videos: + raise TypeError("Found no image in the sample.") + if len(image_or_videos) > 1: + raise TypeError( + f"Auto augment transformations are only properly defined for a single image or video, " + f"but found {len(image_or_videos)}." + ) + + idx, image_or_video = image_or_videos[0] + return (flat_inputs, spec, idx), image_or_video + + def _unflatten_and_insert_image_or_video( + self, + flat_inputs_with_spec: tuple[list[Any], TreeSpec, int], + image_or_video: ImageOrVideo, + ) -> Any: + flat_inputs, spec, idx = flat_inputs_with_spec + flat_inputs[idx] = image_or_video + return tree_unflatten(flat_inputs, spec) + + def _apply_image_or_video_transform( + self, + image: ImageOrVideo, + transform_id: str, + magnitude: float, + interpolation: Union[InterpolationMode, int], + fill: dict[Union[type, str], _FillTypeJIT], + ) -> ImageOrVideo: + # Note: this cast is wrong and is only here to make mypy happy (it disagrees with torchscript) + image = cast(torch.Tensor, image) + fill_ = _get_fill(fill, type(image)) + + if transform_id == "Identity": + return image + elif transform_id == "ShearX": + # magnitude should be arctan(magnitude) + # official autoaug: (1, level, 0, 0, 1, 0) + # https://github.com/tensorflow/models/blob/dd02069717128186b88afa8d857ce57d17957f03/research/autoaugment/augmentation_transforms.py#L290 + # compared to + # torchvision: (1, tan(level), 0, 0, 1, 0) + # https://github.com/pytorch/vision/blob/0c2373d0bba3499e95776e7936e207d8a1676e65/torchvision/transforms/functional.py#L976 + return F.affine( + image, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[math.degrees(math.atan(magnitude)), 0.0], + interpolation=interpolation, + fill=fill_, + center=[0, 0], + ) + elif transform_id == "ShearY": + # magnitude should be arctan(magnitude) + # See above + return F.affine( + image, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[0.0, math.degrees(math.atan(magnitude))], + interpolation=interpolation, + fill=fill_, + center=[0, 0], + ) + elif transform_id == "TranslateX": + return F.affine( + image, + angle=0.0, + translate=[int(magnitude), 0], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill_, + ) + elif transform_id == "TranslateY": + return F.affine( + image, + angle=0.0, + translate=[0, int(magnitude)], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill_, + ) + elif transform_id == "Rotate": + return F.rotate(image, angle=magnitude, interpolation=interpolation, fill=fill_) + elif transform_id == "Brightness": + return F.adjust_brightness(image, brightness_factor=1.0 + magnitude) + elif transform_id == "Color": + return F.adjust_saturation(image, saturation_factor=1.0 + magnitude) + elif transform_id == "Contrast": + return F.adjust_contrast(image, contrast_factor=1.0 + magnitude) + elif transform_id == "Sharpness": + return F.adjust_sharpness(image, sharpness_factor=1.0 + magnitude) + elif transform_id == "Posterize": + return F.posterize(image, bits=int(magnitude)) + elif transform_id == "Solarize": + bound = _FT._max_value(image.dtype) if isinstance(image, torch.Tensor) else 255.0 + return F.solarize(image, threshold=bound * magnitude) + elif transform_id == "AutoContrast": + return F.autocontrast(image) + elif transform_id == "Equalize": + return F.equalize(image) + elif transform_id == "Invert": + return F.invert(image) + else: + raise ValueError(f"No transform available for {transform_id}") + + +class AutoAugment(_AutoAugmentBase): + r"""AutoAugment data augmentation method based on + `"AutoAugment: Learning Augmentation Strategies from Data" `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + policy (AutoAugmentPolicy, optional): Desired policy enum defined by + :class:`torchvision.transforms.autoaugment.AutoAugmentPolicy`. Default is ``AutoAugmentPolicy.IMAGENET``. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.AutoAugment + + _AUGMENTATION_SPACE = { + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * width, num_bins), + True, + ), + "TranslateY": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * height, num_bins), + True, + ), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + "Invert": (lambda num_bins, height, width: None, False), + } + + def __init__( + self, + policy: AutoAugmentPolicy = AutoAugmentPolicy.IMAGENET, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__(interpolation=interpolation, fill=fill) + self.policy = policy + self._policies = self._get_policies(policy) + + def _get_policies( + self, policy: AutoAugmentPolicy + ) -> list[tuple[tuple[str, float, Optional[int]], tuple[str, float, Optional[int]]]]: + if policy == AutoAugmentPolicy.IMAGENET: + return [ + (("Posterize", 0.4, 8), ("Rotate", 0.6, 9)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + (("Posterize", 0.6, 7), ("Posterize", 0.6, 6)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Equalize", 0.4, None), ("Rotate", 0.8, 8)), + (("Solarize", 0.6, 3), ("Equalize", 0.6, None)), + (("Posterize", 0.8, 5), ("Equalize", 1.0, None)), + (("Rotate", 0.2, 3), ("Solarize", 0.6, 8)), + (("Equalize", 0.6, None), ("Posterize", 0.4, 6)), + (("Rotate", 0.8, 8), ("Color", 0.4, 0)), + (("Rotate", 0.4, 9), ("Equalize", 0.6, None)), + (("Equalize", 0.0, None), ("Equalize", 0.8, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Rotate", 0.8, 8), ("Color", 1.0, 2)), + (("Color", 0.8, 8), ("Solarize", 0.8, 7)), + (("Sharpness", 0.4, 7), ("Invert", 0.6, None)), + (("ShearX", 0.6, 5), ("Equalize", 1.0, None)), + (("Color", 0.4, 0), ("Equalize", 0.6, None)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + ] + elif policy == AutoAugmentPolicy.CIFAR10: + return [ + (("Invert", 0.1, None), ("Contrast", 0.2, 6)), + (("Rotate", 0.7, 2), ("TranslateX", 0.3, 9)), + (("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)), + (("ShearY", 0.5, 8), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.5, None), ("Equalize", 0.9, None)), + (("ShearY", 0.2, 7), ("Posterize", 0.3, 7)), + (("Color", 0.4, 3), ("Brightness", 0.6, 7)), + (("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)), + (("Equalize", 0.6, None), ("Equalize", 0.5, None)), + (("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)), + (("Color", 0.7, 7), ("TranslateX", 0.5, 8)), + (("Equalize", 0.3, None), ("AutoContrast", 0.4, None)), + (("TranslateY", 0.4, 3), ("Sharpness", 0.2, 6)), + (("Brightness", 0.9, 6), ("Color", 0.2, 8)), + (("Solarize", 0.5, 2), ("Invert", 0.0, None)), + (("Equalize", 0.2, None), ("AutoContrast", 0.6, None)), + (("Equalize", 0.2, None), ("Equalize", 0.6, None)), + (("Color", 0.9, 9), ("Equalize", 0.6, None)), + (("AutoContrast", 0.8, None), ("Solarize", 0.2, 8)), + (("Brightness", 0.1, 3), ("Color", 0.7, 0)), + (("Solarize", 0.4, 5), ("AutoContrast", 0.9, None)), + (("TranslateY", 0.9, 9), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.9, None), ("Solarize", 0.8, 3)), + (("Equalize", 0.8, None), ("Invert", 0.1, None)), + (("TranslateY", 0.7, 9), ("AutoContrast", 0.9, None)), + ] + elif policy == AutoAugmentPolicy.SVHN: + return [ + (("ShearX", 0.9, 4), ("Invert", 0.2, None)), + (("ShearY", 0.9, 8), ("Invert", 0.7, None)), + (("Equalize", 0.6, None), ("Solarize", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("AutoContrast", 0.8, None)), + (("ShearY", 0.9, 8), ("Invert", 0.4, None)), + (("ShearY", 0.9, 5), ("Solarize", 0.2, 6)), + (("Invert", 0.9, None), ("AutoContrast", 0.8, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("Solarize", 0.3, 3)), + (("ShearY", 0.8, 8), ("Invert", 0.7, None)), + (("Equalize", 0.9, None), ("TranslateY", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Contrast", 0.3, 3), ("Rotate", 0.8, 4)), + (("Invert", 0.8, None), ("TranslateY", 0.0, 2)), + (("ShearY", 0.7, 6), ("Solarize", 0.4, 8)), + (("Invert", 0.6, None), ("Rotate", 0.8, 4)), + (("ShearY", 0.3, 7), ("TranslateX", 0.9, 3)), + (("ShearX", 0.1, 6), ("Invert", 0.6, None)), + (("Solarize", 0.7, 2), ("TranslateY", 0.6, 7)), + (("ShearY", 0.8, 4), ("Invert", 0.8, None)), + (("ShearX", 0.7, 9), ("TranslateY", 0.8, 3)), + (("ShearY", 0.8, 5), ("AutoContrast", 0.7, None)), + (("ShearX", 0.7, 2), ("Invert", 0.1, None)), + ] + else: + raise ValueError(f"The provided policy {policy} is not recognized.") + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(image_or_video) # type: ignore[arg-type] + + policy = self._policies[int(torch.randint(len(self._policies), ()))] + + for transform_id, probability, magnitude_idx in policy: + if not torch.rand(()) <= probability: + continue + + magnitudes_fn, signed = self._AUGMENTATION_SPACE[transform_id] + + magnitudes = magnitudes_fn(10, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[magnitude_idx]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + + image_or_video = self._apply_image_or_video_transform( + image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill + ) + + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video) + + +class RandAugment(_AutoAugmentBase): + r"""RandAugment data augmentation method based on + `"RandAugment: Practical automated data augmentation with a reduced search space" + `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_ops (int, optional): Number of augmentation transformations to apply sequentially, + must be non-negative integer. Default: 2. + magnitude (int, optional): Magnitude for all the transformations. + num_magnitude_bins (int, optional): The number of different magnitude values. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.RandAugment + _AUGMENTATION_SPACE = { + "Identity": (lambda num_bins, height, width: None, False), + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * width, num_bins), + True, + ), + "TranslateY": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * height, num_bins), + True, + ), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + } + + def __init__( + self, + num_ops: int = 2, + magnitude: int = 9, + num_magnitude_bins: int = 31, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__(interpolation=interpolation, fill=fill) + if not isinstance(num_ops, int) or (num_ops < 0): + raise ValueError(f"num_ops should be a non-negative integer, but got {num_ops} instead.") + self.num_ops = num_ops + self.magnitude = magnitude + self.num_magnitude_bins = num_magnitude_bins + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(image_or_video) # type: ignore[arg-type] + + for _ in range(self.num_ops): + transform_id, (magnitudes_fn, signed) = self._get_random_item(self._AUGMENTATION_SPACE) + magnitudes = magnitudes_fn(self.num_magnitude_bins, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[self.magnitude]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + image_or_video = self._apply_image_or_video_transform( + image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill + ) + + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video) + + +class TrivialAugmentWide(_AutoAugmentBase): + r"""Dataset-independent data-augmentation with TrivialAugment Wide, as described in + `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_magnitude_bins (int, optional): The number of different magnitude values. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.TrivialAugmentWide + _AUGMENTATION_SPACE = { + "Identity": (lambda num_bins, height, width: None, False), + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "TranslateX": (lambda num_bins, height, width: torch.linspace(0.0, 32.0, num_bins), True), + "TranslateY": (lambda num_bins, height, width: torch.linspace(0.0, 32.0, num_bins), True), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 135.0, num_bins), True), + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 6))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + } + + def __init__( + self, + num_magnitude_bins: int = 31, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ): + super().__init__(interpolation=interpolation, fill=fill) + self.num_magnitude_bins = num_magnitude_bins + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(image_or_video) # type: ignore[arg-type] + + transform_id, (magnitudes_fn, signed) = self._get_random_item(self._AUGMENTATION_SPACE) + + magnitudes = magnitudes_fn(self.num_magnitude_bins, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[int(torch.randint(self.num_magnitude_bins, ()))]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + + image_or_video = self._apply_image_or_video_transform( + image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill + ) + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video) + + +class AugMix(_AutoAugmentBase): + r"""AugMix data augmentation method based on + `"AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty" `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + severity (int, optional): The severity of base augmentation operators. Default is ``3``. + mixture_width (int, optional): The number of augmentation chains. Default is ``3``. + chain_depth (int, optional): The depth of augmentation chains. A negative value denotes stochastic depth sampled from the interval [1, 3]. + Default is ``-1``. + alpha (float, optional): The hyperparameter for the probability distributions. Default is ``1.0``. + all_ops (bool, optional): Use all operations (including brightness, contrast, color and sharpness). Default is ``True``. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.AugMix + + _PARTIAL_AUGMENTATION_SPACE = { + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (lambda num_bins, height, width: torch.linspace(0.0, width / 3.0, num_bins), True), + "TranslateY": (lambda num_bins, height, width: torch.linspace(0.0, height / 3.0, num_bins), True), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (4 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + } + _AUGMENTATION_SPACE: dict[str, tuple[Callable[[int, int, int], Optional[torch.Tensor]], bool]] = { + **_PARTIAL_AUGMENTATION_SPACE, + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + } + + def __init__( + self, + severity: int = 3, + mixture_width: int = 3, + chain_depth: int = -1, + alpha: float = 1.0, + all_ops: bool = True, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__(interpolation=interpolation, fill=fill) + self._PARAMETER_MAX = 10 + if not (1 <= severity <= self._PARAMETER_MAX): + raise ValueError(f"The severity must be between [1, {self._PARAMETER_MAX}]. Got {severity} instead.") + self.severity = severity + self.mixture_width = mixture_width + self.chain_depth = chain_depth + self.alpha = alpha + self.all_ops = all_ops + + def _sample_dirichlet(self, params: torch.Tensor) -> torch.Tensor: + # Must be on a separate method so that we can overwrite it in tests. + return torch._sample_dirichlet(params) + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, orig_image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(orig_image_or_video) # type: ignore[arg-type] + + if isinstance(orig_image_or_video, torch.Tensor): + image_or_video = orig_image_or_video + else: # isinstance(inpt, PIL.Image.Image): + image_or_video = F.pil_to_tensor(orig_image_or_video) + + augmentation_space = self._AUGMENTATION_SPACE if self.all_ops else self._PARTIAL_AUGMENTATION_SPACE + + orig_dims = list(image_or_video.shape) + expected_ndim = 5 if isinstance(orig_image_or_video, tv_tensors.Video) else 4 + batch = image_or_video.reshape([1] * max(expected_ndim - image_or_video.ndim, 0) + orig_dims) + batch_dims = [batch.size(0)] + [1] * (batch.ndim - 1) + + # Sample the beta weights for combining the original and augmented image or video. To get Beta, we use a + # Dirichlet with 2 parameters. The 1st column stores the weights of the original and the 2nd the ones of + # augmented image or video. + m = self._sample_dirichlet( + torch.tensor([self.alpha, self.alpha], device=batch.device).expand(batch_dims[0], -1) + ) + + # Sample the mixing weights and combine them with the ones sampled from Beta for the augmented images or videos. + combined_weights = self._sample_dirichlet( + torch.tensor([self.alpha] * self.mixture_width, device=batch.device).expand(batch_dims[0], -1) + ) * m[:, 1].reshape([batch_dims[0], -1]) + + mix = m[:, 0].reshape(batch_dims) * batch + for i in range(self.mixture_width): + aug = batch + depth = self.chain_depth if self.chain_depth > 0 else int(torch.randint(low=1, high=4, size=(1,)).item()) + for _ in range(depth): + transform_id, (magnitudes_fn, signed) = self._get_random_item(augmentation_space) + + magnitudes = magnitudes_fn(self._PARAMETER_MAX, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[int(torch.randint(self.severity, ()))]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + + aug = self._apply_image_or_video_transform(aug, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill) # type: ignore[assignment] + mix.add_(combined_weights[:, i].reshape(batch_dims) * aug) + mix = mix.reshape(orig_dims).to(dtype=image_or_video.dtype) + + if isinstance(orig_image_or_video, (tv_tensors.Image, tv_tensors.Video)): + mix = tv_tensors.wrap(mix, like=orig_image_or_video) + elif isinstance(orig_image_or_video, PIL.Image.Image): + mix = F.to_pil_image(mix) + + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, mix) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_color.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_color.py new file mode 100644 index 0000000000000000000000000000000000000000..bf4ae55d23222073704fc3473e589f07c7254c43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_color.py @@ -0,0 +1,377 @@ +import collections.abc +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torchvision import transforms as _transforms +from torchvision.transforms.v2 import functional as F, Transform + +from ._transform import _RandomApplyTransform +from ._utils import query_chw + + +class Grayscale(Transform): + """Convert images or videos to grayscale. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 3 or 1, H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + num_output_channels (int): (1 or 3) number of channels desired for output image + """ + + _v1_transform_cls = _transforms.Grayscale + + def __init__(self, num_output_channels: int = 1): + super().__init__() + self.num_output_channels = num_output_channels + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.rgb_to_grayscale, inpt, num_output_channels=self.num_output_channels) + + +class RandomGrayscale(_RandomApplyTransform): + """Randomly convert image or videos to grayscale with a probability of p (default 0.1). + + If the input is a :class:`torch.Tensor`, it is expected to have [..., 3 or 1, H, W] shape, + where ... means an arbitrary number of leading dimensions + + The output has the same number of channels as the input. + + Args: + p (float): probability that image should be converted to grayscale. + """ + + _v1_transform_cls = _transforms.RandomGrayscale + + def __init__(self, p: float = 0.1) -> None: + super().__init__(p=p) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + num_input_channels, *_ = query_chw(flat_inputs) + return dict(num_input_channels=num_input_channels) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.rgb_to_grayscale, inpt, num_output_channels=params["num_input_channels"]) + + +class RGB(Transform): + """Convert images or videos to RGB (if they are already not RGB). + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions + """ + + def __init__(self): + super().__init__() + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.grayscale_to_rgb, inpt) + + +class ColorJitter(Transform): + """Randomly change the brightness, contrast, saturation and hue of an image or video. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported. + + Args: + brightness (float or tuple of float (min, max)): How much to jitter brightness. + brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness] + or the given [min, max]. Should be non negative numbers. + contrast (float or tuple of float (min, max)): How much to jitter contrast. + contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast] + or the given [min, max]. Should be non-negative numbers. + saturation (float or tuple of float (min, max)): How much to jitter saturation. + saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation] + or the given [min, max]. Should be non negative numbers. + hue (float or tuple of float (min, max)): How much to jitter hue. + hue_factor is chosen uniformly from [-hue, hue] or the given [min, max]. + Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5. + To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + """ + + _v1_transform_cls = _transforms.ColorJitter + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + return {attr: value or 0 for attr, value in super()._extract_params_for_v1_transform().items()} + + def __init__( + self, + brightness: Optional[Union[float, Sequence[float]]] = None, + contrast: Optional[Union[float, Sequence[float]]] = None, + saturation: Optional[Union[float, Sequence[float]]] = None, + hue: Optional[Union[float, Sequence[float]]] = None, + ) -> None: + super().__init__() + self.brightness = self._check_input(brightness, "brightness") + self.contrast = self._check_input(contrast, "contrast") + self.saturation = self._check_input(saturation, "saturation") + self.hue = self._check_input(hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False) + + def _check_input( + self, + value: Optional[Union[float, Sequence[float]]], + name: str, + center: float = 1.0, + bound: tuple[float, float] = (0, float("inf")), + clip_first_on_zero: bool = True, + ) -> Optional[tuple[float, float]]: + if value is None: + return None + + if isinstance(value, (int, float)): + if value < 0: + raise ValueError(f"If {name} is a single number, it must be non negative.") + value = [center - value, center + value] + if clip_first_on_zero: + value[0] = max(value[0], 0.0) + elif isinstance(value, collections.abc.Sequence) and len(value) == 2: + value = [float(v) for v in value] + else: + raise TypeError(f"{name}={value} should be a single number or a sequence with length 2.") + + if not bound[0] <= value[0] <= value[1] <= bound[1]: + raise ValueError(f"{name} values should be between {bound} and increasing, but got {value}.") + + return None if value[0] == value[1] == center else (float(value[0]), float(value[1])) + + @staticmethod + def _generate_value(left: float, right: float) -> float: + return torch.empty(1).uniform_(left, right).item() + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + fn_idx = torch.randperm(4) + + b = None if self.brightness is None else self._generate_value(self.brightness[0], self.brightness[1]) + c = None if self.contrast is None else self._generate_value(self.contrast[0], self.contrast[1]) + s = None if self.saturation is None else self._generate_value(self.saturation[0], self.saturation[1]) + h = None if self.hue is None else self._generate_value(self.hue[0], self.hue[1]) + + return dict(fn_idx=fn_idx, brightness_factor=b, contrast_factor=c, saturation_factor=s, hue_factor=h) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + output = inpt + brightness_factor = params["brightness_factor"] + contrast_factor = params["contrast_factor"] + saturation_factor = params["saturation_factor"] + hue_factor = params["hue_factor"] + for fn_id in params["fn_idx"]: + if fn_id == 0 and brightness_factor is not None: + output = self._call_kernel(F.adjust_brightness, output, brightness_factor=brightness_factor) + elif fn_id == 1 and contrast_factor is not None: + output = self._call_kernel(F.adjust_contrast, output, contrast_factor=contrast_factor) + elif fn_id == 2 and saturation_factor is not None: + output = self._call_kernel(F.adjust_saturation, output, saturation_factor=saturation_factor) + elif fn_id == 3 and hue_factor is not None: + output = self._call_kernel(F.adjust_hue, output, hue_factor=hue_factor) + return output + + +class RandomChannelPermutation(Transform): + """Randomly permute the channels of an image or video""" + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + num_channels, *_ = query_chw(flat_inputs) + return dict(permutation=torch.randperm(num_channels)) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.permute_channels, inpt, params["permutation"]) + + +class RandomPhotometricDistort(Transform): + """Randomly distorts the image or video as used in `SSD: Single Shot + MultiBox Detector `_. + + This transform relies on :class:`~torchvision.transforms.v2.ColorJitter` + under the hood to adjust the contrast, saturation, hue, brightness, and also + randomly permutes channels. + + Args: + brightness (tuple of float (min, max), optional): How much to jitter brightness. + brightness_factor is chosen uniformly from [min, max]. Should be non negative numbers. + contrast (tuple of float (min, max), optional): How much to jitter contrast. + contrast_factor is chosen uniformly from [min, max]. Should be non-negative numbers. + saturation (tuple of float (min, max), optional): How much to jitter saturation. + saturation_factor is chosen uniformly from [min, max]. Should be non negative numbers. + hue (tuple of float (min, max), optional): How much to jitter hue. + hue_factor is chosen uniformly from [min, max]. Should have -0.5 <= min <= max <= 0.5. + To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + p (float, optional) probability each distortion operation (contrast, saturation, ...) to be applied. + Default is 0.5. + """ + + def __init__( + self, + brightness: tuple[float, float] = (0.875, 1.125), + contrast: tuple[float, float] = (0.5, 1.5), + saturation: tuple[float, float] = (0.5, 1.5), + hue: tuple[float, float] = (-0.05, 0.05), + p: float = 0.5, + ): + super().__init__() + self.brightness = brightness + self.contrast = contrast + self.hue = hue + self.saturation = saturation + self.p = p + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + num_channels, *_ = query_chw(flat_inputs) + params: dict[str, Any] = { + key: ColorJitter._generate_value(range[0], range[1]) if torch.rand(1) < self.p else None + for key, range in [ + ("brightness_factor", self.brightness), + ("contrast_factor", self.contrast), + ("saturation_factor", self.saturation), + ("hue_factor", self.hue), + ] + } + params["contrast_before"] = bool(torch.rand(()) < 0.5) + params["channel_permutation"] = torch.randperm(num_channels) if torch.rand(1) < self.p else None + return params + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if params["brightness_factor"] is not None: + inpt = self._call_kernel(F.adjust_brightness, inpt, brightness_factor=params["brightness_factor"]) + if params["contrast_factor"] is not None and params["contrast_before"]: + inpt = self._call_kernel(F.adjust_contrast, inpt, contrast_factor=params["contrast_factor"]) + if params["saturation_factor"] is not None: + inpt = self._call_kernel(F.adjust_saturation, inpt, saturation_factor=params["saturation_factor"]) + if params["hue_factor"] is not None: + inpt = self._call_kernel(F.adjust_hue, inpt, hue_factor=params["hue_factor"]) + if params["contrast_factor"] is not None and not params["contrast_before"]: + inpt = self._call_kernel(F.adjust_contrast, inpt, contrast_factor=params["contrast_factor"]) + if params["channel_permutation"] is not None: + inpt = self._call_kernel(F.permute_channels, inpt, permutation=params["channel_permutation"]) + return inpt + + +class RandomEqualize(_RandomApplyTransform): + """Equalize the histogram of the given image or video with a given probability. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + + Args: + p (float): probability of the image being equalized. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomEqualize + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.equalize, inpt) + + +class RandomInvert(_RandomApplyTransform): + """Inverts the colors of the given image or video with a given probability. + + If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being color inverted. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomInvert + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.invert, inpt) + + +class RandomPosterize(_RandomApplyTransform): + """Posterize the image or video with a given probability by reducing the + number of bits for each color channel. + + If the input is a :class:`torch.Tensor`, it should be of type torch.uint8, + and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + bits (int): number of bits to keep for each channel (0-8) + p (float): probability of the image being posterized. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomPosterize + + def __init__(self, bits: int, p: float = 0.5) -> None: + super().__init__(p=p) + self.bits = bits + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.posterize, inpt, bits=self.bits) + + +class RandomSolarize(_RandomApplyTransform): + """Solarize the image or video with a given probability by inverting all pixel + values above a threshold. + + If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + threshold (float): all pixels equal or above this value are inverted. + p (float): probability of the image being solarized. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomSolarize + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + params["threshold"] = float(params["threshold"]) + return params + + def __init__(self, threshold: float, p: float = 0.5) -> None: + super().__init__(p=p) + self.threshold = threshold + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.solarize, inpt, threshold=self.threshold) + + +class RandomAutocontrast(_RandomApplyTransform): + """Autocontrast the pixels of the given image or video with a given probability. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being autocontrasted. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomAutocontrast + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.autocontrast, inpt) + + +class RandomAdjustSharpness(_RandomApplyTransform): + """Adjust the sharpness of the image or video with a given probability. + + If the input is a :class:`torch.Tensor`, + it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + sharpness_factor (float): How much to adjust the sharpness. Can be + any non-negative number. 0 gives a blurred image, 1 gives the + original image while 2 increases the sharpness by a factor of 2. + p (float): probability of the image being sharpened. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomAdjustSharpness + + def __init__(self, sharpness_factor: float, p: float = 0.5) -> None: + super().__init__(p=p) + self.sharpness_factor = sharpness_factor + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.adjust_sharpness, inpt, sharpness_factor=self.sharpness_factor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_container.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_container.py new file mode 100644 index 0000000000000000000000000000000000000000..95ec25a22f84501ac6ca7520f70db63b5a0f5084 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_container.py @@ -0,0 +1,180 @@ +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import torch + +from torch import nn +from torchvision import transforms as _transforms +from torchvision.transforms.v2 import Transform + + +class Compose(Transform): + """Composes several transforms together. + + This transform does not support torchscript. + Please, see the note below. + + Args: + transforms (list of ``Transform`` objects): list of transforms to compose. + + Example: + >>> transforms.Compose([ + >>> transforms.CenterCrop(10), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> ]) + + .. note:: + In order to script the transformations, please use ``torch.nn.Sequential`` as below. + + >>> transforms = torch.nn.Sequential( + >>> transforms.CenterCrop(10), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> ) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + """ + + def __init__(self, transforms: Sequence[Callable]) -> None: + super().__init__() + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence of callables") + elif not transforms: + raise ValueError("Pass at least one transform") + self.transforms = transforms + + def forward(self, *inputs: Any) -> Any: + needs_unpacking = len(inputs) > 1 + for transform in self.transforms: + outputs = transform(*inputs) + inputs = outputs if needs_unpacking else (outputs,) + return outputs + + def extra_repr(self) -> str: + format_string = [] + for t in self.transforms: + format_string.append(f" {t}") + return "\n".join(format_string) + + +class RandomApply(Transform): + """Apply randomly a list of transformations with a given probability. + + .. note:: + In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of + transforms as shown below: + + >>> transforms = transforms.RandomApply(torch.nn.ModuleList([ + >>> transforms.ColorJitter(), + >>> ]), p=0.3) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + p (float): probability of applying the list of transforms + """ + + _v1_transform_cls = _transforms.RandomApply + + def __init__(self, transforms: Union[Sequence[Callable], nn.ModuleList], p: float = 0.5) -> None: + super().__init__() + + if not isinstance(transforms, (Sequence, nn.ModuleList)): + raise TypeError("Argument transforms should be a sequence of callables or a `nn.ModuleList`") + elif not transforms: + raise ValueError("Pass at least one transform") + self.transforms = transforms + + if not (0.0 <= p <= 1.0): + raise ValueError("`p` should be a floating point value in the interval [0.0, 1.0].") + self.p = p + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + return {"transforms": self.transforms, "p": self.p} + + def forward(self, *inputs: Any) -> Any: + needs_unpacking = len(inputs) > 1 + + if torch.rand(1) >= self.p: + return inputs if needs_unpacking else inputs[0] + + for transform in self.transforms: + outputs = transform(*inputs) + inputs = outputs if needs_unpacking else (outputs,) + return outputs + + def extra_repr(self) -> str: + format_string = [] + for t in self.transforms: + format_string.append(f" {t}") + return "\n".join(format_string) + + +class RandomChoice(Transform): + """Apply single transformation randomly picked from a list. + + This transform does not support torchscript. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + p (list of floats or None, optional): probability of each transform being picked. + If ``p`` doesn't sum to 1, it is automatically normalized. If ``None`` + (default), all transforms have the same probability. + """ + + def __init__( + self, + transforms: Sequence[Callable], + p: Optional[list[float]] = None, + ) -> None: + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence of callables") + elif not transforms: + raise ValueError("Pass at least one transform") + if p is None: + p = [1] * len(transforms) + elif len(p) != len(transforms): + raise ValueError(f"Length of p doesn't match the number of transforms: {len(p)} != {len(transforms)}") + + super().__init__() + + self.transforms = transforms + total = sum(p) + self.p = [prob / total for prob in p] + + def forward(self, *inputs: Any) -> Any: + idx = int(torch.multinomial(torch.tensor(self.p), 1)) + transform = self.transforms[idx] + return transform(*inputs) + + +class RandomOrder(Transform): + """Apply a list of transformations in a random order. + + This transform does not support torchscript. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + """ + + def __init__(self, transforms: Sequence[Callable]) -> None: + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence of callables") + elif not transforms: + raise ValueError("Pass at least one transform") + super().__init__() + self.transforms = transforms + + def forward(self, *inputs: Any) -> Any: + needs_unpacking = len(inputs) > 1 + for idx in torch.randperm(len(self.transforms)): + transform = self.transforms[idx] + outputs = transform(*inputs) + inputs = outputs if needs_unpacking else (outputs,) + return outputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_deprecated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..4e7d6170d4f4c48678027e75cbb246cf250b587a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_deprecated.py @@ -0,0 +1,50 @@ +import warnings +from typing import Any, Union + +import numpy as np +import PIL.Image +import torch +from torchvision.transforms import functional as _F + +from torchvision.transforms.v2 import Transform + + +class ToTensor(Transform): + """[DEPRECATED] Use ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`` instead. + + Convert a PIL Image or ndarray to tensor and scale the values accordingly. + + .. warning:: + :class:`v2.ToTensor` is deprecated and will be removed in a future release. + Please use instead ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])``. + Output is equivalent up to float precision. + + This transform does not support torchscript. + + + Converts a PIL Image or numpy.ndarray (H x W x C) in the range + [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] + if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1) + or if the numpy.ndarray has dtype = np.uint8 + + In the other cases, tensors are returned without scaling. + + .. note:: + Because the input image is scaled to [0.0, 1.0], this transformation should not be used when + transforming target image masks. See the `references`_ for implementing the transforms for image masks. + + .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation + """ + + _transformed_types = (PIL.Image.Image, np.ndarray) + + def __init__(self) -> None: + warnings.warn( + "The transform `ToTensor()` is deprecated and will be removed in a future release. " + "Instead, please use `v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`." + "Output is equivalent up to float precision." + ) + super().__init__() + + def transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: dict[str, Any]) -> torch.Tensor: + return _F.to_tensor(inpt) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_geometry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..1418a6b4953fc27745e68b17d9ede29ba17c57f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_geometry.py @@ -0,0 +1,1417 @@ +import math +import numbers +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Literal, Optional, Union + +import PIL.Image +import torch + +from torchvision import transforms as _transforms, tv_tensors +from torchvision.ops.boxes import box_iou +from torchvision.transforms.functional import _get_perspective_coeffs +from torchvision.transforms.v2 import functional as F, InterpolationMode, Transform +from torchvision.transforms.v2.functional._utils import _FillType + +from ._transform import _RandomApplyTransform +from ._utils import ( + _check_padding_arg, + _check_padding_mode_arg, + _check_sequence_input, + _get_fill, + _setup_angle, + _setup_fill_arg, + _setup_number_or_seq, + _setup_size, + get_bounding_boxes, + has_all, + has_any, + is_pure_tensor, + query_size, +) + + +class RandomHorizontalFlip(_RandomApplyTransform): + """Horizontally flip the input with a given probability. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + p (float, optional): probability of the input being flipped. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomHorizontalFlip + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.horizontal_flip, inpt) + + +class RandomVerticalFlip(_RandomApplyTransform): + """Vertically flip the input with a given probability. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + p (float, optional): probability of the input being flipped. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomVerticalFlip + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.vertical_flip, inpt) + + +class Resize(Transform): + """Resize the input to the given size. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + size (sequence, int, or None): Desired + output size. + + - If size is a sequence like (h, w), output size will be matched to this. + - If size is an int, smaller edge of the image will be matched to this + number. i.e, if height > width, then image will be rescaled to + (size * height / width, size). + - If size is None, the output shape is determined by the ``max_size`` + parameter. + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + max_size (int, optional): The maximum allowed for the longer edge of + the resized image. + + - If ``size`` is an int: if the longer edge of the image is greater + than ``max_size`` after being resized according to ``size``, + ``size`` will be overruled so that the longer edge is equal to + ``max_size``. As a result, the smaller edge may be shorter than + ``size``. This is only supported if ``size`` is an int (or a + sequence of length 1 in torchscript mode). + - If ``size`` is None: the longer edge of the image will be matched + to max_size. i.e, if height > width, then image will be rescaled + to (max_size, max_size * width / height). + + This should be left to ``None`` (default) when ``size`` is a + sequence. + + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + _v1_transform_cls = _transforms.Resize + + def __init__( + self, + size: Union[int, Sequence[int], None], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + + if isinstance(size, int): + size = [size] + elif isinstance(size, Sequence) and len(size) in {1, 2}: + size = list(size) + elif size is None: + if not isinstance(max_size, int): + raise ValueError(f"max_size must be an integer when size is None, but got {max_size} instead.") + else: + raise ValueError( + f"size can be an integer, a sequence of one or two integers, or None, but got {size} instead." + ) + self.size = size + + self.interpolation = interpolation + self.max_size = max_size + self.antialias = antialias + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, + inpt, + self.size, + interpolation=self.interpolation, + max_size=self.max_size, + antialias=self.antialias, + ) + + +class CenterCrop(Transform): + """Crop the input at the center. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + """ + + _v1_transform_cls = _transforms.CenterCrop + + def __init__(self, size: Union[int, Sequence[int]]): + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.center_crop, inpt, output_size=self.size) + + +class RandomResizedCrop(Transform): + """Crop a random portion of the input and resize it to a given size. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + A crop of the original input is made: the crop has a random area (H * W) + and a random aspect ratio. This crop is finally resized to the given + size. This is popularly used to train the Inception networks. + + Args: + size (int or sequence): expected output size of the crop, for each edge. If size is an + int instead of sequence like (h, w), a square output size ``(size, size)`` is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + scale (tuple of float, optional): Specifies the lower and upper bounds for the random area of the crop, + before resizing. The scale is defined with respect to the area of the original image. + ratio (tuple of float, optional): lower and upper bounds for the random aspect ratio of the crop, before + resizing. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + _v1_transform_cls = _transforms.RandomResizedCrop + + def __init__( + self, + size: Union[int, Sequence[int]], + scale: tuple[float, float] = (0.08, 1.0), + ratio: tuple[float, float] = (3.0 / 4.0, 4.0 / 3.0), + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + if not isinstance(scale, Sequence) or len(scale) != 2: + raise TypeError("Scale should be a sequence of two floats.") + if not isinstance(ratio, Sequence) or len(ratio) != 2: + raise TypeError("Ratio should be a sequence of two floats.") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + + self.scale = scale + self.ratio = ratio + self.interpolation = interpolation + self.antialias = antialias + + self._log_ratio = torch.log(torch.tensor(self.ratio)) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + height, width = query_size(flat_inputs) + area = height * width + + log_ratio = self._log_ratio + for _ in range(10): + target_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item() + aspect_ratio = torch.exp( + torch.empty(1).uniform_( + log_ratio[0], # type: ignore[arg-type] + log_ratio[1], # type: ignore[arg-type] + ) + ).item() + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + if 0 < w <= width and 0 < h <= height: + i = torch.randint(0, height - h + 1, size=(1,)).item() + j = torch.randint(0, width - w + 1, size=(1,)).item() + break + else: + # Fallback to central crop + in_ratio = float(width) / float(height) + if in_ratio < min(self.ratio): + w = width + h = int(round(w / min(self.ratio))) + elif in_ratio > max(self.ratio): + h = height + w = int(round(h * max(self.ratio))) + else: # whole image + w = width + h = height + i = (height - h) // 2 + j = (width - w) // 2 + + return dict(top=i, left=j, height=h, width=w) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resized_crop, inpt, **params, size=self.size, interpolation=self.interpolation, antialias=self.antialias + ) + + +class FiveCrop(Transform): + """Crop the image or video into four corners and the central crop. + + If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a + :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions. + For example, the image can have ``[..., C, H, W]`` shape. + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an ``int`` + instead of sequence like (h, w), a square crop of size (size, size) is made. + If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + Example: + >>> class BatchMultiCrop(transforms.Transform): + ... def forward(self, sample: Tuple[Tuple[Union[tv_tensors.Image, tv_tensors.Video], ...], int]): + ... images_or_videos, labels = sample + ... batch_size = len(images_or_videos) + ... image_or_video = images_or_videos[0] + ... images_or_videos = tv_tensors.wrap(torch.stack(images_or_videos), like=image_or_video) + ... labels = torch.full((batch_size,), label, device=images_or_videos.device) + ... return images_or_videos, labels + ... + >>> image = tv_tensors.Image(torch.rand(3, 256, 256)) + >>> label = 3 + >>> transform = transforms.Compose([transforms.FiveCrop(224), BatchMultiCrop()]) + >>> images, labels = transform(image, label) + >>> images.shape + torch.Size([5, 3, 224, 224]) + >>> labels + tensor([3, 3, 3, 3, 3]) + """ + + _v1_transform_cls = _transforms.FiveCrop + + def __init__(self, size: Union[int, Sequence[int]]) -> None: + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, tv_tensors.Mask)): + warnings.warn( + f"{type(self).__name__}() is currently passing through inputs of type " + f"tv_tensors.{type(inpt).__name__}. This will likely change in the future." + ) + return super()._call_kernel(functional, inpt, *args, **kwargs) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.five_crop, inpt, self.size) + + def check_inputs(self, flat_inputs: list[Any]) -> None: + if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask): + raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()") + + +class TenCrop(Transform): + """Crop the image or video into four corners and the central crop plus the flipped version of + these (horizontal flipping is used by default). + + If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a + :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions. + For example, the image can have ``[..., C, H, W]`` shape. + + See :class:`~torchvision.transforms.v2.FiveCrop` for an example. + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + vertical_flip (bool, optional): Use vertical flipping instead of horizontal + """ + + _v1_transform_cls = _transforms.TenCrop + + def __init__(self, size: Union[int, Sequence[int]], vertical_flip: bool = False) -> None: + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + self.vertical_flip = vertical_flip + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, tv_tensors.Mask)): + warnings.warn( + f"{type(self).__name__}() is currently passing through inputs of type " + f"tv_tensors.{type(inpt).__name__}. This will likely change in the future." + ) + return super()._call_kernel(functional, inpt, *args, **kwargs) + + def check_inputs(self, flat_inputs: list[Any]) -> None: + if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask): + raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.ten_crop, inpt, self.size, vertical_flip=self.vertical_flip) + + +class Pad(Transform): + """Pad the input on all sides with the given "pad" value. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + padding (int or sequence): Padding on each border. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is "constant". + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + _v1_transform_cls = _transforms.Pad + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + + if not (params["fill"] is None or isinstance(params["fill"], (int, float))): + raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.") + + return params + + def __init__( + self, + padding: Union[int, Sequence[int]], + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant", + ) -> None: + super().__init__() + + _check_padding_arg(padding) + _check_padding_mode_arg(padding_mode) + + # This cast does Sequence[int] -> List[int] and is required to make mypy happy + if not isinstance(padding, int): + padding = list(padding) + self.padding = padding + self.fill = fill + self._fill = _setup_fill_arg(fill) + self.padding_mode = padding_mode + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel(F.pad, inpt, padding=self.padding, fill=fill, padding_mode=self.padding_mode) # type: ignore[arg-type] + + +class RandomZoomOut(_RandomApplyTransform): + """ "Zoom out" transformation from + `"SSD: Single Shot MultiBox Detector" `_. + + This transformation randomly pads images, videos, bounding boxes and masks creating a zoom out effect. + Output spatial size is randomly sampled from original size up to a maximum size configured + with ``side_range`` parameter: + + .. code-block:: python + + r = uniform_sample(side_range[0], side_range[1]) + output_width = input_width * r + output_height = input_height * r + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + side_range (sequence of floats, optional): tuple of two floats defines minimum and maximum factors to + scale the input size. + p (float, optional): probability that the zoom operation will be performed. + """ + + def __init__( + self, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + side_range: Sequence[float] = (1.0, 4.0), + p: float = 0.5, + ) -> None: + super().__init__(p=p) + + self.fill = fill + self._fill = _setup_fill_arg(fill) + + _check_sequence_input(side_range, "side_range", req_sizes=(2,)) + + self.side_range = side_range + if side_range[0] < 1.0 or side_range[0] > side_range[1]: + raise ValueError(f"Invalid side range provided {side_range}.") + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_h, orig_w = query_size(flat_inputs) + + r = self.side_range[0] + torch.rand(1) * (self.side_range[1] - self.side_range[0]) + canvas_width = int(orig_w * r) + canvas_height = int(orig_h * r) + + r = torch.rand(2) + left = int((canvas_width - orig_w) * r[0]) + top = int((canvas_height - orig_h) * r[1]) + right = canvas_width - (left + orig_w) + bottom = canvas_height - (top + orig_h) + padding = [left, top, right, bottom] + + return dict(padding=padding) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel(F.pad, inpt, **params, fill=fill) + + +class RandomRotation(Transform): + """Rotate the input by angle. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be [-degrees, +degrees]. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + expand (bool, optional): Optional expansion flag. + If true, expands the output to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center (see note below) and no translation. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + + .. note:: + + In theory, setting ``center`` has no effect if ``expand=True``, since the image center will become the + center of rotation. In practice however, due to numerical precision, this can lead to off-by-one + differences of the resulting image size compared to using the image center in the first place. Thus, when + setting ``expand=True``, it's best to leave ``center=None`` (default). + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + _v1_transform_cls = _transforms.RandomRotation + + def __init__( + self, + degrees: Union[numbers.Number, Sequence], + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + ) -> None: + super().__init__() + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + self.interpolation = interpolation + self.expand = expand + + self.fill = fill + self._fill = _setup_fill_arg(fill) + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item() + return dict(angle=angle) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.rotate, + inpt, + **params, + interpolation=self.interpolation, + expand=self.expand, + center=self.center, + fill=fill, + ) + + +class RandomAffine(Transform): + """Random affine transformation the input keeping center invariant. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees). Set to 0 to deactivate rotations. + translate (tuple, optional): tuple of maximum absolute fraction for horizontal + and vertical translations. For example translate=(a, b), then horizontal shift + is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is + randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default. + scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is + randomly sampled from the range a <= scale <= b. Will keep original scale by default. + shear (sequence or number, optional): Range of degrees to select from. + If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear) + will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the + range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values, + an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied. + Will not apply shear by default. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + _v1_transform_cls = _transforms.RandomAffine + + def __init__( + self, + degrees: Union[numbers.Number, Sequence], + translate: Optional[Sequence[float]] = None, + scale: Optional[Sequence[float]] = None, + shear: Optional[Union[int, float, Sequence[float]]] = None, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + center: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + if translate is not None: + _check_sequence_input(translate, "translate", req_sizes=(2,)) + for t in translate: + if not (0.0 <= t <= 1.0): + raise ValueError("translation values should be between 0 and 1") + self.translate = translate + if scale is not None: + _check_sequence_input(scale, "scale", req_sizes=(2,)) + for s in scale: + if s <= 0: + raise ValueError("scale values should be positive") + self.scale = scale + + if shear is not None: + self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4)) + else: + self.shear = shear + + self.interpolation = interpolation + self.fill = fill + self._fill = _setup_fill_arg(fill) + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + height, width = query_size(flat_inputs) + + angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item() + if self.translate is not None: + max_dx = float(self.translate[0] * width) + max_dy = float(self.translate[1] * height) + tx = int(round(torch.empty(1).uniform_(-max_dx, max_dx).item())) + ty = int(round(torch.empty(1).uniform_(-max_dy, max_dy).item())) + translate = (tx, ty) + else: + translate = (0, 0) + + if self.scale is not None: + scale = torch.empty(1).uniform_(self.scale[0], self.scale[1]).item() + else: + scale = 1.0 + + shear_x = shear_y = 0.0 + if self.shear is not None: + shear_x = torch.empty(1).uniform_(self.shear[0], self.shear[1]).item() + if len(self.shear) == 4: + shear_y = torch.empty(1).uniform_(self.shear[2], self.shear[3]).item() + + shear = (shear_x, shear_y) + return dict(angle=angle, translate=translate, scale=scale, shear=shear) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.affine, + inpt, + **params, + interpolation=self.interpolation, + fill=fill, + center=self.center, + ) + + +class RandomCrop(Transform): + """Crop the input at a random location. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + padding (int or sequence, optional): Optional padding on each border + of the image, applied before cropping. Default is None. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + pad_if_needed (boolean, optional): It will pad the image if smaller than the + desired size to avoid raising an exception. Since cropping is done + after padding, the padding seems to be done at a random offset. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + _v1_transform_cls = _transforms.RandomCrop + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + + if not (params["fill"] is None or isinstance(params["fill"], (int, float))): + raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.") + + padding = self.padding + if padding is not None: + pad_left, pad_right, pad_top, pad_bottom = padding + padding = [pad_left, pad_top, pad_right, pad_bottom] + params["padding"] = padding + + return params + + def __init__( + self, + size: Union[int, Sequence[int]], + padding: Optional[Union[int, Sequence[int]]] = None, + pad_if_needed: bool = False, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant", + ) -> None: + super().__init__() + + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + if pad_if_needed or padding is not None: + if padding is not None: + _check_padding_arg(padding) + _check_padding_mode_arg(padding_mode) + + self.padding = F._geometry._parse_pad_padding(padding) if padding else None # type: ignore[arg-type] + self.pad_if_needed = pad_if_needed + self.fill = fill + self._fill = _setup_fill_arg(fill) + self.padding_mode = padding_mode + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + padded_height, padded_width = query_size(flat_inputs) + + if self.padding is not None: + pad_left, pad_right, pad_top, pad_bottom = self.padding + padded_height += pad_top + pad_bottom + padded_width += pad_left + pad_right + else: + pad_left = pad_right = pad_top = pad_bottom = 0 + + cropped_height, cropped_width = self.size + + if self.pad_if_needed: + if padded_height < cropped_height: + diff = cropped_height - padded_height + + pad_top += diff + pad_bottom += diff + padded_height += 2 * diff + + if padded_width < cropped_width: + diff = cropped_width - padded_width + + pad_left += diff + pad_right += diff + padded_width += 2 * diff + + if padded_height < cropped_height or padded_width < cropped_width: + raise ValueError( + f"Required crop size {(cropped_height, cropped_width)} is larger than " + f"{'padded ' if self.padding is not None else ''}input image size {(padded_height, padded_width)}." + ) + + # We need a different order here than we have in self.padding since this padding will be parsed again in `F.pad` + padding = [pad_left, pad_top, pad_right, pad_bottom] + needs_pad = any(padding) + + needs_vert_crop, top = ( + (True, int(torch.randint(0, padded_height - cropped_height + 1, size=()))) + if padded_height > cropped_height + else (False, 0) + ) + needs_horz_crop, left = ( + (True, int(torch.randint(0, padded_width - cropped_width + 1, size=()))) + if padded_width > cropped_width + else (False, 0) + ) + + return dict( + needs_crop=needs_vert_crop or needs_horz_crop, + top=top, + left=left, + height=cropped_height, + width=cropped_width, + needs_pad=needs_pad, + padding=padding, + ) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if params["needs_pad"]: + fill = _get_fill(self._fill, type(inpt)) + inpt = self._call_kernel(F.pad, inpt, padding=params["padding"], fill=fill, padding_mode=self.padding_mode) + + if params["needs_crop"]: + inpt = self._call_kernel( + F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"] + ) + + return inpt + + +class RandomPerspective(_RandomApplyTransform): + """Perform a random perspective transformation of the input with a given probability. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + distortion_scale (float, optional): argument to control the degree of distortion and ranges from 0 to 1. + Default is 0.5. + p (float, optional): probability of the input being transformed. Default is 0.5. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + """ + + _v1_transform_cls = _transforms.RandomPerspective + + def __init__( + self, + distortion_scale: float = 0.5, + p: float = 0.5, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + ) -> None: + super().__init__(p=p) + + if not (0 <= distortion_scale <= 1): + raise ValueError("Argument distortion_scale value should be between 0 and 1") + + self.distortion_scale = distortion_scale + self.interpolation = interpolation + self.fill = fill + self._fill = _setup_fill_arg(fill) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + height, width = query_size(flat_inputs) + + distortion_scale = self.distortion_scale + + half_height = height // 2 + half_width = width // 2 + bound_height = int(distortion_scale * half_height) + 1 + bound_width = int(distortion_scale * half_width) + 1 + topleft = [ + int(torch.randint(0, bound_width, size=(1,))), + int(torch.randint(0, bound_height, size=(1,))), + ] + topright = [ + int(torch.randint(width - bound_width, width, size=(1,))), + int(torch.randint(0, bound_height, size=(1,))), + ] + botright = [ + int(torch.randint(width - bound_width, width, size=(1,))), + int(torch.randint(height - bound_height, height, size=(1,))), + ] + botleft = [ + int(torch.randint(0, bound_width, size=(1,))), + int(torch.randint(height - bound_height, height, size=(1,))), + ] + startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]] + endpoints = [topleft, topright, botright, botleft] + perspective_coeffs = _get_perspective_coeffs(startpoints, endpoints) + return dict(coefficients=perspective_coeffs) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.perspective, + inpt, + startpoints=None, + endpoints=None, + fill=fill, + interpolation=self.interpolation, + **params, + ) + + +class ElasticTransform(Transform): + """Transform the input with elastic transformations. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Given alpha and sigma, it will generate displacement + vectors for all pixels based on random offsets. Alpha controls the strength + and sigma controls the smoothness of the displacements. + The displacements are added to an identity grid and the resulting grid is + used to transform the input. + + .. note:: + Implementation to transform bounding boxes is approximative (not exact). + We construct an approximation of the inverse grid as ``inverse_grid = identity - displacement``. + This is not an exact inverse of the grid used to transform images, i.e. ``grid = identity + displacement``. + Our assumption is that ``displacement * displacement`` is small and can be ignored. + Large displacements would lead to large errors in the approximation. + + Applications: + Randomly transforms the morphology of objects in images and produces a + see-through-water-like effect. + + Args: + alpha (float or sequence of floats, optional): Magnitude of displacements. Default is 50.0. + sigma (float or sequence of floats, optional): Smoothness of displacements. Default is 5.0. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + """ + + _v1_transform_cls = _transforms.ElasticTransform + + def __init__( + self, + alpha: Union[float, Sequence[float]] = 50.0, + sigma: Union[float, Sequence[float]] = 5.0, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + ) -> None: + super().__init__() + self.alpha = _setup_number_or_seq(alpha, "alpha") + self.sigma = _setup_number_or_seq(sigma, "sigma") + + self.interpolation = interpolation + self.fill = fill + self._fill = _setup_fill_arg(fill) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + size = list(query_size(flat_inputs)) + + dx = torch.rand([1, 1] + size) * 2 - 1 + if self.sigma[0] > 0.0: + kx = int(8 * self.sigma[0] + 1) + # if kernel size is even we have to make it odd + if kx % 2 == 0: + kx += 1 + dx = self._call_kernel(F.gaussian_blur, dx, [kx, kx], list(self.sigma)) + dx = dx * self.alpha[0] / size[0] + + dy = torch.rand([1, 1] + size) * 2 - 1 + if self.sigma[1] > 0.0: + ky = int(8 * self.sigma[1] + 1) + # if kernel size is even we have to make it odd + if ky % 2 == 0: + ky += 1 + dy = self._call_kernel(F.gaussian_blur, dy, [ky, ky], list(self.sigma)) + dy = dy * self.alpha[1] / size[1] + displacement = torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2 + return dict(displacement=displacement) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.elastic, + inpt, + **params, + fill=fill, + interpolation=self.interpolation, + ) + + +class RandomIoUCrop(Transform): + """Random IoU crop transformation from + `"SSD: Single Shot MultiBox Detector" `_. + + This transformation requires an image or video data and ``tv_tensors.BoundingBoxes`` in the input. + + .. warning:: + In order to properly remove the bounding boxes below the IoU threshold, `RandomIoUCrop` + must be followed by :class:`~torchvision.transforms.v2.SanitizeBoundingBoxes`, either immediately + after or later in the transforms pipeline. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + min_scale (float, optional): Minimum factors to scale the input size. + max_scale (float, optional): Maximum factors to scale the input size. + min_aspect_ratio (float, optional): Minimum aspect ratio for the cropped image or video. + max_aspect_ratio (float, optional): Maximum aspect ratio for the cropped image or video. + sampler_options (list of float, optional): List of minimal IoU (Jaccard) overlap between all the boxes and + a cropped image or video. Default, ``None`` which corresponds to ``[0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]`` + trials (int, optional): Number of trials to find a crop for a given value of minimal IoU (Jaccard) overlap. + Default, 40. + """ + + def __init__( + self, + min_scale: float = 0.3, + max_scale: float = 1.0, + min_aspect_ratio: float = 0.5, + max_aspect_ratio: float = 2.0, + sampler_options: Optional[list[float]] = None, + trials: int = 40, + ): + super().__init__() + # Configuration similar to https://github.com/weiliu89/caffe/blob/ssd/examples/ssd/ssd_coco.py#L89-L174 + self.min_scale = min_scale + self.max_scale = max_scale + self.min_aspect_ratio = min_aspect_ratio + self.max_aspect_ratio = max_aspect_ratio + if sampler_options is None: + sampler_options = [0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0] + self.options = sampler_options + self.trials = trials + + def check_inputs(self, flat_inputs: list[Any]) -> None: + if not ( + has_all(flat_inputs, tv_tensors.BoundingBoxes) + and has_any(flat_inputs, PIL.Image.Image, tv_tensors.Image, is_pure_tensor) + ): + raise TypeError( + f"{type(self).__name__}() requires input sample to contain tensor or PIL images " + "and bounding boxes. Sample can also contain masks." + ) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_h, orig_w = query_size(flat_inputs) + bboxes = get_bounding_boxes(flat_inputs) + + while True: + # sample an option + idx = int(torch.randint(low=0, high=len(self.options), size=(1,))) + min_jaccard_overlap = self.options[idx] + if min_jaccard_overlap >= 1.0: # a value larger than 1 encodes the leave as-is option + return dict() + + for _ in range(self.trials): + # check the aspect ratio limitations + r = self.min_scale + (self.max_scale - self.min_scale) * torch.rand(2) + new_w = int(orig_w * r[0]) + new_h = int(orig_h * r[1]) + aspect_ratio = new_w / new_h + if not (self.min_aspect_ratio <= aspect_ratio <= self.max_aspect_ratio): + continue + + # check for 0 area crops + r = torch.rand(2) + left = int((orig_w - new_w) * r[0]) + top = int((orig_h - new_h) * r[1]) + right = left + new_w + bottom = top + new_h + if left == right or top == bottom: + continue + + # check for any valid boxes with centers within the crop area + xyxy_bboxes = F.convert_bounding_box_format( + bboxes.as_subclass(torch.Tensor), + bboxes.format, + tv_tensors.BoundingBoxFormat.XYXY, + ) + cx = 0.5 * (xyxy_bboxes[..., 0] + xyxy_bboxes[..., 2]) + cy = 0.5 * (xyxy_bboxes[..., 1] + xyxy_bboxes[..., 3]) + is_within_crop_area = (left < cx) & (cx < right) & (top < cy) & (cy < bottom) + if not is_within_crop_area.any(): + continue + + # check at least 1 box with jaccard limitations + xyxy_bboxes = xyxy_bboxes[is_within_crop_area] + ious = box_iou( + xyxy_bboxes, + torch.tensor([[left, top, right, bottom]], dtype=xyxy_bboxes.dtype, device=xyxy_bboxes.device), + ) + if ious.max() < min_jaccard_overlap: + continue + + return dict(top=top, left=left, height=new_h, width=new_w, is_within_crop_area=is_within_crop_area) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + + if len(params) < 1: + return inpt + + output = self._call_kernel( + F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"] + ) + + if isinstance(output, tv_tensors.BoundingBoxes): + # We "mark" the invalid boxes as degenreate, and they can be + # removed by a later call to SanitizeBoundingBoxes() + output[~params["is_within_crop_area"]] = 0 + + return output + + +class ScaleJitter(Transform): + """Perform Large Scale Jitter on the input according to + `"Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation" `_. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + target_size (tuple of int): Target size. This parameter defines base scale for jittering, + e.g. ``min(target_size[0] / width, target_size[1] / height)``. + scale_range (tuple of float, optional): Minimum and maximum of the scale range. Default, ``(0.1, 2.0)``. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + target_size: tuple[int, int], + scale_range: tuple[float, float] = (0.1, 2.0), + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ): + super().__init__() + self.target_size = target_size + self.scale_range = scale_range + self.interpolation = interpolation + self.antialias = antialias + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_height, orig_width = query_size(flat_inputs) + + scale = self.scale_range[0] + torch.rand(1) * (self.scale_range[1] - self.scale_range[0]) + r = min(self.target_size[1] / orig_height, self.target_size[0] / orig_width) * scale + new_width = int(orig_width * r) + new_height = int(orig_height * r) + + return dict(size=(new_height, new_width)) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias + ) + + +class RandomShortestSize(Transform): + """Randomly resize the input. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + min_size (int or sequence of int): Minimum spatial size. Single integer value or a sequence of integer values. + max_size (int, optional): Maximum spatial size. Default, None. + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + min_size: Union[list[int], tuple[int], int], + max_size: Optional[int] = None, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ): + super().__init__() + self.min_size = [min_size] if isinstance(min_size, int) else list(min_size) + self.max_size = max_size + self.interpolation = interpolation + self.antialias = antialias + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_height, orig_width = query_size(flat_inputs) + + min_size = self.min_size[int(torch.randint(len(self.min_size), ()))] + r = min_size / min(orig_height, orig_width) + if self.max_size is not None: + r = min(r, self.max_size / max(orig_height, orig_width)) + + new_width = int(orig_width * r) + new_height = int(orig_height * r) + + return dict(size=(new_height, new_width)) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias + ) + + +class RandomResize(Transform): + """Randomly resize the input. + + This transformation can be used together with ``RandomCrop`` as data augmentations to train + models on image segmentation task. + + Output spatial size is randomly sampled from the interval ``[min_size, max_size]``: + + .. code-block:: python + + size = uniform_sample(min_size, max_size) + output_width = size + output_height = size + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + min_size (int): Minimum output size for random sampling + max_size (int): Maximum output size for random sampling + interpolation (InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + min_size: int, + max_size: int, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.min_size = min_size + self.max_size = max_size + self.interpolation = interpolation + self.antialias = antialias + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + size = int(torch.randint(self.min_size, self.max_size, ())) + return dict(size=[size]) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, inpt, params["size"], interpolation=self.interpolation, antialias=self.antialias + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_meta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..39f223f0398c836b9d109faf817526376fece7d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_meta.py @@ -0,0 +1,81 @@ +from typing import Any, Union + +from torchvision import tv_tensors +from torchvision.transforms.v2 import functional as F, Transform +from torchvision.tv_tensors._bounding_boxes import CLAMPING_MODE_TYPE + + +class ConvertBoundingBoxFormat(Transform): + """Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY". + + Args: + format (str or tv_tensors.BoundingBoxFormat): output bounding box format. + Possible values are defined by :class:`~torchvision.tv_tensors.BoundingBoxFormat` and + string values match the enums, e.g. "XYXY" or "XYWH" etc. + """ + + _transformed_types = (tv_tensors.BoundingBoxes,) + + def __init__(self, format: Union[str, tv_tensors.BoundingBoxFormat]) -> None: + super().__init__() + self.format = format + + def transform(self, inpt: tv_tensors.BoundingBoxes, params: dict[str, Any]) -> tv_tensors.BoundingBoxes: + return F.convert_bounding_box_format(inpt, new_format=self.format) # type: ignore[return-value, arg-type] + + +class ClampBoundingBoxes(Transform): + """Clamp bounding boxes to their corresponding image dimensions. + + Args: + clamping_mode: Default is "auto" which relies on the input box' + ``clamping_mode`` attribute. Read more in :ref:`clamping_mode_tuto` + for more details on how to use this transform. + """ + + def __init__(self, clamping_mode: Union[CLAMPING_MODE_TYPE, str] = "auto") -> None: + super().__init__() + self.clamping_mode = clamping_mode + + _transformed_types = (tv_tensors.BoundingBoxes,) + + def transform(self, inpt: tv_tensors.BoundingBoxes, params: dict[str, Any]) -> tv_tensors.BoundingBoxes: + return F.clamp_bounding_boxes(inpt, clamping_mode=self.clamping_mode) # type: ignore[return-value] + + +class ClampKeyPoints(Transform): + """Clamp keypoints to their corresponding image dimensions. + + The clamping is done according to the keypoints' ``canvas_size`` meta-data. + """ + + _transformed_types = (tv_tensors.KeyPoints,) + + def transform(self, inpt: tv_tensors.KeyPoints, params: dict[str, Any]) -> tv_tensors.KeyPoints: + return F.clamp_keypoints(inpt) # type: ignore[return-value] + + +class SetClampingMode(Transform): + """Sets the ``clamping_mode`` attribute of the bounding boxes for future transforms. + + + + Args: + clamping_mode: The clamping mode to set. Possible values are: "soft", + "hard", or ``None``. Read more in :ref:`clamping_mode_tuto` for more + details on how to use this transform. + """ + + def __init__(self, clamping_mode: CLAMPING_MODE_TYPE) -> None: + super().__init__() + self.clamping_mode = clamping_mode + + if self.clamping_mode not in (None, "soft", "hard"): + raise ValueError(f"clamping_mode must be soft, hard or None, got {clamping_mode}") + + _transformed_types = (tv_tensors.BoundingBoxes,) + + def transform(self, inpt: tv_tensors.BoundingBoxes, params: dict[str, Any]) -> tv_tensors.BoundingBoxes: + out: tv_tensors.BoundingBoxes = inpt.clone() # type: ignore[assignment] + out.clamping_mode = self.clamping_mode + return out diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_misc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..305149c87b115a7e6789979c224c71c53645d596 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_misc.py @@ -0,0 +1,570 @@ +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import PIL.Image + +import torch +from torch.utils._pytree import tree_flatten, tree_unflatten + +from torchvision import transforms as _transforms, tv_tensors +from torchvision.transforms.v2 import functional as F, Transform + +from ._utils import ( + _parse_labels_getter, + _setup_number_or_seq, + _setup_size, + get_bounding_boxes, + get_keypoints, + has_any, + is_pure_tensor, +) + + +# TODO: do we want/need to expose this? +class Identity(Transform): + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return inpt + + +class Lambda(Transform): + """Apply a user-defined function as a transform. + + This transform does not support torchscript. + + Args: + lambd (function): Lambda/function to be used for transform. + """ + + _transformed_types = (object,) + + def __init__(self, lambd: Callable[[Any], Any], *types: type): + super().__init__() + self.lambd = lambd + self.types = types or self._transformed_types + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if isinstance(inpt, self.types): + return self.lambd(inpt) + else: + return inpt + + def extra_repr(self) -> str: + extras = [] + name = getattr(self.lambd, "__name__", None) + if name: + extras.append(name) + extras.append(f"types={[type.__name__ for type in self.types]}") + return ", ".join(extras) + + +class LinearTransformation(Transform): + """Transform a tensor image or video with a square transformation matrix and a mean_vector computed offline. + + This transform does not support PIL Image. + Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and + subtract mean_vector from it which is then followed by computing the dot + product with the transformation matrix and then reshaping the tensor to its + original shape. + + Applications: + whitening transformation: Suppose X is a column vector zero-centered data. + Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X), + perform SVD on this matrix and pass it as transformation_matrix. + + Args: + transformation_matrix (Tensor): tensor [D x D], D = C x H x W + mean_vector (Tensor): tensor [D], D = C x H x W + """ + + _v1_transform_cls = _transforms.LinearTransformation + + _transformed_types = (is_pure_tensor, tv_tensors.Image, tv_tensors.Video) + + def __init__(self, transformation_matrix: torch.Tensor, mean_vector: torch.Tensor): + super().__init__() + if transformation_matrix.size(0) != transformation_matrix.size(1): + raise ValueError( + "transformation_matrix should be square. Got " + f"{tuple(transformation_matrix.size())} rectangular matrix." + ) + + if mean_vector.size(0) != transformation_matrix.size(0): + raise ValueError( + f"mean_vector should have the same length {mean_vector.size(0)}" + f" as any one of the dimensions of the transformation_matrix [{tuple(transformation_matrix.size())}]" + ) + + if transformation_matrix.device != mean_vector.device: + raise ValueError( + f"Input tensors should be on the same device. Got {transformation_matrix.device} and {mean_vector.device}" + ) + + if transformation_matrix.dtype != mean_vector.dtype: + raise ValueError( + f"Input tensors should have the same dtype. Got {transformation_matrix.dtype} and {mean_vector.dtype}" + ) + + self.transformation_matrix = transformation_matrix + self.mean_vector = mean_vector + + def check_inputs(self, sample: Any) -> Any: + if has_any(sample, PIL.Image.Image): + raise TypeError(f"{type(self).__name__}() does not support PIL images.") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + shape = inpt.shape + n = shape[-3] * shape[-2] * shape[-1] + if n != self.transformation_matrix.shape[0]: + raise ValueError( + "Input tensor and transformation matrix have incompatible shape." + + f"[{shape[-3]} x {shape[-2]} x {shape[-1]}] != " + + f"{self.transformation_matrix.shape[0]}" + ) + + if inpt.device.type != self.mean_vector.device.type: + raise ValueError( + "Input tensor should be on the same device as transformation matrix and mean vector. " + f"Got {inpt.device} vs {self.mean_vector.device}" + ) + + flat_inpt = inpt.reshape(-1, n) - self.mean_vector + + transformation_matrix = self.transformation_matrix.to(flat_inpt.dtype) + output = torch.mm(flat_inpt, transformation_matrix) + output = output.reshape(shape) + + if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + output = tv_tensors.wrap(output, like=inpt) + return output + + +class Normalize(Transform): + """Normalize a tensor image or video with mean and standard deviation. + + This transform does not support PIL Image. + Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n`` + channels, this transform will normalize each channel of the input + ``torch.*Tensor`` i.e., + ``output[channel] = (input[channel] - mean[channel]) / std[channel]`` + + .. note:: + This transform acts out of place, i.e., it does not mutate the input tensor. + + Args: + mean (sequence): Sequence of means for each channel. + std (sequence): Sequence of standard deviations for each channel. + inplace(bool,optional): Bool to make this operation in-place. + + """ + + _v1_transform_cls = _transforms.Normalize + + def __init__(self, mean: Sequence[float], std: Sequence[float], inplace: bool = False): + super().__init__() + self.mean = list(mean) + self.std = list(std) + self.inplace = inplace + + def check_inputs(self, sample: Any) -> Any: + if has_any(sample, PIL.Image.Image): + raise TypeError(f"{type(self).__name__}() does not support PIL images.") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.normalize, inpt, mean=self.mean, std=self.std, inplace=self.inplace) + + +class GaussianBlur(Transform): + """Blurs image with randomly chosen Gaussian blur kernel. + + The convolution will be using reflection padding corresponding to the kernel size, to maintain the input shape. + + If the input is a Tensor, it is expected + to have [..., C, H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + kernel_size (int or sequence): Size of the Gaussian kernel. + sigma (float or tuple of float (min, max)): Standard deviation to be used for + creating kernel to perform blurring. If float, sigma is fixed. If it is tuple + of float (min, max), sigma is chosen uniformly at random to lie in the + given range. + """ + + _v1_transform_cls = _transforms.GaussianBlur + + def __init__( + self, kernel_size: Union[int, Sequence[int]], sigma: Union[int, float, Sequence[float]] = (0.1, 2.0) + ) -> None: + super().__init__() + self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers") + for ks in self.kernel_size: + if ks <= 0 or ks % 2 == 0: + raise ValueError("Kernel size value should be an odd and positive number.") + + self.sigma = _setup_number_or_seq(sigma, "sigma") + + if not 0.0 < self.sigma[0] <= self.sigma[1]: + raise ValueError(f"sigma values should be positive and of the form (min, max). Got {self.sigma}") + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + sigma = torch.empty(1).uniform_(self.sigma[0], self.sigma[1]).item() + return dict(sigma=[sigma, sigma]) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.gaussian_blur, inpt, self.kernel_size, **params) + + +class GaussianNoise(Transform): + """Add gaussian noise to images or videos. + + The input tensor is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + Each image or frame in a batch will be transformed independently i.e. the + noise added to each image will be different. + + The input tensor is also expected to be of float dtype in ``[0, 1]``, + or of ``uint8`` dtype in ``[0, 255]``. This transform does not support PIL + images. + + Regardless of the dtype used, the parameters of the function use the same + scale, so a ``mean`` parameter of 0.5 will result in an average value + increase of 0.5 units for float images, and an average increase of 127.5 + units for ``uint8`` images. + + Args: + mean (float): Mean of the sampled normal distribution. Default is 0. + sigma (float): Standard deviation of the sampled normal distribution. Default is 0.1. + clip (bool, optional): Whether to clip the values after adding noise, be it to + ``[0, 1]`` for floats or to ``[0, 255]`` for ``uint8``. Setting this parameter to + ``False`` may cause unsigned integer overflows with uint8 inputs. + Default is True. + """ + + def __init__(self, mean: float = 0.0, sigma: float = 0.1, clip=True) -> None: + super().__init__() + self.mean = mean + self.sigma = sigma + self.clip = clip + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.gaussian_noise, inpt, mean=self.mean, sigma=self.sigma, clip=self.clip) + + +class ToDtype(Transform): + """Converts the input to a specific dtype, optionally scaling the values for images or videos. + + .. note:: + ``ToDtype(dtype, scale=True)`` is the recommended replacement for ``ConvertImageDtype(dtype)``. + + Args: + dtype (``torch.dtype`` or dict of ``TVTensor`` -> ``torch.dtype``): The dtype to convert to. + If a ``torch.dtype`` is passed, e.g. ``torch.float32``, only images and videos will be converted + to that dtype: this is for compatibility with :class:`~torchvision.transforms.v2.ConvertImageDtype`. + A dict can be passed to specify per-tv_tensor conversions, e.g. + ``dtype={tv_tensors.Image: torch.float32, tv_tensors.Mask: torch.int64, "others":None}``. The "others" + key can be used as a catch-all for any other tv_tensor type, and ``None`` means no conversion. + scale (bool, optional): Whether to scale the values for images or videos. See :ref:`range_and_dtype`. + Default: ``False``. + """ + + _transformed_types = (torch.Tensor,) + + def __init__( + self, dtype: Union[torch.dtype, dict[Union[type, str], Optional[torch.dtype]]], scale: bool = False + ) -> None: + super().__init__() + + if not isinstance(dtype, (dict, torch.dtype)): + raise ValueError(f"dtype must be a dict or a torch.dtype, got {type(dtype)} instead") + + if ( + isinstance(dtype, dict) + and torch.Tensor in dtype + and any(cls in dtype for cls in [tv_tensors.Image, tv_tensors.Video]) + ): + warnings.warn( + "Got `dtype` values for `torch.Tensor` and either `tv_tensors.Image` or `tv_tensors.Video`. " + "Note that a plain `torch.Tensor` will *not* be transformed by this (or any other transformation) " + "in case a `tv_tensors.Image` or `tv_tensors.Video` is present in the input." + ) + self.dtype = dtype + self.scale = scale + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if isinstance(self.dtype, torch.dtype): + # For consistency / BC with ConvertImageDtype, we only care about images or videos when dtype + # is a simple torch.dtype + if not is_pure_tensor(inpt) and not isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + return inpt + + dtype: Optional[torch.dtype] = self.dtype + elif type(inpt) in self.dtype: + dtype = self.dtype[type(inpt)] + elif "others" in self.dtype: + dtype = self.dtype["others"] + else: + raise ValueError( + f"No dtype was specified for type {type(inpt)}. " + "If you only need to convert the dtype of images or videos, you can just pass e.g. dtype=torch.float32. " + "If you're passing a dict as dtype, " + 'you can use "others" as a catch-all key ' + 'e.g. dtype={tv_tensors.Mask: torch.int64, "others": None} to pass-through the rest of the inputs.' + ) + + supports_scaling = is_pure_tensor(inpt) or isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) + if dtype is None: + if self.scale and supports_scaling: + warnings.warn( + "scale was set to True but no dtype was specified for images or videos: no scaling will be done." + ) + return inpt + + return self._call_kernel(F.to_dtype, inpt, dtype=dtype, scale=self.scale) + + +class ConvertImageDtype(Transform): + """[DEPRECATED] Use ``v2.ToDtype(dtype, scale=True)`` instead. + + Convert input image to the given ``dtype`` and scale the values accordingly. + + .. warning:: + Consider using ``ToDtype(dtype, scale=True)`` instead. See :class:`~torchvision.transforms.v2.ToDtype`. + + This function does not support PIL Image. + + Args: + dtype (torch.dtype): Desired data type of the output + + .. note:: + + When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. + If converted back and forth, this mismatch has no effect. + + Raises: + RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as + well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to + overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range + of the integer ``dtype``. + """ + + _v1_transform_cls = _transforms.ConvertImageDtype + + def __init__(self, dtype: torch.dtype = torch.float32) -> None: + super().__init__() + self.dtype = dtype + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.to_dtype, inpt, dtype=self.dtype, scale=True) + + +class SanitizeBoundingBoxes(Transform): + """Remove degenerate/invalid bounding boxes and their corresponding labels and masks. + + This transform removes bounding boxes and their associated labels/masks that: + + - are below a given ``min_size`` or ``min_area``: by default this also removes degenerate boxes that have e.g. X2 <= X1. + - have any coordinate outside of their corresponding image. You may want to + call :class:`~torchvision.transforms.v2.ClampBoundingBoxes` first to avoid undesired removals. + + It can also sanitize other tensors like the "iscrowd" or "area" properties from COCO + (see ``labels_getter`` parameter). + + .. note:: + **Mask handling**: This transform automatically detects and sanitizes per-instance masks + (shape ``[N, H, W]`` where N matches the number of bounding boxes). Semantic segmentation masks + (shape ``[H, W]``) or masks with mismatched dimensions are passed through unchanged. + You do not need to add masks to ``labels_getter`` for them to be sanitized. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. It is critical to call this transform if + :class:`~torchvision.transforms.v2.RandomIoUCrop` was called. + If you want to be extra careful, you may call it after all transforms that + may modify bounding boxes but once at the end should be enough in most + cases. + + Args: + min_size (float, optional): The size below which bounding boxes are removed. Default is 1. + min_area (float, optional): The area below which bounding boxes are removed. Default is 1. + labels_getter (callable or str or None, optional): indicates how to identify the labels in the input + (or anything else that needs to be sanitized along with the bounding boxes). + By default, this will try to find a "labels" key in the input (case-insensitive), if + the input is a dict or it is a tuple whose second element is a dict. + This heuristic should work well with a lot of datasets, including the built-in torchvision datasets. + + It can also be a callable that takes the same input as the transform, and returns either: + + - A single tensor (the labels) + - A tuple/list of tensors, each of which will be subject to the same sanitization as the bounding boxes. + This is useful to sanitize multiple tensors like the labels, and the "iscrowd" or "area" properties + from COCO. + + If ``labels_getter`` is None then only bounding boxes are sanitized. + """ + + def __init__( + self, + min_size: float = 1.0, + min_area: float = 1.0, + labels_getter: Union[Callable[[Any], Any], str, None] = "default", + ) -> None: + super().__init__() + + if min_size < 1: + raise ValueError(f"min_size must be >= 1, got {min_size}.") + self.min_size = min_size + + if min_area < 1: + raise ValueError(f"min_area must be >= 1, got {min_area}.") + self.min_area = min_area + + self.labels_getter = labels_getter + self._labels_getter = _parse_labels_getter(labels_getter) + + def forward(self, *inputs: Any) -> Any: + inputs = inputs if len(inputs) > 1 else inputs[0] + + labels = self._labels_getter(inputs) + if labels is not None: + msg = "The labels in the input to forward() must be a tensor or None, got {type} instead." + if isinstance(labels, torch.Tensor): + labels = (labels,) + elif isinstance(labels, (tuple, list)): + for entry in labels: + if not isinstance(entry, torch.Tensor): + # TODO: we don't need to enforce tensors, just that entries are indexable as t[bool_mask] + raise ValueError(msg.format(type=type(entry))) + else: + raise ValueError(msg.format(type=type(labels))) + + flat_inputs, spec = tree_flatten(inputs) + boxes = get_bounding_boxes(flat_inputs) + + if labels is not None: + for label in labels: + if boxes.shape[0] != label.shape[0]: + raise ValueError( + f"Number of boxes (shape={boxes.shape}) and must match the number of labels." + f"Found labels with shape={label.shape})." + ) + + valid = F._misc._get_sanitize_bounding_boxes_mask( + boxes, + format=boxes.format, + canvas_size=boxes.canvas_size, + min_size=self.min_size, + min_area=self.min_area, + ) + + params = dict(valid=valid, labels=labels) + flat_outputs = [self.transform(inpt, params) for inpt in flat_inputs] + + return tree_unflatten(flat_outputs, spec) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + is_label = params["labels"] is not None and any(inpt is label for label in params["labels"]) + is_bounding_boxes = isinstance(inpt, tv_tensors.BoundingBoxes) + is_mask = isinstance(inpt, tv_tensors.Mask) + + if not (is_label or is_bounding_boxes or is_mask): + return inpt + + try: + output = inpt[params["valid"]] + except (IndexError): + # If indexing fails (e.g., shape mismatch), pass through unchanged + return inpt + + if is_label: + return output + else: + return tv_tensors.wrap(output, like=inpt) + + +class SanitizeKeyPoints(Transform): + """Remove keypoints outside of the image area and their corresponding labels (if any). + + This transform removes keypoints or groups of keypoints and their associated labels that + have coordinates outside of their corresponding image. + If you would instead like to clamp such keypoints to the image edges, use + :class:`~torchvision.transforms.v2.ClampKeyPoints`. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. + + Keypoints can be passed as a set of individual keypoints or as a set of objects + (e.g., polygons or polygonal chains) consisting of a fixed number of keypoints of shape ``[..., 2]``. + When groups of keypoints are passed (i.e., an at least 3-dimensional tensor), this transform + will only remove entire groups, not individual keypoints within a group. + + Args: + labels_getter (callable or str or None, optional): indicates how to identify the labels in the input + (or anything else that needs to be sanitized along with the keypoints). + If set to the string ``"default"``, this will try to find a "labels" key in the input (case-insensitive), if + the input is a dict or it is a tuple whose second element is a dict. + + It can also be a callable that takes the same input as the transform, and returns either: + + - A single tensor (the labels) + - A tuple/list of tensors, each of which will be subject to the same sanitization as the keypoints. + + If ``labels_getter`` is None (the default), then only keypoints are sanitized. + """ + + def __init__( + self, + labels_getter: Union[Callable[[Any], Any], str, None] = None, + ) -> None: + super().__init__() + self.labels_getter = labels_getter + self._labels_getter = _parse_labels_getter(labels_getter) + + def forward(self, *inputs: Any) -> Any: + inputs = inputs if len(inputs) > 1 else inputs[0] + + labels = self._labels_getter(inputs) + if labels is not None: + msg = "The labels in the input to forward() must be a tensor or None, got {type} instead." + if isinstance(labels, torch.Tensor): + labels = (labels,) + elif isinstance(labels, (tuple, list)): + for entry in labels: + if not isinstance(entry, torch.Tensor): + # TODO: we don't need to enforce tensors, just that entries are indexable as t[bool_mask] + raise ValueError(msg.format(type=type(entry))) + else: + raise ValueError(msg.format(type=type(labels))) + + flat_inputs, spec = tree_flatten(inputs) + points = get_keypoints(flat_inputs) + + if labels is not None: + for label in labels: + if points.shape[0] != label.shape[0]: + raise ValueError( + f"Number of kepyoints (shape={points.shape}) must match the number of labels." + f"Found labels with shape={label.shape})." + ) + + valid = F._misc._get_sanitize_keypoints_mask( + points, + canvas_size=points.canvas_size, + ) + + params = dict(valid=valid, labels=labels) + flat_outputs = [self.transform(inpt, params) for inpt in flat_inputs] + + return tree_unflatten(flat_outputs, spec) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + is_label = params["labels"] is not None and any(inpt is label for label in params["labels"]) + is_keypoints = isinstance(inpt, tv_tensors.KeyPoints) + + if not (is_label or is_keypoints): + return inpt + + output = inpt[params["valid"]] + + if is_label: + return output + else: + return tv_tensors.wrap(output, like=inpt) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_temporal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_temporal.py new file mode 100644 index 0000000000000000000000000000000000000000..0642a741e35ae8bb2a3f2b825b7b921fd9548dad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_temporal.py @@ -0,0 +1,26 @@ +from typing import Any + +import torch +from torchvision.transforms.v2 import functional as F, Transform + + +class UniformTemporalSubsample(Transform): + """Uniformly subsample ``num_samples`` indices from the temporal dimension of the video. + + Videos are expected to be of shape ``[..., T, C, H, W]`` where ``T`` denotes the temporal dimension. + + When ``num_samples`` is larger than the size of temporal dimension of the video, it + will sample frames based on nearest neighbor interpolation. + + Args: + num_samples (int): The number of equispaced samples to be selected + """ + + _transformed_types = (torch.Tensor,) + + def __init__(self, num_samples: int): + super().__init__() + self.num_samples = num_samples + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.uniform_temporal_subsample, inpt, self.num_samples) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_transform.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..ac84fcb6c826d4d6473fd8441965089cf80ca920 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_transform.py @@ -0,0 +1,194 @@ +from __future__ import annotations + +import enum +from typing import Any, Callable + +import PIL.Image +import torch +from torch import nn +from torch.utils._pytree import tree_flatten, tree_unflatten +from torchvision import tv_tensors +from torchvision.transforms.v2._utils import check_type, has_any, is_pure_tensor +from torchvision.utils import _log_api_usage_once + +from .functional._utils import _get_kernel + + +class Transform(nn.Module): + """Base class to implement your own v2 transforms. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_transforms.py` for + more details. + """ + + # Class attribute defining transformed types. Other types are passed-through without any transformation + # We support both Types and callables that are able to do further checks on the type of the input. + _transformed_types: tuple[type | Callable[[Any], bool], ...] = (torch.Tensor, PIL.Image.Image) + + def __init__(self) -> None: + super().__init__() + _log_api_usage_once(self) + + def check_inputs(self, flat_inputs: list[Any]) -> None: + pass + + # When v2 was introduced, this method was private and called + # `_get_params()`. Now it's publicly exposed as `make_params()`. It cannot + # be exposed as `get_params()` because there is already a `get_params()` + # methods for v2 transforms: it's the v1's `get_params()` that we have to + # keep in order to guarantee 100% BC with v1. (It's defined in + # __init_subclass__ below). + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + """Method to override for custom transforms. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_transforms.py`""" + return dict() + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + kernel = _get_kernel(functional, type(inpt), allow_passthrough=True) + return kernel(inpt, *args, **kwargs) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + """Method to override for custom transforms. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_transforms.py`""" + raise NotImplementedError + + def forward(self, *inputs: Any) -> Any: + """Do not override this! Use ``transform()`` instead.""" + flat_inputs, spec = tree_flatten(inputs if len(inputs) > 1 else inputs[0]) + + self.check_inputs(flat_inputs) + + needs_transform_list = self._needs_transform_list(flat_inputs) + params = self.make_params( + [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform] + ) + + flat_outputs = [ + self.transform(inpt, params) if needs_transform else inpt + for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) + ] + + return tree_unflatten(flat_outputs, spec) + + def _needs_transform_list(self, flat_inputs: list[Any]) -> list[bool]: + # Below is a heuristic on how to deal with pure tensor inputs: + # 1. Pure tensors, i.e. tensors that are not a tv_tensor, are passed through if there is an explicit image + # (`tv_tensors.Image` or `PIL.Image.Image`) or video (`tv_tensors.Video`) in the sample. + # 2. If there is no explicit image or video in the sample, only the first encountered pure tensor is + # transformed as image, while the rest is passed through. The order is defined by the returned `flat_inputs` + # of `tree_flatten`, which recurses depth-first through the input. + # + # This heuristic stems from two requirements: + # 1. We need to keep BC for single input pure tensors and treat them as images. + # 2. We don't want to treat all pure tensors as images, because some datasets like `CelebA` or `Widerface` + # return supplemental numerical data as tensors that cannot be transformed as images. + # + # The heuristic should work well for most people in practice. The only case where it doesn't is if someone + # tries to transform multiple pure tensors at the same time, expecting them all to be treated as images. + # However, this case wasn't supported by transforms v1 either, so there is no BC concern. + + needs_transform_list = [] + transform_pure_tensor = not has_any(flat_inputs, tv_tensors.Image, tv_tensors.Video, PIL.Image.Image) + for inpt in flat_inputs: + needs_transform = True + + if not check_type(inpt, self._transformed_types): + needs_transform = False + elif is_pure_tensor(inpt): + if transform_pure_tensor: + transform_pure_tensor = False + else: + needs_transform = False + needs_transform_list.append(needs_transform) + return needs_transform_list + + def extra_repr(self) -> str: + extra = [] + for name, value in self.__dict__.items(): + if name.startswith("_") or name == "training": + continue + + if not isinstance(value, (bool, int, float, str, tuple, list, enum.Enum)): + continue + + extra.append(f"{name}={value}") + + return ", ".join(extra) + + # This attribute should be set on all transforms that have a v1 equivalent. Doing so enables two things: + # 1. In case the v1 transform has a static `get_params` method, it will also be available under the same name on + # the v2 transform. See `__init_subclass__` for details. + # 2. The v2 transform will be JIT scriptable. See `_extract_params_for_v1_transform` and `__prepare_scriptable__` + # for details. + _v1_transform_cls: type[nn.Module] | None = None + + def __init_subclass__(cls) -> None: + # Since `get_params` is a `@staticmethod`, we have to bind it to the class itself rather than to an instance. + # This method is called after subclassing has happened, i.e. `cls` is the subclass, e.g. `Resize`. + if cls._v1_transform_cls is not None and hasattr(cls._v1_transform_cls, "get_params"): + cls.get_params = staticmethod(cls._v1_transform_cls.get_params) # type: ignore[attr-defined] + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + # This method is called by `__prepare_scriptable__` to instantiate the equivalent v1 transform from the current + # v2 transform instance. It extracts all available public attributes that are specific to that transform and + # not `nn.Module` in general. + # Overwrite this method on the v2 transform class if the above is not sufficient. For example, this might happen + # if the v2 transform introduced new parameters that are not support by the v1 transform. + common_attrs = nn.Module().__dict__.keys() + return { + attr: value + for attr, value in self.__dict__.items() + if not attr.startswith("_") and attr not in common_attrs + } + + def __prepare_scriptable__(self) -> nn.Module: + # This method is called early on when `torch.jit.script`'ing an `nn.Module` instance. If it succeeds, the return + # value is used for scripting over the original object that should have been scripted. Since the v1 transforms + # are JIT scriptable, and we made sure that for single image inputs v1 and v2 are equivalent, we just return the + # equivalent v1 transform here. This of course only makes transforms v2 JIT scriptable as long as transforms v1 + # is around. + if self._v1_transform_cls is None: + raise RuntimeError( + f"Transform {type(self).__name__} cannot be JIT scripted. " + "torchscript is only supported for backward compatibility with transforms " + "which are already in torchvision.transforms. " + "For torchscript support (on tensors only), you can use the functional API instead." + ) + + return self._v1_transform_cls(**self._extract_params_for_v1_transform()) + + +class _RandomApplyTransform(Transform): + def __init__(self, p: float = 0.5) -> None: + if not (0.0 <= p <= 1.0): + raise ValueError("`p` should be a floating point value in the interval [0.0, 1.0].") + + super().__init__() + self.p = p + + def forward(self, *inputs: Any) -> Any: + # We need to almost duplicate `Transform.forward()` here since we always want to check the inputs, but return + # early afterwards in case the random check triggers. The same result could be achieved by calling + # `super().forward()` after the random check, but that would call `self.check_inputs` twice. + + inputs = inputs if len(inputs) > 1 else inputs[0] + flat_inputs, spec = tree_flatten(inputs) + + self.check_inputs(flat_inputs) + + if torch.rand(1) >= self.p: + return inputs + + needs_transform_list = self._needs_transform_list(flat_inputs) + params = self.make_params( + [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform] + ) + + flat_outputs = [ + self.transform(inpt, params) if needs_transform else inpt + for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) + ] + + return tree_unflatten(flat_outputs, spec) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_type_conversion.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_type_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..7cac62868b9b5331e4760e56dde284fa40929d14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_type_conversion.py @@ -0,0 +1,92 @@ +from typing import Any, Optional, Union + +import numpy as np +import PIL.Image +import torch + +from torchvision import tv_tensors +from torchvision.transforms.v2 import functional as F, Transform + +from torchvision.transforms.v2._utils import is_pure_tensor + + +class PILToTensor(Transform): + """Convert a PIL Image to a tensor of the same type - this does not scale values. + + This transform does not support torchscript. + + Convert a PIL Image with H height, W width, and C channels to a Tensor of shape (C x H x W). + + Example: + >>> from PIL import Image + >>> from torchvision.transforms import v2 + >>> img = Image.new("RGB", (320, 240)) # size (W=320, H=240) + >>> tensor = v2.PILToTensor()(img) + >>> print(tensor.shape) + torch.Size([3, 240, 320]) + """ + + _transformed_types = (PIL.Image.Image,) + + def transform(self, inpt: PIL.Image.Image, params: dict[str, Any]) -> torch.Tensor: + return F.pil_to_tensor(inpt) + + +class ToImage(Transform): + """Convert a tensor, ndarray, or PIL Image to :class:`~torchvision.tv_tensors.Image` + ; this does not scale values. + + This transform does not support torchscript. + """ + + _transformed_types = (is_pure_tensor, PIL.Image.Image, np.ndarray) + + def transform( + self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: dict[str, Any] + ) -> tv_tensors.Image: + return F.to_image(inpt) + + +class ToPILImage(Transform): + """Convert a tensor or an ndarray to PIL Image + + This transform does not support torchscript. + + Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape + H x W x C to a PIL Image while adjusting the value range depending on the ``mode``. + + Args: + mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). + If ``mode`` is ``None`` (default) there are some assumptions made about the input data: + + - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``. + - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``. + - If the input has 2 channels, the ``mode`` is assumed to be ``LA``. + - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, + ``short``). + + .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes + """ + + _transformed_types = (is_pure_tensor, tv_tensors.Image, np.ndarray) + + def __init__(self, mode: Optional[str] = None) -> None: + super().__init__() + self.mode = mode + + def transform( + self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: dict[str, Any] + ) -> PIL.Image.Image: + return F.to_pil_image(inpt, mode=self.mode) + + +class ToPureTensor(Transform): + """Convert all TVTensors to pure tensors, removing associated metadata (if any). + + This doesn't scale or change the values, only the type. + """ + + _transformed_types = (tv_tensors.TVTensor,) + + def transform(self, inpt: Any, params: dict[str, Any]) -> torch.Tensor: + return inpt.as_subclass(torch.Tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6051b4e61c02c004c01e6610f8a5f584046e87 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/_utils.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +import collections.abc +import numbers +from collections.abc import Sequence +from contextlib import suppress + +from typing import Any, Callable, Literal + +import PIL.Image +import torch + +from torchvision import tv_tensors + +from torchvision._utils import sequence_to_str + +from torchvision.transforms.transforms import _check_sequence_input, _setup_angle, _setup_size # noqa: F401 +from torchvision.transforms.v2.functional import get_dimensions, get_size, is_pure_tensor +from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT + + +def _setup_number_or_seq(arg: int | float | Sequence[int | float], name: str) -> Sequence[float]: + if not isinstance(arg, (int, float, Sequence)): + raise TypeError(f"{name} should be a number or a sequence of numbers. Got {type(arg)}") + if isinstance(arg, Sequence) and len(arg) not in (1, 2): + raise ValueError(f"If {name} is a sequence its length should be 1 or 2. Got {len(arg)}") + if isinstance(arg, Sequence): + for element in arg: + if not isinstance(element, (int, float)): + raise ValueError(f"{name} should be a sequence of numbers. Got {type(element)}") + + if isinstance(arg, (int, float)): + arg = [float(arg), float(arg)] + elif isinstance(arg, Sequence): + if len(arg) == 1: + arg = [float(arg[0]), float(arg[0])] + else: + arg = [float(arg[0]), float(arg[1])] + return arg + + +def _check_fill_arg(fill: _FillType | dict[type | str, _FillType]) -> None: + if isinstance(fill, dict): + for value in fill.values(): + _check_fill_arg(value) + else: + if fill is not None and not isinstance(fill, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate fill arg, only Numbers, tuples, lists and dicts are allowed.") + + +def _convert_fill_arg(fill: _FillType) -> _FillTypeJIT: + # Fill = 0 is not equivalent to None, https://github.com/pytorch/vision/issues/6517 + # So, we can't reassign fill to 0 + # if fill is None: + # fill = 0 + if fill is None: + return fill + + if not isinstance(fill, (int, float)): + fill = [float(v) for v in list(fill)] + return fill # type: ignore[return-value] + + +def _setup_fill_arg(fill: _FillType | dict[type | str, _FillType]) -> dict[type | str, _FillTypeJIT]: + _check_fill_arg(fill) + + if isinstance(fill, dict): + for k, v in fill.items(): + fill[k] = _convert_fill_arg(v) + return fill # type: ignore[return-value] + else: + return {"others": _convert_fill_arg(fill)} + + +def _get_fill(fill_dict, inpt_type): + if inpt_type in fill_dict: + return fill_dict[inpt_type] + elif "others" in fill_dict: + return fill_dict["others"] + else: + RuntimeError("This should never happen, please open an issue on the torchvision repo if you hit this.") + + +def _check_padding_arg(padding: int | Sequence[int]) -> None: + + err_msg = f"Padding must be an int or a 1, 2, or 4 element of tuple or list, got {padding}." + if isinstance(padding, (tuple, list)): + if len(padding) not in [1, 2, 4] or not all(isinstance(p, int) for p in padding): + raise ValueError(err_msg) + elif not isinstance(padding, int): + raise ValueError(err_msg) + + +# TODO: let's use torchvision._utils.StrEnum to have the best of both worlds (strings and enums) +# https://github.com/pytorch/vision/issues/6250 +def _check_padding_mode_arg(padding_mode: Literal["constant", "edge", "reflect", "symmetric"]) -> None: + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + +def _find_labels_default_heuristic(inputs: Any) -> torch.Tensor: + """ + This heuristic covers three cases: + + 1. The input is tuple or list whose second item is a labels tensor. This happens for already batched + classification inputs for MixUp and CutMix (typically after the Dataloder). + 2. The input is a tuple or list whose second item is a dictionary that contains the labels tensor + under a label-like (see below) key. This happens for the inputs of detection models. + 3. The input is a dictionary that is structured as the one from 2. + + What is "label-like" key? We first search for an case-insensitive match of 'labels' inside the keys of the + dictionary. This is the name our detection models expect. If we can't find that, we look for a case-insensitive + match of the term 'label' anywhere inside the key, i.e. 'FooLaBeLBar'. If we can't find that either, the dictionary + contains no "label-like" key. + """ + + if isinstance(inputs, (tuple, list)): + inputs = inputs[1] + + # MixUp, CutMix + if is_pure_tensor(inputs): + return inputs + + if not isinstance(inputs, collections.abc.Mapping): + raise ValueError( + f"When using the default labels_getter, the input passed to forward must be a dictionary or a two-tuple " + f"whose second item is a dictionary or a tensor, but got {inputs} instead." + ) + + candidate_key = None + with suppress(StopIteration): + candidate_key = next(key for key in inputs.keys() if key.lower() == "labels") + if candidate_key is None: + with suppress(StopIteration): + candidate_key = next(key for key in inputs.keys() if "label" in key.lower()) + if candidate_key is None: + raise ValueError( + "Could not infer where the labels are in the sample. Try passing a callable as the labels_getter parameter?" + "If there are no labels in the sample by design, pass labels_getter=None." + ) + + return inputs[candidate_key] + + +def _parse_labels_getter(labels_getter: str | Callable[[Any], Any] | None) -> Callable[[Any], Any]: + if labels_getter == "default": + return _find_labels_default_heuristic + elif callable(labels_getter): + return labels_getter + elif labels_getter is None: + return lambda _: None + else: + raise ValueError(f"labels_getter should either be 'default', a callable, or None, but got {labels_getter}.") + + +def get_bounding_boxes(flat_inputs: list[Any]) -> tv_tensors.BoundingBoxes: + """Return the Bounding Boxes in the input. + + Assumes only one ``BoundingBoxes`` object is present. + """ + # This assumes there is only one bbox per sample as per the general convention + try: + return next(inpt for inpt in flat_inputs if isinstance(inpt, tv_tensors.BoundingBoxes)) + except StopIteration: + raise ValueError("No bounding boxes were found in the sample") + + +def get_keypoints(flat_inputs: list[Any]) -> tv_tensors.KeyPoints: + """Return the keypoints in the input. + + Assumes only one ``KeyPoints`` object is present. + """ + # This assumes there is only one keypoint per sample as per the general convention + try: + return next(inpt for inpt in flat_inputs if isinstance(inpt, tv_tensors.KeyPoints)) + except StopIteration: + raise ValueError("No keypoints were found in the sample") + + +def query_chw(flat_inputs: list[Any]) -> tuple[int, int, int]: + """Return Channel, Height, and Width.""" + chws = { + tuple(get_dimensions(inpt)) + for inpt in flat_inputs + if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video)) + } + if not chws: + raise TypeError("No image or video was found in the sample") + elif len(chws) > 1: + raise ValueError(f"Found multiple CxHxW dimensions in the sample: {sequence_to_str(sorted(chws))}") + c, h, w = chws.pop() + return c, h, w + + +def query_size(flat_inputs: list[Any]) -> tuple[int, int]: + """Return Height and Width.""" + sizes = { + tuple(get_size(inpt)) + for inpt in flat_inputs + if check_type( + inpt, + ( + is_pure_tensor, + tv_tensors.Image, + PIL.Image.Image, + tv_tensors.Video, + tv_tensors.Mask, + tv_tensors.BoundingBoxes, + tv_tensors.KeyPoints, + ), + ) + } + if not sizes: + raise TypeError("No image, video, mask, bounding box of keypoint was found in the sample") + elif len(sizes) > 1: + raise ValueError(f"Found multiple HxW dimensions in the sample: {sequence_to_str(sorted(sizes))}") + h, w = sizes.pop() + return h, w + + +def check_type(obj: Any, types_or_checks: tuple[type | Callable[[Any], bool], ...]) -> bool: + for type_or_check in types_or_checks: + if isinstance(obj, type_or_check) if isinstance(type_or_check, type) else type_or_check(obj): + return True + return False + + +def has_any(flat_inputs: list[Any], *types_or_checks: type | Callable[[Any], bool]) -> bool: + for inpt in flat_inputs: + if check_type(inpt, types_or_checks): + return True + return False + + +def has_all(flat_inputs: list[Any], *types_or_checks: type | Callable[[Any], bool]) -> bool: + for type_or_check in types_or_checks: + for inpt in flat_inputs: + if isinstance(inpt, type_or_check) if isinstance(type_or_check, type) else type_or_check(inpt): + break + else: + return False + return True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13fbaa588fea9bf99857a5409136efeb486d19cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/__init__.py @@ -0,0 +1,167 @@ +from torchvision.transforms import InterpolationMode # usort: skip + +from ._utils import is_pure_tensor, register_kernel # usort: skip + +from ._meta import ( + clamp_bounding_boxes, + clamp_keypoints, + convert_bounding_box_format, + get_dimensions_image, + get_dimensions_video, + get_dimensions, + get_num_frames_video, + get_num_frames, + get_image_num_channels, + get_num_channels_image, + get_num_channels_video, + get_num_channels, + get_size_bounding_boxes, + get_size_keypoints, + get_size_image, + get_size_mask, + get_size_video, + get_size, +) # usort: skip + +from ._augment import erase, erase_image, erase_video, jpeg, jpeg_image, jpeg_video +from ._color import ( + adjust_brightness, + adjust_brightness_image, + adjust_brightness_video, + adjust_contrast, + adjust_contrast_image, + adjust_contrast_video, + adjust_gamma, + adjust_gamma_image, + adjust_gamma_video, + adjust_hue, + adjust_hue_image, + adjust_hue_video, + adjust_saturation, + adjust_saturation_image, + adjust_saturation_video, + adjust_sharpness, + adjust_sharpness_image, + adjust_sharpness_video, + autocontrast, + autocontrast_image, + autocontrast_video, + equalize, + equalize_image, + equalize_video, + grayscale_to_rgb, + grayscale_to_rgb_image, + invert, + invert_image, + invert_video, + permute_channels, + permute_channels_image, + permute_channels_video, + posterize, + posterize_image, + posterize_video, + rgb_to_grayscale, + rgb_to_grayscale_image, + solarize, + solarize_image, + solarize_video, + to_grayscale, +) +from ._geometry import ( + affine, + affine_bounding_boxes, + affine_image, + affine_keypoints, + affine_mask, + affine_video, + center_crop, + center_crop_bounding_boxes, + center_crop_image, + center_crop_keypoints, + center_crop_mask, + center_crop_video, + crop, + crop_bounding_boxes, + crop_image, + crop_keypoints, + crop_mask, + crop_video, + elastic, + elastic_bounding_boxes, + elastic_image, + elastic_keypoints, + elastic_mask, + elastic_transform, + elastic_video, + five_crop, + five_crop_image, + five_crop_video, + hflip, # TODO: Consider moving all pure alias definitions at the bottom of the file + horizontal_flip, + horizontal_flip_bounding_boxes, + horizontal_flip_image, + horizontal_flip_keypoints, + horizontal_flip_mask, + horizontal_flip_video, + pad, + pad_bounding_boxes, + pad_image, + pad_keypoints, + pad_mask, + pad_video, + perspective, + perspective_bounding_boxes, + perspective_image, + perspective_keypoints, + perspective_mask, + perspective_video, + resize, + resize_bounding_boxes, + resize_image, + resize_keypoints, + resize_mask, + resize_video, + resized_crop, + resized_crop_bounding_boxes, + resized_crop_image, + resized_crop_keypoints, + resized_crop_mask, + resized_crop_video, + rotate, + rotate_bounding_boxes, + rotate_image, + rotate_keypoints, + rotate_mask, + rotate_video, + ten_crop, + ten_crop_image, + ten_crop_video, + vertical_flip, + vertical_flip_bounding_boxes, + vertical_flip_image, + vertical_flip_keypoints, + vertical_flip_mask, + vertical_flip_video, + vflip, +) +from ._misc import ( + convert_image_dtype, + gaussian_blur, + gaussian_blur_image, + gaussian_blur_video, + gaussian_noise, + gaussian_noise_image, + gaussian_noise_video, + normalize, + normalize_image, + normalize_video, + sanitize_bounding_boxes, + sanitize_keypoints, + to_dtype, + to_dtype_image, + to_dtype_video, +) +from ._temporal import uniform_temporal_subsample, uniform_temporal_subsample_video +from ._type_conversion import pil_to_tensor, to_image, to_pil_image + +from ._deprecated import get_image_size, to_tensor # usort: skip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_augment.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_augment.py new file mode 100644 index 0000000000000000000000000000000000000000..a904d8d7cbdfeb78588abbf43c8bca37b3431735 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_augment.py @@ -0,0 +1,106 @@ +import io + +import PIL.Image + +import torch +from torchvision import tv_tensors +from torchvision.io import decode_jpeg, encode_jpeg +from torchvision.transforms.functional import pil_to_tensor, to_pil_image +from torchvision.utils import _log_api_usage_once + +from ._utils import _get_kernel, _register_kernel_internal + + +def erase( + inpt: torch.Tensor, + i: int, + j: int, + h: int, + w: int, + v: torch.Tensor, + inplace: bool = False, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomErase` for details.""" + if torch.jit.is_scripting(): + return erase_image(inpt, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + + _log_api_usage_once(erase) + + kernel = _get_kernel(erase, type(inpt)) + return kernel(inpt, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + + +@_register_kernel_internal(erase, torch.Tensor) +@_register_kernel_internal(erase, tv_tensors.Image) +def erase_image( + image: torch.Tensor, i: int, j: int, h: int, w: int, v: torch.Tensor, inplace: bool = False +) -> torch.Tensor: + if not inplace: + image = image.clone() + + image[..., i : i + h, j : j + w] = v + return image + + +@_register_kernel_internal(erase, PIL.Image.Image) +def _erase_image_pil( + image: PIL.Image.Image, i: int, j: int, h: int, w: int, v: torch.Tensor, inplace: bool = False +) -> PIL.Image.Image: + t_img = pil_to_tensor(image) + output = erase_image(t_img, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + return to_pil_image(output, mode=image.mode) + + +@_register_kernel_internal(erase, tv_tensors.Video) +def erase_video( + video: torch.Tensor, i: int, j: int, h: int, w: int, v: torch.Tensor, inplace: bool = False +) -> torch.Tensor: + return erase_image(video, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + + +def jpeg(image: torch.Tensor, quality: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.JPEG` for details.""" + if torch.jit.is_scripting(): + return jpeg_image(image, quality=quality) + + _log_api_usage_once(jpeg) + + kernel = _get_kernel(jpeg, type(image)) + return kernel(image, quality=quality) + + +@_register_kernel_internal(jpeg, torch.Tensor) +@_register_kernel_internal(jpeg, tv_tensors.Image) +def jpeg_image(image: torch.Tensor, quality: int) -> torch.Tensor: + original_shape = image.shape + image = image.view((-1,) + image.shape[-3:]) + + if image.shape[0] == 0: # degenerate + return image.reshape(original_shape).clone() + + images = [] + for i in range(image.shape[0]): + # isinstance checks are needed for torchscript. + encoded_image = encode_jpeg(image[i], quality=quality) + assert isinstance(encoded_image, torch.Tensor) + decoded_image = decode_jpeg(encoded_image) + assert isinstance(decoded_image, torch.Tensor) + images.append(decoded_image) + + images = torch.stack(images, dim=0).view(original_shape) + return images + + +@_register_kernel_internal(jpeg, tv_tensors.Video) +def jpeg_video(video: torch.Tensor, quality: int) -> torch.Tensor: + return jpeg_image(video, quality=quality) + + +@_register_kernel_internal(jpeg, PIL.Image.Image) +def _jpeg_image_pil(image: PIL.Image.Image, quality: int) -> PIL.Image.Image: + raw_jpeg = io.BytesIO() + image.save(raw_jpeg, format="JPEG", quality=quality) + + # we need to copy since PIL.Image.open() will return PIL.JpegImagePlugin.JpegImageFile + # which is a sub-class of PIL.Image.Image. this will fail check_transform() test. + return PIL.Image.open(raw_jpeg).copy() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_color.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_color.py new file mode 100644 index 0000000000000000000000000000000000000000..be254c0d63a0dd6d67c3d3a042a24265a3bd2034 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_color.py @@ -0,0 +1,740 @@ +import PIL.Image +import torch +from torch.nn.functional import conv2d +from torchvision import tv_tensors +from torchvision.transforms import _functional_pil as _FP +from torchvision.transforms._functional_tensor import _max_value + +from torchvision.utils import _log_api_usage_once + +from ._misc import _num_value_bits, to_dtype_image +from ._type_conversion import pil_to_tensor, to_pil_image +from ._utils import _get_kernel, _register_kernel_internal + + +def rgb_to_grayscale(inpt: torch.Tensor, num_output_channels: int = 1) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Grayscale` for details.""" + if torch.jit.is_scripting(): + return rgb_to_grayscale_image(inpt, num_output_channels=num_output_channels) + + _log_api_usage_once(rgb_to_grayscale) + + kernel = _get_kernel(rgb_to_grayscale, type(inpt)) + return kernel(inpt, num_output_channels=num_output_channels) + + +# `to_grayscale` actually predates `rgb_to_grayscale` in v1, but only handles PIL images. Since `rgb_to_grayscale` is a +# superset in terms of functionality and has the same signature, we alias here to avoid disruption. +to_grayscale = rgb_to_grayscale + + +def _rgb_to_grayscale_image( + image: torch.Tensor, num_output_channels: int = 1, preserve_dtype: bool = True +) -> torch.Tensor: + # TODO: Maybe move the validation that num_output_channels is 1 or 3 to this function instead of callers. + if image.shape[-3] == 1 and num_output_channels == 1: + return image.clone() + if image.shape[-3] == 1 and num_output_channels == 3: + s = [1] * len(image.shape) + s[-3] = 3 + return image.repeat(s) + r, g, b = image.unbind(dim=-3) + l_img = r.mul(0.2989).add_(g, alpha=0.587).add_(b, alpha=0.114) + l_img = l_img.unsqueeze(dim=-3) + if preserve_dtype: + l_img = l_img.to(image.dtype) + if num_output_channels == 3: + l_img = l_img.expand(image.shape) + return l_img + + +@_register_kernel_internal(rgb_to_grayscale, torch.Tensor) +@_register_kernel_internal(rgb_to_grayscale, tv_tensors.Image) +def rgb_to_grayscale_image(image: torch.Tensor, num_output_channels: int = 1) -> torch.Tensor: + if num_output_channels not in (1, 3): + raise ValueError(f"num_output_channels must be 1 or 3, got {num_output_channels}.") + return _rgb_to_grayscale_image(image, num_output_channels=num_output_channels, preserve_dtype=True) + + +@_register_kernel_internal(rgb_to_grayscale, PIL.Image.Image) +def _rgb_to_grayscale_image_pil(image: PIL.Image.Image, num_output_channels: int = 1) -> PIL.Image.Image: + if num_output_channels not in (1, 3): + raise ValueError(f"num_output_channels must be 1 or 3, got {num_output_channels}.") + return _FP.to_grayscale(image, num_output_channels=num_output_channels) + + +def grayscale_to_rgb(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RGB` for details.""" + if torch.jit.is_scripting(): + return grayscale_to_rgb_image(inpt) + + _log_api_usage_once(grayscale_to_rgb) + + kernel = _get_kernel(grayscale_to_rgb, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(grayscale_to_rgb, torch.Tensor) +@_register_kernel_internal(grayscale_to_rgb, tv_tensors.Image) +def grayscale_to_rgb_image(image: torch.Tensor) -> torch.Tensor: + if image.shape[-3] >= 3: + # Image already has RGB channels. We don't need to do anything. + return image + # rgb_to_grayscale can be used to add channels so we reuse that function. + return _rgb_to_grayscale_image(image, num_output_channels=3, preserve_dtype=True) + + +@_register_kernel_internal(grayscale_to_rgb, PIL.Image.Image) +def grayscale_to_rgb_image_pil(image: PIL.Image.Image) -> PIL.Image.Image: + return image.convert(mode="RGB") + + +def _blend(image1: torch.Tensor, image2: torch.Tensor, ratio: float) -> torch.Tensor: + ratio = float(ratio) + fp = image1.is_floating_point() + bound = _max_value(image1.dtype) + output = image1.mul(ratio).add_(image2, alpha=(1.0 - ratio)).clamp_(0, bound) + return output if fp else output.to(image1.dtype) + + +def adjust_brightness(inpt: torch.Tensor, brightness_factor: float) -> torch.Tensor: + """Adjust brightness.""" + + if torch.jit.is_scripting(): + return adjust_brightness_image(inpt, brightness_factor=brightness_factor) + + _log_api_usage_once(adjust_brightness) + + kernel = _get_kernel(adjust_brightness, type(inpt)) + return kernel(inpt, brightness_factor=brightness_factor) + + +@_register_kernel_internal(adjust_brightness, torch.Tensor) +@_register_kernel_internal(adjust_brightness, tv_tensors.Image) +def adjust_brightness_image(image: torch.Tensor, brightness_factor: float) -> torch.Tensor: + if brightness_factor < 0: + raise ValueError(f"brightness_factor ({brightness_factor}) is not non-negative.") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + fp = image.is_floating_point() + bound = _max_value(image.dtype) + output = image.mul(brightness_factor).clamp_(0, bound) + return output if fp else output.to(image.dtype) + + +@_register_kernel_internal(adjust_brightness, PIL.Image.Image) +def _adjust_brightness_image_pil(image: PIL.Image.Image, brightness_factor: float) -> PIL.Image.Image: + return _FP.adjust_brightness(image, brightness_factor=brightness_factor) + + +@_register_kernel_internal(adjust_brightness, tv_tensors.Video) +def adjust_brightness_video(video: torch.Tensor, brightness_factor: float) -> torch.Tensor: + return adjust_brightness_image(video, brightness_factor=brightness_factor) + + +def adjust_saturation(inpt: torch.Tensor, saturation_factor: float) -> torch.Tensor: + """Adjust saturation.""" + if torch.jit.is_scripting(): + return adjust_saturation_image(inpt, saturation_factor=saturation_factor) + + _log_api_usage_once(adjust_saturation) + + kernel = _get_kernel(adjust_saturation, type(inpt)) + return kernel(inpt, saturation_factor=saturation_factor) + + +@_register_kernel_internal(adjust_saturation, torch.Tensor) +@_register_kernel_internal(adjust_saturation, tv_tensors.Image) +def adjust_saturation_image(image: torch.Tensor, saturation_factor: float) -> torch.Tensor: + if saturation_factor < 0: + raise ValueError(f"saturation_factor ({saturation_factor}) is not non-negative.") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + if c == 1: # Match PIL behaviour + return image + + grayscale_image = _rgb_to_grayscale_image(image, num_output_channels=1, preserve_dtype=False) + if not image.is_floating_point(): + grayscale_image = grayscale_image.floor_() + + return _blend(image, grayscale_image, saturation_factor) + + +_adjust_saturation_image_pil = _register_kernel_internal(adjust_saturation, PIL.Image.Image)(_FP.adjust_saturation) + + +@_register_kernel_internal(adjust_saturation, tv_tensors.Video) +def adjust_saturation_video(video: torch.Tensor, saturation_factor: float) -> torch.Tensor: + return adjust_saturation_image(video, saturation_factor=saturation_factor) + + +def adjust_contrast(inpt: torch.Tensor, contrast_factor: float) -> torch.Tensor: + """See :class:`~torchvision.transforms.RandomAutocontrast`""" + if torch.jit.is_scripting(): + return adjust_contrast_image(inpt, contrast_factor=contrast_factor) + + _log_api_usage_once(adjust_contrast) + + kernel = _get_kernel(adjust_contrast, type(inpt)) + return kernel(inpt, contrast_factor=contrast_factor) + + +@_register_kernel_internal(adjust_contrast, torch.Tensor) +@_register_kernel_internal(adjust_contrast, tv_tensors.Image) +def adjust_contrast_image(image: torch.Tensor, contrast_factor: float) -> torch.Tensor: + if contrast_factor < 0: + raise ValueError(f"contrast_factor ({contrast_factor}) is not non-negative.") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + fp = image.is_floating_point() + if c == 3: + grayscale_image = _rgb_to_grayscale_image(image, num_output_channels=1, preserve_dtype=False) + if not fp: + grayscale_image = grayscale_image.floor_() + else: + grayscale_image = image if fp else image.to(torch.float32) + mean = torch.mean(grayscale_image, dim=(-3, -2, -1), keepdim=True) + return _blend(image, mean, contrast_factor) + + +_adjust_contrast_image_pil = _register_kernel_internal(adjust_contrast, PIL.Image.Image)(_FP.adjust_contrast) + + +@_register_kernel_internal(adjust_contrast, tv_tensors.Video) +def adjust_contrast_video(video: torch.Tensor, contrast_factor: float) -> torch.Tensor: + return adjust_contrast_image(video, contrast_factor=contrast_factor) + + +def adjust_sharpness(inpt: torch.Tensor, sharpness_factor: float) -> torch.Tensor: + """See :class:`~torchvision.transforms.RandomAdjustSharpness`""" + if torch.jit.is_scripting(): + return adjust_sharpness_image(inpt, sharpness_factor=sharpness_factor) + + _log_api_usage_once(adjust_sharpness) + + kernel = _get_kernel(adjust_sharpness, type(inpt)) + return kernel(inpt, sharpness_factor=sharpness_factor) + + +@_register_kernel_internal(adjust_sharpness, torch.Tensor) +@_register_kernel_internal(adjust_sharpness, tv_tensors.Image) +def adjust_sharpness_image(image: torch.Tensor, sharpness_factor: float) -> torch.Tensor: + num_channels, height, width = image.shape[-3:] + if num_channels not in (1, 3): + raise TypeError(f"Input image tensor can have 1 or 3 channels, but found {num_channels}") + + if sharpness_factor < 0: + raise ValueError(f"sharpness_factor ({sharpness_factor}) is not non-negative.") + + if image.numel() == 0 or height <= 2 or width <= 2: + return image + + bound = _max_value(image.dtype) + fp = image.is_floating_point() + shape = image.shape + + if image.ndim > 4: + image = image.reshape(-1, num_channels, height, width) + needs_unsquash = True + else: + needs_unsquash = False + + # The following is a normalized 3x3 kernel with 1s in the edges and a 5 in the middle. + kernel_dtype = image.dtype if fp else torch.float32 + a, b = 1.0 / 13.0, 5.0 / 13.0 + kernel = torch.tensor([[a, a, a], [a, b, a], [a, a, a]], dtype=kernel_dtype, device=image.device) + kernel = kernel.expand(num_channels, 1, 3, 3) + + # We copy and cast at the same time to avoid modifications on the original data + output = image.to(dtype=kernel_dtype, copy=True) + blurred_degenerate = conv2d(output, kernel, groups=num_channels) + if not fp: + # it is better to round before cast + blurred_degenerate = blurred_degenerate.round_() + + # Create a view on the underlying output while pointing at the same data. We do this to avoid indexing twice. + view = output[..., 1:-1, 1:-1] + + # We speed up blending by minimizing flops and doing in-place. The 2 blend options are mathematically equivalent: + # x+(1-r)*(y-x) = x + (1-r)*y - (1-r)*x = x*r + y*(1-r) + view.add_(blurred_degenerate.sub_(view), alpha=(1.0 - sharpness_factor)) + + # The actual data of output have been modified by the above. We only need to clamp and cast now. + output = output.clamp_(0, bound) + if not fp: + output = output.to(image.dtype) + + if needs_unsquash: + output = output.reshape(shape) + + return output + + +_adjust_sharpness_image_pil = _register_kernel_internal(adjust_sharpness, PIL.Image.Image)(_FP.adjust_sharpness) + + +@_register_kernel_internal(adjust_sharpness, tv_tensors.Video) +def adjust_sharpness_video(video: torch.Tensor, sharpness_factor: float) -> torch.Tensor: + return adjust_sharpness_image(video, sharpness_factor=sharpness_factor) + + +def adjust_hue(inpt: torch.Tensor, hue_factor: float) -> torch.Tensor: + """Adjust hue""" + if torch.jit.is_scripting(): + return adjust_hue_image(inpt, hue_factor=hue_factor) + + _log_api_usage_once(adjust_hue) + + kernel = _get_kernel(adjust_hue, type(inpt)) + return kernel(inpt, hue_factor=hue_factor) + + +def _rgb_to_hsv(image: torch.Tensor) -> torch.Tensor: + r, g, _ = image.unbind(dim=-3) + + # Implementation is based on + # https://github.com/python-pillow/Pillow/blob/4174d4267616897df3746d315d5a2d0f82c656ee/src/libImaging/Convert.c#L330 + minc, maxc = torch.aminmax(image, dim=-3) + + # The algorithm erases S and H channel where `maxc = minc`. This avoids NaN + # from happening in the results, because + # + S channel has division by `maxc`, which is zero only if `maxc = minc` + # + H channel has division by `(maxc - minc)`. + # + # Instead of overwriting NaN afterwards, we just prevent it from occurring so + # we don't need to deal with it in case we save the NaN in a buffer in + # backprop, if it is ever supported, but it doesn't hurt to do so. + eqc = maxc == minc + + channels_range = maxc - minc + # Since `eqc => channels_range = 0`, replacing denominator with 1 when `eqc` is fine. + ones = torch.ones_like(maxc) + s = channels_range / torch.where(eqc, ones, maxc) + # Note that `eqc => maxc = minc = r = g = b`. So the following calculation + # of `h` would reduce to `bc - gc + 2 + rc - bc + 4 + rc - bc = 6` so it + # would not matter what values `rc`, `gc`, and `bc` have here, and thus + # replacing denominator with 1 when `eqc` is fine. + channels_range_divisor = torch.where(eqc, ones, channels_range).unsqueeze_(dim=-3) + rc, gc, bc = ((maxc.unsqueeze(dim=-3) - image) / channels_range_divisor).unbind(dim=-3) + + mask_maxc_neq_r = maxc != r + mask_maxc_eq_g = maxc == g + + hg = rc.add(2.0).sub_(bc).mul_(mask_maxc_eq_g & mask_maxc_neq_r) + hr = bc.sub_(gc).mul_(~mask_maxc_neq_r) + hb = gc.add_(4.0).sub_(rc).mul_(mask_maxc_neq_r.logical_and_(mask_maxc_eq_g.logical_not_())) + + h = hr.add_(hg).add_(hb) + h = h.mul_(1.0 / 6.0).add_(1.0).fmod_(1.0) + return torch.stack((h, s, maxc), dim=-3) + + +def _hsv_to_rgb(img: torch.Tensor) -> torch.Tensor: + h, s, v = img.unbind(dim=-3) + h6 = h.mul(6) + i = torch.floor(h6) + f = h6.sub_(i) + i = i.to(dtype=torch.int32) + + sxf = s * f + one_minus_s = 1.0 - s + q = (1.0 - sxf).mul_(v).clamp_(0.0, 1.0) + t = sxf.add_(one_minus_s).mul_(v).clamp_(0.0, 1.0) + p = one_minus_s.mul_(v).clamp_(0.0, 1.0) + i.remainder_(6) + + vpqt = torch.stack((v, p, q, t), dim=-3) + + # vpqt -> rgb mapping based on i + select = torch.tensor([[0, 2, 1, 1, 3, 0], [3, 0, 0, 2, 1, 1], [1, 1, 3, 0, 0, 2]], dtype=torch.long) + select = select.to(device=img.device, non_blocking=True) + + select = select[:, i] + if select.ndim > 3: + # if input.shape is (B, ..., C, H, W) then + # select.shape is (C, B, ..., H, W) + # thus we move C axis to get (B, ..., C, H, W) + select = select.moveaxis(0, -3) + + return vpqt.gather(-3, select) + + +@_register_kernel_internal(adjust_hue, torch.Tensor) +@_register_kernel_internal(adjust_hue, tv_tensors.Image) +def adjust_hue_image(image: torch.Tensor, hue_factor: float) -> torch.Tensor: + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + if c == 1: # Match PIL behaviour + return image + + if image.numel() == 0: + # exit earlier on empty images + return image + + orig_dtype = image.dtype + image = to_dtype_image(image, torch.float32, scale=True) + + image = _rgb_to_hsv(image) + h, s, v = image.unbind(dim=-3) + h.add_(hue_factor).remainder_(1.0) + image = torch.stack((h, s, v), dim=-3) + image_hue_adj = _hsv_to_rgb(image) + + return to_dtype_image(image_hue_adj, orig_dtype, scale=True) + + +_adjust_hue_image_pil = _register_kernel_internal(adjust_hue, PIL.Image.Image)(_FP.adjust_hue) + + +@_register_kernel_internal(adjust_hue, tv_tensors.Video) +def adjust_hue_video(video: torch.Tensor, hue_factor: float) -> torch.Tensor: + return adjust_hue_image(video, hue_factor=hue_factor) + + +def adjust_gamma(inpt: torch.Tensor, gamma: float, gain: float = 1) -> torch.Tensor: + """Adjust gamma.""" + if torch.jit.is_scripting(): + return adjust_gamma_image(inpt, gamma=gamma, gain=gain) + + _log_api_usage_once(adjust_gamma) + + kernel = _get_kernel(adjust_gamma, type(inpt)) + return kernel(inpt, gamma=gamma, gain=gain) + + +@_register_kernel_internal(adjust_gamma, torch.Tensor) +@_register_kernel_internal(adjust_gamma, tv_tensors.Image) +def adjust_gamma_image(image: torch.Tensor, gamma: float, gain: float = 1.0) -> torch.Tensor: + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number") + + # The input image is either assumed to be at [0, 1] scale (if float) or is converted to that scale (if integer). + # Since the gamma is non-negative, the output remains at [0, 1] scale. + if not torch.is_floating_point(image): + output = to_dtype_image(image, torch.float32, scale=True).pow_(gamma) + else: + output = image.pow(gamma) + + if gain != 1.0: + # The clamp operation is needed only if multiplication is performed. It's only when gain != 1, that the scale + # of the output can go beyond [0, 1]. + output = output.mul_(gain).clamp_(0.0, 1.0) + + return to_dtype_image(output, image.dtype, scale=True) + + +_adjust_gamma_image_pil = _register_kernel_internal(adjust_gamma, PIL.Image.Image)(_FP.adjust_gamma) + + +@_register_kernel_internal(adjust_gamma, tv_tensors.Video) +def adjust_gamma_video(video: torch.Tensor, gamma: float, gain: float = 1) -> torch.Tensor: + return adjust_gamma_image(video, gamma=gamma, gain=gain) + + +def posterize(inpt: torch.Tensor, bits: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomPosterize` for details.""" + if torch.jit.is_scripting(): + return posterize_image(inpt, bits=bits) + + _log_api_usage_once(posterize) + + kernel = _get_kernel(posterize, type(inpt)) + return kernel(inpt, bits=bits) + + +@_register_kernel_internal(posterize, torch.Tensor) +@_register_kernel_internal(posterize, tv_tensors.Image) +def posterize_image(image: torch.Tensor, bits: int) -> torch.Tensor: + if not isinstance(bits, int) or not 0 <= bits <= 8: + raise TypeError(f"bits must be a positive integer in the range [0, 8], got {bits} instead.") + + if image.is_floating_point(): + levels = 1 << bits + return image.mul(levels).floor_().clamp_(0, levels - 1).mul_(1.0 / levels) + else: + num_value_bits = _num_value_bits(image.dtype) + if bits >= num_value_bits: + return image + + mask = ((1 << bits) - 1) << (num_value_bits - bits) + return image & mask + + +_posterize_image_pil = _register_kernel_internal(posterize, PIL.Image.Image)(_FP.posterize) + + +@_register_kernel_internal(posterize, tv_tensors.Video) +def posterize_video(video: torch.Tensor, bits: int) -> torch.Tensor: + return posterize_image(video, bits=bits) + + +def solarize(inpt: torch.Tensor, threshold: float) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomSolarize` for details.""" + if torch.jit.is_scripting(): + return solarize_image(inpt, threshold=threshold) + + _log_api_usage_once(solarize) + + kernel = _get_kernel(solarize, type(inpt)) + return kernel(inpt, threshold=threshold) + + +@_register_kernel_internal(solarize, torch.Tensor) +@_register_kernel_internal(solarize, tv_tensors.Image) +def solarize_image(image: torch.Tensor, threshold: float) -> torch.Tensor: + if threshold > _max_value(image.dtype): + raise TypeError(f"Threshold should be less or equal the maximum value of the dtype, but got {threshold}") + + return torch.where(image >= threshold, invert_image(image), image) + + +_solarize_image_pil = _register_kernel_internal(solarize, PIL.Image.Image)(_FP.solarize) + + +@_register_kernel_internal(solarize, tv_tensors.Video) +def solarize_video(video: torch.Tensor, threshold: float) -> torch.Tensor: + return solarize_image(video, threshold=threshold) + + +def autocontrast(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomAutocontrast` for details.""" + if torch.jit.is_scripting(): + return autocontrast_image(inpt) + + _log_api_usage_once(autocontrast) + + kernel = _get_kernel(autocontrast, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(autocontrast, torch.Tensor) +@_register_kernel_internal(autocontrast, tv_tensors.Image) +def autocontrast_image(image: torch.Tensor) -> torch.Tensor: + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + if image.numel() == 0: + # exit earlier on empty images + return image + + bound = _max_value(image.dtype) + fp = image.is_floating_point() + float_image = image if fp else image.to(torch.float32) + + minimum = float_image.amin(dim=(-2, -1), keepdim=True) + maximum = float_image.amax(dim=(-2, -1), keepdim=True) + + eq_idxs = maximum == minimum + inv_scale = maximum.sub_(minimum).mul_(1.0 / bound) + minimum[eq_idxs] = 0.0 + inv_scale[eq_idxs] = 1.0 + + if fp: + diff = float_image.sub(minimum) + else: + diff = float_image.sub_(minimum) + + return diff.div_(inv_scale).clamp_(0, bound).to(image.dtype) + + +_autocontrast_image_pil = _register_kernel_internal(autocontrast, PIL.Image.Image)(_FP.autocontrast) + + +@_register_kernel_internal(autocontrast, tv_tensors.Video) +def autocontrast_video(video: torch.Tensor) -> torch.Tensor: + return autocontrast_image(video) + + +def equalize(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomEqualize` for details.""" + if torch.jit.is_scripting(): + return equalize_image(inpt) + + _log_api_usage_once(equalize) + + kernel = _get_kernel(equalize, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(equalize, torch.Tensor) +@_register_kernel_internal(equalize, tv_tensors.Image) +def equalize_image(image: torch.Tensor) -> torch.Tensor: + if image.numel() == 0: + return image + + # 1. The algorithm below can easily be extended to support arbitrary integer dtypes. However, the histogram that + # would be needed to computed will have at least `torch.iinfo(dtype).max + 1` values. That is perfectly fine for + # `torch.int8`, `torch.uint8`, and `torch.int16`, at least questionable for `torch.int32` and completely + # unfeasible for `torch.int64`. + # 2. Floating point inputs need to be binned for this algorithm. Apart from converting them to an integer dtype, we + # could also use PyTorch's builtin histogram functionality. However, that has its own set of issues: in addition + # to being slow in general, PyTorch's implementation also doesn't support batches. In total, that makes it slower + # and more complicated to implement than a simple conversion and a fast histogram implementation for integers. + # Since we need to convert in most cases anyway and out of the acceptable dtypes mentioned in 1. `torch.uint8` is + # by far the most common, we choose it as base. + output_dtype = image.dtype + image = to_dtype_image(image, torch.uint8, scale=True) + + # The histogram is computed by using the flattened image as index. For example, a pixel value of 127 in the image + # corresponds to adding 1 to index 127 in the histogram. + batch_shape = image.shape[:-2] + flat_image = image.flatten(start_dim=-2).to(torch.long) + hist = flat_image.new_zeros(batch_shape + (256,), dtype=torch.int32) + hist.scatter_add_(dim=-1, index=flat_image, src=hist.new_ones(1).expand_as(flat_image)) + cum_hist = hist.cumsum(dim=-1) + + # The simplest form of lookup-table (LUT) that also achieves histogram equalization is + # `lut = cum_hist / flat_image.shape[-1] * 255` + # However, PIL uses a more elaborate scheme: + # https://github.com/python-pillow/Pillow/blob/eb59cb61d5239ee69cbbf12709a0c6fd7314e6d7/src/PIL/ImageOps.py#L368-L385 + # `lut = ((cum_hist + num_non_max_pixels // (2 * 255)) // num_non_max_pixels) * 255` + + # The last non-zero element in the histogram is the first element in the cumulative histogram with the maximum + # value. Thus, the "max" in `num_non_max_pixels` does not refer to 255 as the maximum value of uint8 images, but + # rather the maximum value in the image, which might be or not be 255. + index = cum_hist.argmax(dim=-1) + num_non_max_pixels = flat_image.shape[-1] - hist.gather(dim=-1, index=index.unsqueeze_(-1)) + + # This is performance optimization that saves us one multiplication later. With this, the LUT computation simplifies + # to `lut = (cum_hist + step // 2) // step` and thus saving the final multiplication by 255 while keeping the + # division count the same. PIL uses the variable name `step` for this, so we keep that for easier comparison. + step = num_non_max_pixels.div_(255, rounding_mode="floor") + + # Although it looks like we could return early if we find `step == 0` like PIL does, that is unfortunately not as + # easy due to our support for batched images. We can only return early if `(step == 0).all()` holds. If it doesn't, + # we have to go through the computation below anyway. Since `step == 0` is an edge case anyway, it makes no sense to + # pay the runtime cost for checking it every time. + valid_equalization = step.ne(0).unsqueeze_(-1) + + # `lut[k]` is computed with `cum_hist[k-1]` with `lut[0] == (step // 2) // step == 0`. Thus, we perform the + # computation only for `lut[1:]` with `cum_hist[:-1]` and add `lut[0] == 0` afterwards. + cum_hist = cum_hist[..., :-1] + ( + cum_hist.add_(step // 2) + # We need the `clamp_`(min=1) call here to avoid zero division since they fail for integer dtypes. This has no + # effect on the returned result of this kernel since images inside the batch with `step == 0` are returned as is + # instead of equalized version. + .div_(step.clamp_(min=1), rounding_mode="floor") + # We need the `clamp_` call here since PILs LUT computation scheme can produce values outside the valid value + # range of uint8 images + .clamp_(0, 255) + ) + lut = cum_hist.to(torch.uint8) + lut = torch.cat([lut.new_zeros(1).expand(batch_shape + (1,)), lut], dim=-1) + equalized_image = lut.gather(dim=-1, index=flat_image).view_as(image) + + output = torch.where(valid_equalization, equalized_image, image) + return to_dtype_image(output, output_dtype, scale=True) + + +_equalize_image_pil = _register_kernel_internal(equalize, PIL.Image.Image)(_FP.equalize) + + +@_register_kernel_internal(equalize, tv_tensors.Video) +def equalize_video(video: torch.Tensor) -> torch.Tensor: + return equalize_image(video) + + +def invert(inpt: torch.Tensor) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.RandomInvert`.""" + if torch.jit.is_scripting(): + return invert_image(inpt) + + _log_api_usage_once(invert) + + kernel = _get_kernel(invert, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(invert, torch.Tensor) +@_register_kernel_internal(invert, tv_tensors.Image) +def invert_image(image: torch.Tensor) -> torch.Tensor: + if image.is_floating_point(): + return 1.0 - image + elif image.dtype == torch.uint8: + return image.bitwise_not() + else: # signed integer dtypes + # We can't use `Tensor.bitwise_not` here, since we want to retain the leading zero bit that encodes the sign + return image.bitwise_xor((1 << _num_value_bits(image.dtype)) - 1) + + +_invert_image_pil = _register_kernel_internal(invert, PIL.Image.Image)(_FP.invert) + + +@_register_kernel_internal(invert, tv_tensors.Video) +def invert_video(video: torch.Tensor) -> torch.Tensor: + return invert_image(video) + + +def permute_channels(inpt: torch.Tensor, permutation: list[int]) -> torch.Tensor: + """Permute the channels of the input according to the given permutation. + + This function supports plain :class:`~torch.Tensor`'s, :class:`PIL.Image.Image`'s, and + :class:`torchvision.tv_tensors.Image` and :class:`torchvision.tv_tensors.Video`. + + Example: + >>> rgb_image = torch.rand(3, 256, 256) + >>> bgr_image = F.permute_channels(rgb_image, permutation=[2, 1, 0]) + + Args: + permutation (List[int]): Valid permutation of the input channel indices. The index of the element determines the + channel index in the input and the value determines the channel index in the output. For example, + ``permutation=[2, 0 , 1]`` + + - takes ``ìnpt[..., 0, :, :]`` and puts it at ``output[..., 2, :, :]``, + - takes ``ìnpt[..., 1, :, :]`` and puts it at ``output[..., 0, :, :]``, and + - takes ``ìnpt[..., 2, :, :]`` and puts it at ``output[..., 1, :, :]``. + + Raises: + ValueError: If ``len(permutation)`` doesn't match the number of channels in the input. + """ + if torch.jit.is_scripting(): + return permute_channels_image(inpt, permutation=permutation) + + _log_api_usage_once(permute_channels) + + kernel = _get_kernel(permute_channels, type(inpt)) + return kernel(inpt, permutation=permutation) + + +@_register_kernel_internal(permute_channels, torch.Tensor) +@_register_kernel_internal(permute_channels, tv_tensors.Image) +def permute_channels_image(image: torch.Tensor, permutation: list[int]) -> torch.Tensor: + shape = image.shape + num_channels, height, width = shape[-3:] + + if len(permutation) != num_channels: + raise ValueError( + f"Length of permutation does not match number of channels: " f"{len(permutation)} != {num_channels}" + ) + + if image.numel() == 0: + return image + + image = image.reshape(-1, num_channels, height, width) + image = image[:, permutation, :, :] + return image.reshape(shape) + + +@_register_kernel_internal(permute_channels, PIL.Image.Image) +def _permute_channels_image_pil(image: PIL.Image.Image, permutation: list[int]) -> PIL.Image.Image: + return to_pil_image(permute_channels_image(pil_to_tensor(image), permutation=permutation)) + + +@_register_kernel_internal(permute_channels, tv_tensors.Video) +def permute_channels_video(video: torch.Tensor, permutation: list[int]) -> torch.Tensor: + return permute_channels_image(video, permutation=permutation) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_deprecated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..3131b5e8c495ec763ccc822a43e19133eb5fd3ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_deprecated.py @@ -0,0 +1,24 @@ +import warnings +from typing import Any + +import torch + +from torchvision.transforms import functional as _F + + +@torch.jit.unused +def to_tensor(inpt: Any) -> torch.Tensor: + """[DEPREACTED] Use to_image() and to_dtype() instead.""" + warnings.warn( + "The function `to_tensor(...)` is deprecated and will be removed in a future release. " + "Instead, please use `to_image(...)` followed by `to_dtype(..., dtype=torch.float32, scale=True)`." + ) + return _F.to_tensor(inpt) + + +def get_image_size(inpt: torch.Tensor) -> list[int]: + warnings.warn( + "The function `get_image_size(...)` is deprecated and will be removed in a future release. " + "Instead, please use `get_size(...)` which returns `[h, w]` instead of `[w, h]`." + ) + return _F.get_image_size(inpt) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_geometry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..4fcb7fabe0df05a8ac5d33da2bbe41a7c2aac3e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_geometry.py @@ -0,0 +1,3003 @@ +import math +import numbers +import warnings +from collections.abc import Sequence +from typing import Any, Optional, Union + +import PIL.Image +import torch +from torch.nn.functional import grid_sample, interpolate, pad as torch_pad + +from torchvision import tv_tensors +from torchvision.transforms import _functional_pil as _FP +from torchvision.transforms._functional_tensor import _pad_symmetric +from torchvision.transforms.functional import ( + _compute_resized_output_size as __compute_resized_output_size, + _get_perspective_coeffs, + _interpolation_modes_from_int, + InterpolationMode, + pil_modes_mapping, + pil_to_tensor, + to_pil_image, +) +from torchvision.tv_tensors._bounding_boxes import CLAMPING_MODE_TYPE + +from torchvision.utils import _log_api_usage_once + +from ._meta import _get_size_image_pil, clamp_bounding_boxes, convert_bounding_box_format + +from ._utils import _FillTypeJIT, _get_kernel, _register_five_ten_crop_kernel_internal, _register_kernel_internal + + +def _check_interpolation(interpolation: Union[InterpolationMode, int]) -> InterpolationMode: + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise ValueError( + f"Argument interpolation should be an `InterpolationMode` or a corresponding Pillow integer constant, " + f"but got {interpolation}." + ) + return interpolation + + +def horizontal_flip(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomHorizontalFlip` for details.""" + if torch.jit.is_scripting(): + return horizontal_flip_image(inpt) + + _log_api_usage_once(horizontal_flip) + + kernel = _get_kernel(horizontal_flip, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(horizontal_flip, torch.Tensor) +@_register_kernel_internal(horizontal_flip, tv_tensors.Image) +def horizontal_flip_image(image: torch.Tensor) -> torch.Tensor: + return image.flip(-1) + + +@_register_kernel_internal(horizontal_flip, PIL.Image.Image) +def _horizontal_flip_image_pil(image: PIL.Image.Image) -> PIL.Image.Image: + return _FP.hflip(image) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.Mask) +def horizontal_flip_mask(mask: torch.Tensor) -> torch.Tensor: + return horizontal_flip_image(mask) + + +def horizontal_flip_keypoints(keypoints: torch.Tensor, canvas_size: tuple[int, int]): + shape = keypoints.shape + keypoints = keypoints.clone().reshape(-1, 2) + keypoints[..., 0] = keypoints[..., 0].sub_(canvas_size[1] - 1).neg_() + return keypoints.reshape(shape) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _horizontal_flip_keypoints_dispatch(keypoints: tv_tensors.KeyPoints): + out = horizontal_flip_keypoints(keypoints.as_subclass(torch.Tensor), canvas_size=keypoints.canvas_size) + return tv_tensors.wrap(out, like=keypoints) + + +def horizontal_flip_bounding_boxes( + bounding_boxes: torch.Tensor, format: tv_tensors.BoundingBoxFormat, canvas_size: tuple[int, int] +) -> torch.Tensor: + shape = bounding_boxes.shape + + if tv_tensors.is_rotated_bounding_format(format): + bounding_boxes = ( + bounding_boxes.clone().reshape(-1, 5) + if format != tv_tensors.BoundingBoxFormat.XYXYXYXY + else bounding_boxes.clone().reshape(-1, 8) + ) + else: + bounding_boxes = bounding_boxes.clone().reshape(-1, 4) + + if format == tv_tensors.BoundingBoxFormat.XYXY: + bounding_boxes[:, [2, 0]] = bounding_boxes[:, [0, 2]].sub_(canvas_size[1]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYWH: + bounding_boxes[:, 0].add_(bounding_boxes[:, 2]).sub_(canvas_size[1]).neg_() + elif format == tv_tensors.BoundingBoxFormat.CXCYWH: + bounding_boxes[:, 0].sub_(canvas_size[1]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + bounding_boxes[:, 0::2].sub_(canvas_size[1]).neg_() + bounding_boxes = bounding_boxes[:, [2, 3, 0, 1, 6, 7, 4, 5]] + elif format == tv_tensors.BoundingBoxFormat.XYWHR: + angle_rad = bounding_boxes[:, 4].mul(torch.pi).div(180) + bounding_boxes[:, 0].add_(bounding_boxes[:, 2].mul(angle_rad.cos())).sub_(canvas_size[1]).neg_() + bounding_boxes[:, 1].sub_(bounding_boxes[:, 2].mul(angle_rad.sin())) + bounding_boxes[:, 4].neg_() + else: # format == tv_tensors.BoundingBoxFormat.CXCYWHR: + bounding_boxes[:, 0].sub_(canvas_size[1]).neg_() + bounding_boxes[:, 4].neg_() + + return bounding_boxes.reshape(shape) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _horizontal_flip_bounding_boxes_dispatch(inpt: tv_tensors.BoundingBoxes) -> tv_tensors.BoundingBoxes: + output = horizontal_flip_bounding_boxes( + inpt.as_subclass(torch.Tensor), format=inpt.format, canvas_size=inpt.canvas_size + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.Video) +def horizontal_flip_video(video: torch.Tensor) -> torch.Tensor: + return horizontal_flip_image(video) + + +def vertical_flip(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomVerticalFlip` for details.""" + if torch.jit.is_scripting(): + return vertical_flip_image(inpt) + + _log_api_usage_once(vertical_flip) + + kernel = _get_kernel(vertical_flip, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(vertical_flip, torch.Tensor) +@_register_kernel_internal(vertical_flip, tv_tensors.Image) +def vertical_flip_image(image: torch.Tensor) -> torch.Tensor: + return image.flip(-2) + + +@_register_kernel_internal(vertical_flip, PIL.Image.Image) +def _vertical_flip_image_pil(image: PIL.Image.Image) -> PIL.Image.Image: + return _FP.vflip(image) + + +@_register_kernel_internal(vertical_flip, tv_tensors.Mask) +def vertical_flip_mask(mask: torch.Tensor) -> torch.Tensor: + return vertical_flip_image(mask) + + +def vertical_flip_keypoints(keypoints: torch.Tensor, canvas_size: tuple[int, int]) -> torch.Tensor: + shape = keypoints.shape + keypoints = keypoints.clone().reshape(-1, 2) + keypoints[..., 1] = keypoints[..., 1].sub_(canvas_size[0] - 1).neg_() + return keypoints.reshape(shape) + + +def vertical_flip_bounding_boxes( + bounding_boxes: torch.Tensor, format: tv_tensors.BoundingBoxFormat, canvas_size: tuple[int, int] +) -> torch.Tensor: + shape = bounding_boxes.shape + + if tv_tensors.is_rotated_bounding_format(format): + bounding_boxes = ( + bounding_boxes.clone().reshape(-1, 5) + if format != tv_tensors.BoundingBoxFormat.XYXYXYXY + else bounding_boxes.clone().reshape(-1, 8) + ) + else: + bounding_boxes = bounding_boxes.clone().reshape(-1, 4) + + if format == tv_tensors.BoundingBoxFormat.XYXY: + bounding_boxes[:, [1, 3]] = bounding_boxes[:, [3, 1]].sub_(canvas_size[0]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYWH: + bounding_boxes[:, 1].add_(bounding_boxes[:, 3]).sub_(canvas_size[0]).neg_() + elif format == tv_tensors.BoundingBoxFormat.CXCYWH: + bounding_boxes[:, 1].sub_(canvas_size[0]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + bounding_boxes[:, 1::2].sub_(canvas_size[0]).neg_() + bounding_boxes = bounding_boxes[:, [2, 3, 0, 1, 6, 7, 4, 5]] + elif format == tv_tensors.BoundingBoxFormat.XYWHR: + angle_rad = bounding_boxes[:, 4].mul(torch.pi).div(180) + bounding_boxes[:, 1].sub_(bounding_boxes[:, 2].mul(angle_rad.sin())).sub_(canvas_size[0]).neg_() + bounding_boxes[:, 0].add_(bounding_boxes[:, 2].mul(angle_rad.cos())) + bounding_boxes[:, 4].neg_().add_(180) + else: # format == tv_tensors.BoundingBoxFormat.CXCYWHR: + bounding_boxes[:, 1].sub_(canvas_size[0]).neg_() + bounding_boxes[:, 4].neg_().add_(180) + + return bounding_boxes.reshape(shape) + + +@_register_kernel_internal(vertical_flip, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _vertical_flip_keypoints_dispatch(inpt: tv_tensors.KeyPoints) -> tv_tensors.KeyPoints: + output = vertical_flip_keypoints(inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(vertical_flip, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _vertical_flip_bounding_boxes_dispatch(inpt: tv_tensors.BoundingBoxes) -> tv_tensors.BoundingBoxes: + output = vertical_flip_bounding_boxes( + inpt.as_subclass(torch.Tensor), format=inpt.format, canvas_size=inpt.canvas_size + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(vertical_flip, tv_tensors.Video) +def vertical_flip_video(video: torch.Tensor) -> torch.Tensor: + return vertical_flip_image(video) + + +# We changed the names to align them with the transforms, i.e. `RandomHorizontalFlip`. Still, `hflip` and `vflip` are +# prevalent and well understood. Thus, we just alias them without deprecating the old names. +hflip = horizontal_flip +vflip = vertical_flip + + +def _compute_resized_output_size( + canvas_size: tuple[int, int], size: Optional[list[int]], max_size: Optional[int] = None +) -> list[int]: + if isinstance(size, int): + size = [size] + elif max_size is not None and size is not None and len(size) != 1: + raise ValueError( + "max_size should only be passed if size is None or specifies the length of the smaller edge, " + "i.e. size should be an int or a sequence of length 1 in torchscript mode." + ) + return __compute_resized_output_size(canvas_size, size=size, max_size=max_size, allow_size_none=True) + + +def resize( + inpt: torch.Tensor, + size: Optional[list[int]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Resize` for details.""" + if torch.jit.is_scripting(): + return resize_image(inpt, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + + _log_api_usage_once(resize) + + kernel = _get_kernel(resize, type(inpt)) + return kernel(inpt, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + + +# This is an internal helper method for resize_image. We should put it here instead of keeping it +# inside resize_image due to torchscript. +# uint8 dtype support for bilinear and bicubic is limited to cpu and +# according to our benchmarks on eager, non-AVX CPUs should still prefer u8->f32->interpolate->u8 path for bilinear +def _do_native_uint8_resize_on_cpu(interpolation: InterpolationMode) -> bool: + if interpolation == InterpolationMode.BILINEAR: + if torch.compiler.is_compiling(): + return True + else: + return torch.backends.cpu.get_cpu_capability() in ("AVX2", "AVX512") + + return interpolation == InterpolationMode.BICUBIC + + +@_register_kernel_internal(resize, torch.Tensor) +@_register_kernel_internal(resize, tv_tensors.Image) +def resize_image( + image: torch.Tensor, + size: Optional[list[int]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> torch.Tensor: + interpolation = _check_interpolation(interpolation) + antialias = False if antialias is None else antialias + align_corners: Optional[bool] = None + if interpolation == InterpolationMode.BILINEAR or interpolation == InterpolationMode.BICUBIC: + align_corners = False + else: + # The default of antialias is True from 0.17, so we don't warn or + # error if other interpolation modes are used. This is documented. + antialias = False + + shape = image.shape + numel = image.numel() + num_channels, old_height, old_width = shape[-3:] + new_height, new_width = _compute_resized_output_size((old_height, old_width), size=size, max_size=max_size) + + if (new_height, new_width) == (old_height, old_width): + return image + elif numel > 0: + dtype = image.dtype + acceptable_dtypes = [torch.float32, torch.float64] + if interpolation == InterpolationMode.NEAREST or interpolation == InterpolationMode.NEAREST_EXACT: + # uint8 dtype can be included for cpu and cuda input if nearest mode + acceptable_dtypes.append(torch.uint8) + elif image.device.type == "cpu": + if _do_native_uint8_resize_on_cpu(interpolation): + acceptable_dtypes.append(torch.uint8) + + image = image.reshape(-1, num_channels, old_height, old_width) + strides = image.stride() + if image.is_contiguous(memory_format=torch.channels_last) and image.shape[0] == 1 and numel != strides[0]: + # There is a weird behaviour in torch core where the output tensor of `interpolate()` can be allocated as + # contiguous even though the input is un-ambiguously channels_last (https://github.com/pytorch/pytorch/issues/68430). + # In particular this happens for the typical torchvision use-case of single CHW images where we fake the batch dim + # to become 1CHW. Below, we restride those tensors to trick torch core into properly allocating the output as + # channels_last, thus preserving the memory format of the input. This is not just for format consistency: + # for uint8 bilinear images, this also avoids an extra copy (re-packing) of the output and saves time. + # TODO: when https://github.com/pytorch/pytorch/issues/68430 is fixed (possibly by https://github.com/pytorch/pytorch/pull/100373), + # we should be able to remove this hack. + new_strides = list(strides) + new_strides[0] = numel + image = image.as_strided((1, num_channels, old_height, old_width), new_strides) + + need_cast = dtype not in acceptable_dtypes + if need_cast: + image = image.to(dtype=torch.float32) + + image = interpolate( + image, + size=[new_height, new_width], + mode=interpolation.value, + align_corners=align_corners, + antialias=antialias, + ) + + if need_cast: + if interpolation == InterpolationMode.BICUBIC and dtype == torch.uint8: + # This path is hit on non-AVX archs, or on GPU. + image = image.clamp_(min=0, max=255) + if dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64): + image = image.round_() + image = image.to(dtype=dtype) + + return image.reshape(shape[:-3] + (num_channels, new_height, new_width)) + + +def _resize_image_pil( + image: PIL.Image.Image, + size: Union[Sequence[int], int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, +) -> PIL.Image.Image: + old_height, old_width = image.height, image.width + new_height, new_width = _compute_resized_output_size( + (old_height, old_width), + size=size, # type: ignore[arg-type] + max_size=max_size, + ) + + interpolation = _check_interpolation(interpolation) + + if (new_height, new_width) == (old_height, old_width): + return image + + return image.resize((new_width, new_height), resample=pil_modes_mapping[interpolation]) + + +@_register_kernel_internal(resize, PIL.Image.Image) +def __resize_image_pil_dispatch( + image: PIL.Image.Image, + size: Union[Sequence[int], int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> PIL.Image.Image: + if antialias is False: + warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.") + return _resize_image_pil(image, size=size, interpolation=interpolation, max_size=max_size) + + +def resize_mask(mask: torch.Tensor, size: Optional[list[int]], max_size: Optional[int] = None) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = resize_image(mask, size=size, interpolation=InterpolationMode.NEAREST, max_size=max_size) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(resize, tv_tensors.Mask, tv_tensor_wrapper=False) +def _resize_mask_dispatch( + inpt: tv_tensors.Mask, size: list[int], max_size: Optional[int] = None, **kwargs: Any +) -> tv_tensors.Mask: + output = resize_mask(inpt.as_subclass(torch.Tensor), size, max_size=max_size) + return tv_tensors.wrap(output, like=inpt) + + +def resize_keypoints( + keypoints: torch.Tensor, + size: Optional[list[int]], + canvas_size: tuple[int, int], + max_size: Optional[int] = None, +): + old_height, old_width = canvas_size + new_height, new_width = _compute_resized_output_size(canvas_size, size=size, max_size=max_size) + + if (new_height, new_width) == (old_height, old_width): + return keypoints, canvas_size + + w_ratio = new_width / old_width + h_ratio = new_height / old_height + ratios = torch.tensor([w_ratio, h_ratio], device=keypoints.device) + keypoints = keypoints.mul(ratios).to(keypoints.dtype) + + return keypoints, (new_height, new_width) + + +@_register_kernel_internal(resize, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _resize_keypoints_dispatch( + keypoints: tv_tensors.KeyPoints, + size: Optional[list[int]], + max_size: Optional[int] = None, + **kwargs: Any, +) -> tv_tensors.KeyPoints: + out, canvas_size = resize_keypoints( + keypoints.as_subclass(torch.Tensor), + size, + canvas_size=keypoints.canvas_size, + max_size=max_size, + ) + return tv_tensors.wrap(out, like=keypoints, canvas_size=canvas_size) + + +def _parallelogram_to_bounding_boxes(parallelogram: torch.Tensor) -> torch.Tensor: + """ + Convert a parallelogram to a rectangle while keeping two points unchanged. + This function transforms a parallelogram represented by 8 coordinates (4 points) into a rectangle. + The two diagonally opposed points of the parallelogram forming the longest diagonal remain fixed. + The other points are adjusted to form a proper rectangle. + + Note: + This function is not applied in-place and will return a copy of the input tensor. + + Args: + parallelogram (torch.Tensor): Tensor of shape (..., 8) containing coordinates of parallelograms. + Format is [x1, y1, x2, y2, x3, y3, x4, y4]. + + Returns: + torch.Tensor: Tensor of same shape as input containing the rectangle coordinates. + The output maintains the same dtype as the input. + """ + original_shape = parallelogram.shape + dtype = parallelogram.dtype + acceptable_dtypes = [torch.float32, torch.float64] + need_cast = dtype not in acceptable_dtypes + if need_cast: + # Up-case to avoid overflow for square operations + parallelogram = parallelogram.to(torch.float32) + + x1, y1, x2, y2, x3, y3, x4, y4 = parallelogram.unbind(-1) + cx = (x1 + x3) / 2 + cy = (y1 + y3) / 2 + + # Calculate width, height, and rotation angle of the parallelogram + wp = torch.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + hp = torch.sqrt((x4 - x1) ** 2 + (y4 - y1) ** 2) + r12 = torch.atan2(y1 - y2, x2 - x1) + r14 = torch.atan2(y1 - y4, x4 - x1) + r_rad = r12 - r14 + sign = torch.where(r_rad > torch.pi / 2, -1, 1) + cos, sin = r_rad.cos(), r_rad.sin() + + # Calculate width, height, and rotation angle of the rectangle + w = torch.where(wp < hp, wp * sin, wp + hp * cos * sign) + h = torch.where(wp > hp, hp * sin, hp + wp * cos * sign) + r_rad = torch.where(hp > wp, r14 + torch.pi / 2, r12) + cos, sin = r_rad.cos(), r_rad.sin() + + x1 = cx - w / 2 * cos - h / 2 * sin + y1 = cy - h / 2 * cos + w / 2 * sin + x2 = cx + w / 2 * cos - h / 2 * sin + y2 = cy - h / 2 * cos - w / 2 * sin + x3 = cx + w / 2 * cos + h / 2 * sin + y3 = cy + h / 2 * cos - w / 2 * sin + x4 = cx - w / 2 * cos + h / 2 * sin + y4 = cy + h / 2 * cos + w / 2 * sin + out_boxes = torch.stack((x1, y1, x2, y2, x3, y3, x4, y4), dim=-1).reshape(original_shape) + + if need_cast: + out_boxes = out_boxes.to(dtype) + return out_boxes + + +def resize_bounding_boxes( + bounding_boxes: torch.Tensor, + canvas_size: tuple[int, int], + size: Optional[list[int]], + max_size: Optional[int] = None, + format: tv_tensors.BoundingBoxFormat = tv_tensors.BoundingBoxFormat.XYXY, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + # We set the default format as `tv_tensors.BoundingBoxFormat.XYXY` + # to ensure backward compatibility. + # Indeed before the introduction of rotated bounding box format + # this function did not received `format` parameter as input. + old_height, old_width = canvas_size + new_height, new_width = _compute_resized_output_size(canvas_size, size=size, max_size=max_size) + + if (new_height, new_width) == (old_height, old_width): + return bounding_boxes, canvas_size + + w_ratio = new_width / old_width + h_ratio = new_height / old_height + if tv_tensors.is_rotated_bounding_format(format): + original_shape = bounding_boxes.shape + xyxyxyxy_boxes = convert_bounding_box_format( + bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, inplace=False + ).reshape(-1, 8) + + ratios = torch.tensor( + [w_ratio, h_ratio, w_ratio, h_ratio, w_ratio, h_ratio, w_ratio, h_ratio], device=bounding_boxes.device + ) + transformed_points = xyxyxyxy_boxes.mul(ratios) + out_bboxes = _parallelogram_to_bounding_boxes(transformed_points) + out_bboxes = clamp_bounding_boxes( + out_bboxes, + format=tv_tensors.BoundingBoxFormat.XYXYXYXY, + canvas_size=(new_height, new_width), + clamping_mode=clamping_mode, + ) + return ( + convert_bounding_box_format( + out_bboxes, + old_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, + new_format=format, + inplace=False, + ) + .to(bounding_boxes.dtype) + .reshape(original_shape), + (new_height, new_width), + ) + else: + ratios = torch.tensor([w_ratio, h_ratio, w_ratio, h_ratio], device=bounding_boxes.device) + return ( + bounding_boxes.mul(ratios).to(bounding_boxes.dtype), + (new_height, new_width), + ) + + +@_register_kernel_internal(resize, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _resize_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, size: Optional[list[int]], max_size: Optional[int] = None, **kwargs: Any +) -> tv_tensors.BoundingBoxes: + output, canvas_size = resize_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + size=size, + max_size=max_size, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(resize, tv_tensors.Video) +def resize_video( + video: torch.Tensor, + size: Optional[list[int]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> torch.Tensor: + return resize_image(video, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + + +def affine( + inpt: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomAffine` for details.""" + if torch.jit.is_scripting(): + return affine_image( + inpt, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=interpolation, + fill=fill, + center=center, + ) + + _log_api_usage_once(affine) + + kernel = _get_kernel(affine, type(inpt)) + return kernel( + inpt, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=interpolation, + fill=fill, + center=center, + ) + + +def _affine_parse_args( + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: InterpolationMode = InterpolationMode.NEAREST, + center: Optional[list[float]] = None, +) -> tuple[float, list[float], list[float], Optional[list[float]]]: + if not isinstance(angle, (int, float)): + raise TypeError("Argument angle should be int or float") + + if not isinstance(translate, (list, tuple)): + raise TypeError("Argument translate should be a sequence") + + if len(translate) != 2: + raise ValueError("Argument translate should be a sequence of length 2") + + if scale <= 0.0: + raise ValueError("Argument scale should be positive") + + if not isinstance(shear, (numbers.Number, (list, tuple))): + raise TypeError("Shear should be either a single value or a sequence of two values") + + if not isinstance(interpolation, InterpolationMode): + raise TypeError("Argument interpolation should be a InterpolationMode") + + if isinstance(angle, int): + angle = float(angle) + + if isinstance(translate, tuple): + translate = list(translate) + + if isinstance(shear, numbers.Number): + shear = [shear, 0.0] + + if isinstance(shear, tuple): + shear = list(shear) + + if len(shear) == 1: + shear = [shear[0], shear[0]] + + if len(shear) != 2: + raise ValueError(f"Shear should be a sequence containing two values. Got {shear}") + + if center is not None: + if not isinstance(center, (list, tuple)): + raise TypeError("Argument center should be a sequence") + else: + center = [float(c) for c in center] + + return angle, translate, shear, center + + +def _get_inverse_affine_matrix( + center: list[float], angle: float, translate: list[float], scale: float, shear: list[float], inverted: bool = True +) -> list[float]: + # Helper method to compute inverse matrix for affine transformation + + # Pillow requires inverse affine transformation matrix: + # Affine matrix is : M = T * C * RotateScaleShear * C^-1 + # + # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] + # C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1] + # RotateScaleShear is rotation with scale and shear matrix + # + # RotateScaleShear(a, s, (sx, sy)) = + # = R(a) * S(s) * SHy(sy) * SHx(sx) + # = [ s*cos(a - sy)/cos(sy), s*(-cos(a - sy)*tan(sx)/cos(sy) - sin(a)), 0 ] + # [ s*sin(a - sy)/cos(sy), s*(-sin(a - sy)*tan(sx)/cos(sy) + cos(a)), 0 ] + # [ 0 , 0 , 1 ] + # where R is a rotation matrix, S is a scaling matrix, and SHx and SHy are the shears: + # SHx(s) = [1, -tan(s)] and SHy(s) = [1 , 0] + # [0, 1 ] [-tan(s), 1] + # + # Thus, the inverse is M^-1 = C * RotateScaleShear^-1 * C^-1 * T^-1 + + rot = math.radians(angle) + sx = math.radians(shear[0]) + sy = math.radians(shear[1]) + + cx, cy = center + tx, ty = translate + + # Cached results + cos_sy = math.cos(sy) + tan_sx = math.tan(sx) + rot_minus_sy = rot - sy + cx_plus_tx = cx + tx + cy_plus_ty = cy + ty + + # Rotate Scale Shear (RSS) without scaling + a = math.cos(rot_minus_sy) / cos_sy + b = -(a * tan_sx + math.sin(rot)) + c = math.sin(rot_minus_sy) / cos_sy + d = math.cos(rot) - c * tan_sx + + if inverted: + # Inverted rotation matrix with scale and shear + # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1 + matrix = [d / scale, -b / scale, 0.0, -c / scale, a / scale, 0.0] + # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1 + # and then apply center translation: C * RSS^-1 * C^-1 * T^-1 + matrix[2] += cx - matrix[0] * cx_plus_tx - matrix[1] * cy_plus_ty + matrix[5] += cy - matrix[3] * cx_plus_tx - matrix[4] * cy_plus_ty + else: + matrix = [a * scale, b * scale, 0.0, c * scale, d * scale, 0.0] + # Apply inverse of center translation: RSS * C^-1 + # and then apply translation and center : T * C * RSS * C^-1 + matrix[2] += cx_plus_tx - matrix[0] * cx - matrix[1] * cy + matrix[5] += cy_plus_ty - matrix[3] * cx - matrix[4] * cy + + return matrix + + +def _compute_affine_output_size(matrix: list[float], w: int, h: int) -> tuple[int, int]: + if torch.compiler.is_compiling() and not torch.jit.is_scripting(): + return _compute_affine_output_size_python(matrix, w, h) + else: + return _compute_affine_output_size_tensor(matrix, w, h) + + +def _compute_affine_output_size_tensor(matrix: list[float], w: int, h: int) -> tuple[int, int]: + # Inspired of PIL implementation: + # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054 + + # pts are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + # Points are shifted due to affine matrix torch convention about + # the center point. Center is (0, 0) for image center pivot point (w * 0.5, h * 0.5) + half_w = 0.5 * w + half_h = 0.5 * h + pts = torch.tensor( + [ + [-half_w, -half_h, 1.0], + [-half_w, half_h, 1.0], + [half_w, half_h, 1.0], + [half_w, -half_h, 1.0], + ] + ) + theta = torch.tensor(matrix, dtype=torch.float).view(2, 3) + new_pts = torch.matmul(pts, theta.T) + min_vals, max_vals = new_pts.aminmax(dim=0) + + # shift points to [0, w] and [0, h] interval to match PIL results + halfs = torch.tensor((half_w, half_h)) + min_vals.add_(halfs) + max_vals.add_(halfs) + + # Truncate precision to 1e-4 to avoid ceil of Xe-15 to 1.0 + tol = 1e-4 + inv_tol = 1.0 / tol + cmax = max_vals.mul_(inv_tol).trunc_().mul_(tol).ceil_() + cmin = min_vals.mul_(inv_tol).trunc_().mul_(tol).floor_() + size = cmax.sub_(cmin) + return int(size[0]), int(size[1]) # w, h + + +def _compute_affine_output_size_python(matrix: list[float], w: int, h: int) -> tuple[int, int]: + # Mostly copied from PIL implementation: + # The only difference is with transformed points as input matrix has zero translation part here and + # PIL has a centered translation part. + # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054 + + a, b, c, d, e, f = matrix + xx = [] + yy = [] + + half_w = 0.5 * w + half_h = 0.5 * h + for x, y in ((-half_w, -half_h), (half_w, -half_h), (half_w, half_h), (-half_w, half_h)): + nx = a * x + b * y + c + ny = d * x + e * y + f + xx.append(nx + half_w) + yy.append(ny + half_h) + + nw = math.ceil(max(xx)) - math.floor(min(xx)) + nh = math.ceil(max(yy)) - math.floor(min(yy)) + return int(nw), int(nh) # w, h + + +def _apply_grid_transform(img: torch.Tensor, grid: torch.Tensor, mode: str, fill: _FillTypeJIT) -> torch.Tensor: + input_shape = img.shape + output_height, output_width = grid.shape[1], grid.shape[2] + num_channels, input_height, input_width = input_shape[-3:] + output_shape = input_shape[:-3] + (num_channels, output_height, output_width) + + if img.numel() == 0: + return img.reshape(output_shape) + + img = img.reshape(-1, num_channels, input_height, input_width) + squashed_batch_size = img.shape[0] + + # We are using context knowledge that grid should have float dtype + fp = img.dtype == grid.dtype + float_img = img if fp else img.to(grid.dtype) + + if squashed_batch_size > 1: + # Apply same grid to a batch of images + grid = grid.expand(squashed_batch_size, -1, -1, -1) + + # Append a dummy mask for customized fill colors, should be faster than grid_sample() twice + if fill is not None: + mask = torch.ones( + (squashed_batch_size, 1, input_height, input_width), dtype=float_img.dtype, device=float_img.device + ) + float_img = torch.cat((float_img, mask), dim=1) + + float_img = grid_sample(float_img, grid, mode=mode, padding_mode="zeros", align_corners=False) + + # Fill with required color + if fill is not None: + float_img, mask = torch.tensor_split(float_img, indices=(-1,), dim=-3) + mask = mask.expand_as(float_img) + fill_list = fill if isinstance(fill, (tuple, list)) else [float(fill)] # type: ignore[arg-type] + fill_img = torch.tensor(fill_list, dtype=float_img.dtype, device=float_img.device).view(1, -1, 1, 1) + if mode == "nearest": + float_img = torch.where(mask < 0.5, fill_img.expand_as(float_img), float_img) + else: # 'bilinear' + # The following is mathematically equivalent to: + # img * mask + (1.0 - mask) * fill = img * mask - fill * mask + fill = mask * (img - fill) + fill + float_img = float_img.sub_(fill_img).mul_(mask).add_(fill_img) + + img = float_img.round_().to(img.dtype) if not fp else float_img + + return img.reshape(output_shape) + + +def _assert_grid_transform_inputs( + image: torch.Tensor, + matrix: Optional[list[float]], + interpolation: str, + fill: _FillTypeJIT, + supported_interpolation_modes: list[str], + coeffs: Optional[list[float]] = None, +) -> None: + if matrix is not None: + if not isinstance(matrix, list): + raise TypeError("Argument matrix should be a list") + elif len(matrix) != 6: + raise ValueError("Argument matrix should have 6 float values") + + if coeffs is not None and len(coeffs) != 8: + raise ValueError("Argument coeffs should have 8 float values") + + if fill is not None: + if isinstance(fill, (tuple, list)): + length = len(fill) + num_channels = image.shape[-3] + if length > 1 and length != num_channels: + raise ValueError( + "The number of elements in 'fill' cannot broadcast to match the number of " + f"channels of the image ({length} != {num_channels})" + ) + elif not isinstance(fill, (int, float)): + raise ValueError("Argument fill should be either int, float, tuple or list") + + if interpolation not in supported_interpolation_modes: + raise ValueError(f"Interpolation mode '{interpolation}' is unsupported with Tensor input") + + +def _affine_grid( + theta: torch.Tensor, + w: int, + h: int, + ow: int, + oh: int, +) -> torch.Tensor: + # https://github.com/pytorch/pytorch/blob/74b65c32be68b15dc7c9e8bb62459efbfbde33d8/aten/src/ATen/native/ + # AffineGridGenerator.cpp#L18 + # Difference with AffineGridGenerator is that: + # 1) we normalize grid values after applying theta + # 2) we can normalize by other image size, such that it covers "extend" option like in PIL.Image.rotate + dtype = theta.dtype + device = theta.device + + base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device) + x_grid = torch.linspace((1.0 - ow) * 0.5, (ow - 1.0) * 0.5, steps=ow, device=device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace((1.0 - oh) * 0.5, (oh - 1.0) * 0.5, steps=oh, device=device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta = theta.transpose(1, 2).div_(torch.tensor([0.5 * w, 0.5 * h], dtype=dtype, device=device)) + output_grid = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta) + return output_grid.view(1, oh, ow, 2) + + +@_register_kernel_internal(affine, torch.Tensor) +@_register_kernel_internal(affine, tv_tensors.Image) +def affine_image( + image: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + interpolation = _check_interpolation(interpolation) + + angle, translate, shear, center = _affine_parse_args(angle, translate, scale, shear, interpolation, center) + + height, width = image.shape[-2:] + + center_f = [0.0, 0.0] + if center is not None: + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [(c - s * 0.5) for c, s in zip(center, [width, height])] + + translate_f = [float(t) for t in translate] + matrix = _get_inverse_affine_matrix(center_f, angle, translate_f, scale, shear) + + _assert_grid_transform_inputs(image, matrix, interpolation.value, fill, ["nearest", "bilinear"]) + + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=image.device).reshape(1, 2, 3) + grid = _affine_grid(theta, w=width, h=height, ow=width, oh=height) + return _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + +@_register_kernel_internal(affine, PIL.Image.Image) +def _affine_image_pil( + image: PIL.Image.Image, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> PIL.Image.Image: + interpolation = _check_interpolation(interpolation) + angle, translate, shear, center = _affine_parse_args(angle, translate, scale, shear, interpolation, center) + + # center = (img_size[0] * 0.5 + 0.5, img_size[1] * 0.5 + 0.5) + # it is visually better to estimate the center without 0.5 offset + # otherwise image rotated by 90 degrees is shifted vs output image of torch.rot90 or F_t.affine + if center is None: + height, width = _get_size_image_pil(image) + center = [width * 0.5, height * 0.5] + matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + + return _FP.affine(image, matrix, interpolation=pil_modes_mapping[interpolation], fill=fill) + + +# TODO: Consider merging/unifying this with the bbox implementation +def _affine_keypoints_with_expand( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + expand: bool = False, +) -> tuple[torch.Tensor, tuple[int, int]]: + if keypoints.numel() == 0: + return keypoints, canvas_size + + original_dtype = keypoints.dtype + original_shape = keypoints.shape + keypoints = keypoints.clone() if keypoints.is_floating_point() else keypoints.float() + dtype = keypoints.dtype + device = keypoints.device + + angle, translate, shear, center = _affine_parse_args( + angle, translate, scale, shear, InterpolationMode.NEAREST, center + ) + + if center is None: + height, width = canvas_size + center = [width * 0.5, height * 0.5] + + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear, inverted=False) + transposed_affine_matrix = ( + torch.tensor( + affine_vector, + dtype=dtype, + device=device, + ) + .reshape(2, 3) + .T + ) + + # 1) We transform points into a tensor of points with shape (N, 3), where N is the number of points. + points = keypoints.reshape(-1, 2) + points = torch.cat([points, torch.ones(points.shape[0], 1, device=device, dtype=dtype)], dim=-1) + # 2) Now let's transform the points using affine matrix + transformed_points = torch.matmul(points, transposed_affine_matrix) + + if expand: + # Compute minimum point for transformed image frame: + # Points are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + height, width = canvas_size + points = torch.tensor( + [ + [0.0, 0.0, 1.0], + [0.0, float(height), 1.0], + [float(width), float(height), 1.0], + [float(width), 0.0, 1.0], + ], + dtype=dtype, + device=device, + ) + new_points = torch.matmul(points, transposed_affine_matrix) + tr = torch.amin(new_points, dim=0, keepdim=True) + # Translate keypoints + transformed_points.sub_(tr) + # Estimate meta-data for image with inverted=True + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + new_width, new_height = _compute_affine_output_size(affine_vector, width, height) + canvas_size = (new_height, new_width) + + out_keypoints = transformed_points.reshape(original_shape) + out_keypoints = out_keypoints.to(original_dtype) + + return out_keypoints, canvas_size + + +def affine_keypoints( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, +): + return _affine_keypoints_with_expand( + keypoints=keypoints, + canvas_size=canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + expand=False, + ) + + +@_register_kernel_internal(affine, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _affine_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.KeyPoints: + output, canvas_size = affine_keypoints( + inpt.as_subclass(torch.Tensor), + canvas_size=inpt.canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def _affine_bounding_boxes_with_expand( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + expand: bool = False, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + if bounding_boxes.numel() == 0: + return bounding_boxes, canvas_size + + original_shape = bounding_boxes.shape + dtype = bounding_boxes.dtype + need_cast = not bounding_boxes.is_floating_point() + bounding_boxes = bounding_boxes.float() if need_cast else bounding_boxes.clone() + device = bounding_boxes.device + is_rotated = tv_tensors.is_rotated_bounding_format(format) + intermediate_format = tv_tensors.BoundingBoxFormat.XYXYXYXY if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + intermediate_shape = 8 if is_rotated else 4 + bounding_boxes = ( + convert_bounding_box_format(bounding_boxes, old_format=format, new_format=intermediate_format, inplace=True) + ).reshape(-1, intermediate_shape) + + angle, translate, shear, center = _affine_parse_args( + angle, translate, scale, shear, InterpolationMode.NEAREST, center + ) + + if center is None: + height, width = canvas_size + center = [width * 0.5, height * 0.5] + + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear, inverted=False) + transposed_affine_matrix = ( + torch.tensor( + affine_vector, + dtype=bounding_boxes.dtype, + device=device, + ) + .reshape(2, 3) + .T + ) + # 1) Let's transform bboxes into a tensor of 4 points (top-left, top-right, bottom-left, bottom-right corners). + # Tensor of points has shape (N * 4, 3), where N is the number of bboxes + # Single point structure is similar to + # [(xmin, ymin, 1), (xmax, ymin, 1), (xmax, ymax, 1), (xmin, ymax, 1)] + if is_rotated: + points = bounding_boxes.reshape(-1, 2) + else: + points = bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]].reshape(-1, 2) + points = torch.cat([points, torch.ones(points.shape[0], 1, device=device, dtype=bounding_boxes.dtype)], dim=-1) + # 2) Now let's transform the points using affine matrix + transformed_points = torch.matmul(points, transposed_affine_matrix) + # 3) Reshape transformed points to [N boxes, 4 points, x/y coords] + # and compute bounding box from 4 transformed points: + if is_rotated: + transformed_points = transformed_points.reshape(-1, 8) + out_bboxes = _parallelogram_to_bounding_boxes(transformed_points) + else: + transformed_points = transformed_points.reshape(-1, 4, 2) + out_bbox_mins, out_bbox_maxs = torch.aminmax(transformed_points, dim=1) + out_bboxes = torch.cat([out_bbox_mins, out_bbox_maxs], dim=1) + + if expand: + # Compute minimum point for transformed image frame: + # Points are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + height, width = canvas_size + points = torch.tensor( + [ + [0.0, 0.0, 1.0], + [0.0, float(height), 1.0], + [float(width), float(height), 1.0], + [float(width), 0.0, 1.0], + ], + dtype=bounding_boxes.dtype, + device=device, + ) + new_points = torch.matmul(points, transposed_affine_matrix) + tr = torch.amin(new_points, dim=0, keepdim=True) + # Translate bounding boxes + out_bboxes.sub_(tr.repeat((1, 4 if is_rotated else 2))) + # Estimate meta-data for image with inverted=True + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + new_width, new_height = _compute_affine_output_size(affine_vector, width, height) + canvas_size = (new_height, new_width) + + out_bboxes = clamp_bounding_boxes( + out_bboxes, format=intermediate_format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + out_bboxes = convert_bounding_box_format( + out_bboxes, old_format=intermediate_format, new_format=format, inplace=True + ).reshape(original_shape) + + if need_cast: + out_bboxes = out_bboxes.to(dtype) + return out_bboxes, canvas_size + + +def affine_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> torch.Tensor: + out_box, _ = _affine_bounding_boxes_with_expand( + bounding_boxes, + format=format, + canvas_size=canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + expand=False, + clamping_mode=clamping_mode, + ) + return out_box + + +@_register_kernel_internal(affine, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _affine_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.BoundingBoxes: + output = affine_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + + +def affine_mask( + mask: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = affine_image( + mask, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=InterpolationMode.NEAREST, + fill=fill, + center=center, + ) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(affine, tv_tensors.Mask, tv_tensor_wrapper=False) +def _affine_mask_dispatch( + inpt: tv_tensors.Mask, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.Mask: + output = affine_mask( + inpt.as_subclass(torch.Tensor), + angle=angle, + translate=translate, + scale=scale, + shear=shear, + fill=fill, + center=center, + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(affine, tv_tensors.Video) +def affine_video( + video: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + return affine_image( + video, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=interpolation, + fill=fill, + center=center, + ) + + +def rotate( + inpt: torch.Tensor, + angle: float, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomRotation` for details.""" + if torch.jit.is_scripting(): + return rotate_image(inpt, angle=angle, interpolation=interpolation, expand=expand, fill=fill, center=center) + + _log_api_usage_once(rotate) + + kernel = _get_kernel(rotate, type(inpt)) + return kernel(inpt, angle=angle, interpolation=interpolation, expand=expand, fill=fill, center=center) + + +@_register_kernel_internal(rotate, torch.Tensor) +@_register_kernel_internal(rotate, tv_tensors.Image) +def rotate_image( + image: torch.Tensor, + angle: float, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + angle = angle % 360 # shift angle to [0, 360) range + + # fast path: transpose without affine transform + if center is None: + if angle == 0: + return image.clone() + if angle == 180: + return torch.rot90(image, k=2, dims=(-2, -1)) + + if expand or image.shape[-1] == image.shape[-2]: + if angle == 90: + return torch.rot90(image, k=1, dims=(-2, -1)) + if angle == 270: + return torch.rot90(image, k=3, dims=(-2, -1)) + + interpolation = _check_interpolation(interpolation) + + input_height, input_width = image.shape[-2:] + + center_f = [0.0, 0.0] + if center is not None: + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [(c - s * 0.5) for c, s in zip(center, [input_width, input_height])] + + # due to current incoherence of rotation angle direction between affine and rotate implementations + # we need to set -angle. + matrix = _get_inverse_affine_matrix(center_f, -angle, [0.0, 0.0], 1.0, [0.0, 0.0]) + + _assert_grid_transform_inputs(image, matrix, interpolation.value, fill, ["nearest", "bilinear"]) + + output_width, output_height = ( + _compute_affine_output_size(matrix, input_width, input_height) if expand else (input_width, input_height) + ) + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=image.device).reshape(1, 2, 3) + grid = _affine_grid(theta, w=input_width, h=input_height, ow=output_width, oh=output_height) + return _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + +@_register_kernel_internal(rotate, PIL.Image.Image) +def _rotate_image_pil( + image: PIL.Image.Image, + angle: float, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> PIL.Image.Image: + interpolation = _check_interpolation(interpolation) + + return _FP.rotate( + image, angle, interpolation=pil_modes_mapping[interpolation], expand=expand, fill=fill, center=center # type: ignore[arg-type] + ) + + +def rotate_keypoints( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, +) -> tuple[torch.Tensor, tuple[int, int]]: + return _affine_keypoints_with_expand( + keypoints=keypoints, + canvas_size=canvas_size, + angle=-angle, + translate=[0.0, 0.0], + scale=1.0, + shear=[0.0, 0.0], + center=center, + expand=expand, + ) + + +@_register_kernel_internal(rotate, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _rotate_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, angle: float, expand: bool = False, center: Optional[list[float]] = None, **kwargs +) -> tv_tensors.KeyPoints: + output, canvas_size = rotate_keypoints( + inpt, canvas_size=inpt.canvas_size, angle=angle, center=center, expand=expand + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def rotate_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + return _affine_bounding_boxes_with_expand( + bounding_boxes, + format=format, + canvas_size=canvas_size, + angle=-angle, + translate=[0.0, 0.0], + scale=1.0, + shear=[0.0, 0.0], + center=center, + expand=expand, + clamping_mode=clamping_mode, + ) + + +@_register_kernel_internal(rotate, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _rotate_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, angle: float, expand: bool = False, center: Optional[list[float]] = None, **kwargs +) -> tv_tensors.BoundingBoxes: + output, canvas_size = rotate_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + angle=angle, + expand=expand, + center=center, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def rotate_mask( + mask: torch.Tensor, + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = rotate_image( + mask, + angle=angle, + expand=expand, + interpolation=InterpolationMode.NEAREST, + fill=fill, + center=center, + ) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(rotate, tv_tensors.Mask, tv_tensor_wrapper=False) +def _rotate_mask_dispatch( + inpt: tv_tensors.Mask, + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, + **kwargs, +) -> tv_tensors.Mask: + output = rotate_mask(inpt.as_subclass(torch.Tensor), angle=angle, expand=expand, fill=fill, center=center) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(rotate, tv_tensors.Video) +def rotate_video( + video: torch.Tensor, + angle: float, + interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + return rotate_image(video, angle, interpolation=interpolation, expand=expand, fill=fill, center=center) + + +def pad( + inpt: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Pad` for details.""" + if torch.jit.is_scripting(): + return pad_image(inpt, padding=padding, fill=fill, padding_mode=padding_mode) + + _log_api_usage_once(pad) + + kernel = _get_kernel(pad, type(inpt)) + return kernel(inpt, padding=padding, fill=fill, padding_mode=padding_mode) + + +def _parse_pad_padding(padding: Union[int, list[int]]) -> list[int]: + if isinstance(padding, int): + pad_left = pad_right = pad_top = pad_bottom = padding + elif isinstance(padding, (tuple, list)): + if len(padding) == 1: + pad_left = pad_right = pad_top = pad_bottom = padding[0] + elif len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + elif len(padding) == 4: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + else: + raise ValueError( + f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple" + ) + else: + raise TypeError(f"`padding` should be an integer or tuple or list of integers, but got {padding}") + + return [pad_left, pad_right, pad_top, pad_bottom] + + +@_register_kernel_internal(pad, torch.Tensor) +@_register_kernel_internal(pad, tv_tensors.Image) +def pad_image( + image: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + # Be aware that while `padding` has order `[left, top, right, bottom]`, `torch_padding` uses + # `[left, right, top, bottom]`. This stems from the fact that we align our API with PIL, but need to use `torch_pad` + # internally. + torch_padding = _parse_pad_padding(padding) + + if padding_mode not in ("constant", "edge", "reflect", "symmetric"): + raise ValueError( + f"`padding_mode` should be either `'constant'`, `'edge'`, `'reflect'` or `'symmetric'`, " + f"but got `'{padding_mode}'`." + ) + + if fill is None: + fill = 0 + + if isinstance(fill, (int, float)): + return _pad_with_scalar_fill(image, torch_padding, fill=fill, padding_mode=padding_mode) + elif len(fill) == 1: + return _pad_with_scalar_fill(image, torch_padding, fill=fill[0], padding_mode=padding_mode) + else: + return _pad_with_vector_fill(image, torch_padding, fill=fill, padding_mode=padding_mode) + + +def _pad_with_scalar_fill( + image: torch.Tensor, + torch_padding: list[int], + fill: Union[int, float], + padding_mode: str, +) -> torch.Tensor: + shape = image.shape + num_channels, height, width = shape[-3:] + + batch_size = 1 + for s in shape[:-3]: + batch_size *= s + + image = image.reshape(batch_size, num_channels, height, width) + + if padding_mode == "edge": + # Similar to the padding order, `torch_pad`'s PIL's padding modes don't have the same names. Thus, we map + # the PIL name for the padding mode, which we are also using for our API, to the corresponding `torch_pad` + # name. + padding_mode = "replicate" + + if padding_mode == "constant": + image = torch_pad(image, torch_padding, mode=padding_mode, value=float(fill)) + elif padding_mode in ("reflect", "replicate"): + # `torch_pad` only supports `"reflect"` or `"replicate"` padding for floating point inputs. + # TODO: See https://github.com/pytorch/pytorch/issues/40763 + dtype = image.dtype + if not image.is_floating_point(): + needs_cast = True + image = image.to(torch.float32) + else: + needs_cast = False + + image = torch_pad(image, torch_padding, mode=padding_mode) + + if needs_cast: + image = image.to(dtype) + else: # padding_mode == "symmetric" + image = _pad_symmetric(image, torch_padding) + + new_height, new_width = image.shape[-2:] + + return image.reshape(shape[:-3] + (num_channels, new_height, new_width)) + + +# TODO: This should be removed once torch_pad supports non-scalar padding values +def _pad_with_vector_fill( + image: torch.Tensor, + torch_padding: list[int], + fill: list[float], + padding_mode: str, +) -> torch.Tensor: + if padding_mode != "constant": + raise ValueError(f"Padding mode '{padding_mode}' is not supported if fill is not scalar") + + output = _pad_with_scalar_fill(image, torch_padding, fill=0, padding_mode="constant") + left, right, top, bottom = torch_padding + + # We are creating the tensor in the autodetected dtype first and convert to the right one after to avoid an implicit + # float -> int conversion. That happens for example for the valid input of a uint8 image with floating point fill + # value. + fill = torch.tensor(fill, device=image.device).to(dtype=image.dtype).reshape(-1, 1, 1) + + if top > 0: + output[..., :top, :] = fill + if left > 0: + output[..., :, :left] = fill + if bottom > 0: + output[..., -bottom:, :] = fill + if right > 0: + output[..., :, -right:] = fill + return output + + +_pad_image_pil = _register_kernel_internal(pad, PIL.Image.Image)(_FP.pad) + + +@_register_kernel_internal(pad, tv_tensors.Mask) +def pad_mask( + mask: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + if fill is None: + fill = 0 + + if isinstance(fill, (tuple, list)): + raise ValueError("Non-scalar fill value is not supported") + + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = pad_image(mask, padding=padding, fill=fill, padding_mode=padding_mode) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +def pad_keypoints( + keypoints: torch.Tensor, canvas_size: tuple[int, int], padding: list[int], padding_mode: str = "constant" +): + SUPPORTED_MODES = ["constant"] + if padding_mode not in SUPPORTED_MODES: + # TODO: add support of other padding modes + raise ValueError( + f"Padding mode '{padding_mode}' is not supported with KeyPoints" + f" (supported modes are {', '.join(SUPPORTED_MODES)})" + ) + left, right, top, bottom = _parse_pad_padding(padding) + pad = torch.tensor([left, top], dtype=keypoints.dtype, device=keypoints.device) + canvas_size = (canvas_size[0] + top + bottom, canvas_size[1] + left + right) + return keypoints + pad, canvas_size + + +@_register_kernel_internal(pad, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _pad_keypoints_dispatch( + keypoints: tv_tensors.KeyPoints, padding: list[int], padding_mode: str = "constant", **kwargs +) -> tv_tensors.KeyPoints: + output, canvas_size = pad_keypoints( + keypoints.as_subclass(torch.Tensor), + canvas_size=keypoints.canvas_size, + padding=padding, + padding_mode=padding_mode, + ) + return tv_tensors.wrap(output, like=keypoints, canvas_size=canvas_size) + + +def pad_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + padding: list[int], + padding_mode: str = "constant", + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + if padding_mode not in ["constant"]: + # TODO: add support of other padding modes + raise ValueError(f"Padding mode '{padding_mode}' is not supported with bounding boxes") + + left, right, top, bottom = _parse_pad_padding(padding) + + if format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + pad = [left, top, left, top, left, top, left, top] + elif format == tv_tensors.BoundingBoxFormat.XYWHR or format == tv_tensors.BoundingBoxFormat.CXCYWHR: + pad = [left, top, 0, 0, 0] + elif format == tv_tensors.BoundingBoxFormat.XYXY: + pad = [left, top, left, top] + else: + pad = [left, top, 0, 0] + bounding_boxes = bounding_boxes + torch.tensor(pad, dtype=bounding_boxes.dtype, device=bounding_boxes.device) + + height, width = canvas_size + height += top + bottom + width += left + right + canvas_size = (height, width) + + return ( + clamp_bounding_boxes(bounding_boxes, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode), + canvas_size, + ) + + +@_register_kernel_internal(pad, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _pad_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, padding: list[int], padding_mode: str = "constant", **kwargs +) -> tv_tensors.BoundingBoxes: + output, canvas_size = pad_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + padding=padding, + padding_mode=padding_mode, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(pad, tv_tensors.Video) +def pad_video( + video: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + return pad_image(video, padding, fill=fill, padding_mode=padding_mode) + + +def crop(inpt: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomCrop` for details.""" + if torch.jit.is_scripting(): + return crop_image(inpt, top=top, left=left, height=height, width=width) + + _log_api_usage_once(crop) + + kernel = _get_kernel(crop, type(inpt)) + return kernel(inpt, top=top, left=left, height=height, width=width) + + +@_register_kernel_internal(crop, torch.Tensor) +@_register_kernel_internal(crop, tv_tensors.Image) +def crop_image(image: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + h, w = image.shape[-2:] + + right = left + width + bottom = top + height + + if left < 0 or top < 0 or right > w or bottom > h: + image = image[..., max(top, 0) : bottom, max(left, 0) : right] + torch_padding = [ + max(min(right, 0) - left, 0), + max(right - max(w, left), 0), + max(min(bottom, 0) - top, 0), + max(bottom - max(h, top), 0), + ] + return _pad_with_scalar_fill(image, torch_padding, fill=0, padding_mode="constant") + return image[..., top:bottom, left:right] + + +_crop_image_pil = _FP.crop +_register_kernel_internal(crop, PIL.Image.Image)(_crop_image_pil) + + +def crop_keypoints( + keypoints: torch.Tensor, + top: int, + left: int, + height: int, + width: int, +) -> tuple[torch.Tensor, tuple[int, int]]: + + keypoints = keypoints - torch.tensor([left, top], dtype=keypoints.dtype, device=keypoints.device) + canvas_size = (height, width) + + return keypoints, canvas_size + + +@_register_kernel_internal(crop, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _crop_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, top: int, left: int, height: int, width: int +) -> tv_tensors.KeyPoints: + output, canvas_size = crop_keypoints(inpt.as_subclass(torch.Tensor), top=top, left=left, height=height, width=width) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def crop_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + top: int, + left: int, + height: int, + width: int, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + + # Crop or implicit pad if left and/or top have negative values: + if format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + sub = [left, top, left, top, left, top, left, top] + elif format == tv_tensors.BoundingBoxFormat.XYWHR or format == tv_tensors.BoundingBoxFormat.CXCYWHR: + sub = [left, top, 0, 0, 0] + elif format == tv_tensors.BoundingBoxFormat.XYXY: + sub = [left, top, left, top] + else: + sub = [left, top, 0, 0] + + bounding_boxes = bounding_boxes - torch.tensor(sub, dtype=bounding_boxes.dtype, device=bounding_boxes.device) + canvas_size = (height, width) + + if format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + bounding_boxes = _parallelogram_to_bounding_boxes(bounding_boxes) + + return ( + clamp_bounding_boxes(bounding_boxes, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode), + canvas_size, + ) + + +@_register_kernel_internal(crop, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _crop_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, top: int, left: int, height: int, width: int +) -> tv_tensors.BoundingBoxes: + output, canvas_size = crop_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + top=top, + left=left, + height=height, + width=width, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(crop, tv_tensors.Mask) +def crop_mask(mask: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = crop_image(mask, top, left, height, width) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(crop, tv_tensors.Video) +def crop_video(video: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + return crop_image(video, top, left, height, width) + + +def perspective( + inpt: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomPerspective` for details.""" + if torch.jit.is_scripting(): + return perspective_image( + inpt, + startpoints=startpoints, + endpoints=endpoints, + interpolation=interpolation, + fill=fill, + coefficients=coefficients, + ) + + _log_api_usage_once(perspective) + + kernel = _get_kernel(perspective, type(inpt)) + return kernel( + inpt, + startpoints=startpoints, + endpoints=endpoints, + interpolation=interpolation, + fill=fill, + coefficients=coefficients, + ) + + +def _perspective_grid(coeffs: list[float], ow: int, oh: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + # https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/ + # src/libImaging/Geometry.c#L394 + + # + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + # + theta1 = torch.tensor( + [[[coeffs[0], coeffs[1], coeffs[2]], [coeffs[3], coeffs[4], coeffs[5]]]], dtype=dtype, device=device + ) + theta2 = torch.tensor([[[coeffs[6], coeffs[7], 1.0], [coeffs[6], coeffs[7], 1.0]]], dtype=dtype, device=device) + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device) + x_grid = torch.linspace(d, ow + d - 1.0, steps=ow, device=device, dtype=dtype) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(d, oh + d - 1.0, steps=oh, device=device, dtype=dtype).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta1 = theta1.transpose(1, 2).div_(torch.tensor([0.5 * ow, 0.5 * oh], dtype=dtype, device=device)) + shape = (1, oh * ow, 3) + output_grid1 = base_grid.view(shape).bmm(rescaled_theta1) + output_grid2 = base_grid.view(shape).bmm(theta2.transpose(1, 2)) + + output_grid = output_grid1.div_(output_grid2).sub_(1.0) + return output_grid.view(1, oh, ow, 2) + + +def _perspective_coefficients( + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]], +) -> list[float]: + if coefficients is not None: + if startpoints is not None and endpoints is not None: + raise ValueError("The startpoints/endpoints and the coefficients shouldn't be defined concurrently.") + elif len(coefficients) != 8: + raise ValueError("Argument coefficients should have 8 float values") + return coefficients + elif startpoints is not None and endpoints is not None: + return _get_perspective_coeffs(startpoints, endpoints) + else: + raise ValueError("Either the startpoints/endpoints or the coefficients must have non `None` values.") + + +@_register_kernel_internal(perspective, torch.Tensor) +@_register_kernel_internal(perspective, tv_tensors.Image) +def perspective_image( + image: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + interpolation = _check_interpolation(interpolation) + + _assert_grid_transform_inputs( + image, + matrix=None, + interpolation=interpolation.value, + fill=fill, + supported_interpolation_modes=["nearest", "bilinear"], + coeffs=perspective_coeffs, + ) + + oh, ow = image.shape[-2:] + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + grid = _perspective_grid(perspective_coeffs, ow=ow, oh=oh, dtype=dtype, device=image.device) + return _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + +@_register_kernel_internal(perspective, PIL.Image.Image) +def _perspective_image_pil( + image: PIL.Image.Image, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> PIL.Image.Image: + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + interpolation = _check_interpolation(interpolation) + return _FP.perspective(image, perspective_coeffs, interpolation=pil_modes_mapping[interpolation], fill=fill) + + +def perspective_keypoints( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, +): + if keypoints.numel() == 0: + return keypoints + dtype = keypoints.dtype if torch.is_floating_point(keypoints) else torch.float32 + device = keypoints.device + original_shape = keypoints.shape + + keypoints = keypoints.clone().reshape(-1, 2) + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + + denom = perspective_coeffs[0] * perspective_coeffs[4] - perspective_coeffs[1] * perspective_coeffs[3] + if denom == 0: + raise RuntimeError( + f"Provided perspective_coeffs {perspective_coeffs} can not be inverted to transform keypoints. " + f"Denominator is zero, denom={denom}" + ) + + theta1, theta2 = _compute_perspective_thetas(perspective_coeffs, dtype, device, denom) + points = torch.cat([keypoints, torch.ones(keypoints.shape[0], 1, device=keypoints.device)], dim=-1) + + numer_points = torch.matmul(points, theta1.T) + denom_points = torch.matmul(points, theta2.T) + transformed_points = numer_points.div_(denom_points) + return transformed_points.to(keypoints.dtype).reshape(original_shape) + + +@_register_kernel_internal(perspective, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _perspective_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.KeyPoints: + output = perspective_keypoints( + inpt.as_subclass(torch.Tensor), + canvas_size=inpt.canvas_size, + startpoints=startpoints, + endpoints=endpoints, + coefficients=coefficients, + ) + return tv_tensors.wrap(output, like=inpt) + + +def perspective_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> torch.Tensor: + if bounding_boxes.numel() == 0: + return bounding_boxes + + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + + original_shape = bounding_boxes.shape + original_dtype = bounding_boxes.dtype + is_rotated = tv_tensors.is_rotated_bounding_format(format) + intermediate_format = tv_tensors.BoundingBoxFormat.XYXYXYXY if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + # TODO: first cast to float if bbox is int64 before convert_bounding_box_format + bounding_boxes = ( + convert_bounding_box_format(bounding_boxes, old_format=format, new_format=intermediate_format) + ).reshape(-1, 8 if is_rotated else 4) + + dtype = bounding_boxes.dtype if torch.is_floating_point(bounding_boxes) else torch.float32 + device = bounding_boxes.device + + # perspective_coeffs are computed as endpoint -> start point + # We have to invert perspective_coeffs for bboxes: + # (x, y) - end point and (x_out, y_out) - start point + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + # and we would like to get: + # x = (inv_coeffs[0] * x_out + inv_coeffs[1] * y_out + inv_coeffs[2]) + # / (inv_coeffs[6] * x_out + inv_coeffs[7] * y_out + 1) + # y = (inv_coeffs[3] * x_out + inv_coeffs[4] * y_out + inv_coeffs[5]) + # / (inv_coeffs[6] * x_out + inv_coeffs[7] * y_out + 1) + # and compute inv_coeffs in terms of coeffs + + denom = perspective_coeffs[0] * perspective_coeffs[4] - perspective_coeffs[1] * perspective_coeffs[3] + if denom == 0: + raise RuntimeError( + f"Provided perspective_coeffs {perspective_coeffs} can not be inverted to transform bounding boxes. " + f"Denominator is zero, denom={denom}" + ) + + theta1, theta2 = _compute_perspective_thetas(perspective_coeffs, dtype, device, denom) + + # 1) Let's transform bboxes into a tensor of 4 points (top-left, top-right, bottom-left, bottom-right corners). + # Tensor of points has shape (N * 4, 3), where N is the number of bboxes + # Single point structure is similar to + # [(xmin, ymin, 1), (xmax, ymin, 1), (xmax, ymax, 1), (xmin, ymax, 1)] + points = bounding_boxes if is_rotated else bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]] + points = points.reshape(-1, 2) + points = torch.cat([points, torch.ones(points.shape[0], 1, device=points.device)], dim=-1) + # 2) Now let's transform the points using perspective matrices + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + + numer_points = torch.matmul(points, theta1.T) + denom_points = torch.matmul(points, theta2.T) + transformed_points = numer_points.div_(denom_points) + + # 3) Reshape transformed points to [N boxes, 4 points, x/y coords] + # and compute bounding box from 4 transformed points: + if is_rotated: + transformed_points = transformed_points.reshape(-1, 8) + out_bboxes = _parallelogram_to_bounding_boxes(transformed_points) + else: + transformed_points = transformed_points.reshape(-1, 4, 2) + out_bbox_mins, out_bbox_maxs = torch.aminmax(transformed_points, dim=1) + out_bboxes = torch.cat([out_bbox_mins, out_bbox_maxs], dim=1) + + out_bboxes = clamp_bounding_boxes( + out_bboxes, format=intermediate_format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + + out_bboxes = convert_bounding_box_format( + out_bboxes, old_format=intermediate_format, new_format=format, inplace=True + ).reshape(original_shape) + + out_bboxes = out_bboxes.to(original_dtype) + return out_bboxes + + +def _compute_perspective_thetas( + perspective_coeffs: list[float], + dtype: torch.dtype, + device: torch.device, + denom: float, +) -> tuple[torch.Tensor, torch.Tensor]: + inv_coeffs = [ + (perspective_coeffs[4] - perspective_coeffs[5] * perspective_coeffs[7]) / denom, + (-perspective_coeffs[1] + perspective_coeffs[2] * perspective_coeffs[7]) / denom, + (perspective_coeffs[1] * perspective_coeffs[5] - perspective_coeffs[2] * perspective_coeffs[4]) / denom, + (-perspective_coeffs[3] + perspective_coeffs[5] * perspective_coeffs[6]) / denom, + (perspective_coeffs[0] - perspective_coeffs[2] * perspective_coeffs[6]) / denom, + (-perspective_coeffs[0] * perspective_coeffs[5] + perspective_coeffs[2] * perspective_coeffs[3]) / denom, + (-perspective_coeffs[4] * perspective_coeffs[6] + perspective_coeffs[3] * perspective_coeffs[7]) / denom, + (-perspective_coeffs[0] * perspective_coeffs[7] + perspective_coeffs[1] * perspective_coeffs[6]) / denom, + ] + + theta1 = torch.tensor( + [[inv_coeffs[0], inv_coeffs[1], inv_coeffs[2]], [inv_coeffs[3], inv_coeffs[4], inv_coeffs[5]]], + dtype=dtype, + device=device, + ) + + theta2 = torch.tensor( + [[inv_coeffs[6], inv_coeffs[7], 1.0], [inv_coeffs[6], inv_coeffs[7], 1.0]], dtype=dtype, device=device + ) + + return theta1, theta2 + + +@_register_kernel_internal(perspective, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _perspective_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.BoundingBoxes: + output = perspective_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + startpoints=startpoints, + endpoints=endpoints, + coefficients=coefficients, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + + +def perspective_mask( + mask: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = perspective_image( + mask, startpoints, endpoints, interpolation=InterpolationMode.NEAREST, fill=fill, coefficients=coefficients + ) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(perspective, tv_tensors.Mask, tv_tensor_wrapper=False) +def _perspective_mask_dispatch( + inpt: tv_tensors.Mask, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.Mask: + output = perspective_mask( + inpt.as_subclass(torch.Tensor), + startpoints=startpoints, + endpoints=endpoints, + fill=fill, + coefficients=coefficients, + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(perspective, tv_tensors.Video) +def perspective_video( + video: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + return perspective_image( + video, startpoints, endpoints, interpolation=interpolation, fill=fill, coefficients=coefficients + ) + + +def elastic( + inpt: torch.Tensor, + displacement: torch.Tensor, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.ElasticTransform` for details.""" + if torch.jit.is_scripting(): + return elastic_image(inpt, displacement=displacement, interpolation=interpolation, fill=fill) + + _log_api_usage_once(elastic) + + kernel = _get_kernel(elastic, type(inpt)) + return kernel(inpt, displacement=displacement, interpolation=interpolation, fill=fill) + + +elastic_transform = elastic + + +@_register_kernel_internal(elastic, torch.Tensor) +@_register_kernel_internal(elastic, tv_tensors.Image) +def elastic_image( + image: torch.Tensor, + displacement: torch.Tensor, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + + interpolation = _check_interpolation(interpolation) + + height, width = image.shape[-2:] + device = image.device + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + + # Patch: elastic transform should support (cpu,f16) input + is_cpu_half = device.type == "cpu" and dtype == torch.float16 + if is_cpu_half: + image = image.to(torch.float32) + dtype = torch.float32 + + # We are aware that if input image dtype is uint8 and displacement is float64 then + # displacement will be cast to float32 and all computations will be done with float32 + # We can fix this later if needed + + expected_shape = (1, height, width, 2) + if expected_shape != displacement.shape: + raise ValueError(f"Argument displacement shape should be {expected_shape}, but given {displacement.shape}") + + grid = _create_identity_grid((height, width), device=device, dtype=dtype).add_( + displacement.to(dtype=dtype, device=device) + ) + output = _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + if is_cpu_half: + output = output.to(torch.float16) + + return output + + +@_register_kernel_internal(elastic, PIL.Image.Image) +def _elastic_image_pil( + image: PIL.Image.Image, + displacement: torch.Tensor, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> PIL.Image.Image: + t_img = pil_to_tensor(image) + output = elastic_image(t_img, displacement, interpolation=interpolation, fill=fill) + return to_pil_image(output, mode=image.mode) + + +def _create_identity_grid(size: tuple[int, int], device: torch.device, dtype: torch.dtype) -> torch.Tensor: + sy, sx = size + base_grid = torch.empty(1, sy, sx, 2, device=device, dtype=dtype) + x_grid = torch.linspace((-sx + 1) / sx, (sx - 1) / sx, sx, device=device, dtype=dtype) + base_grid[..., 0].copy_(x_grid) + + y_grid = torch.linspace((-sy + 1) / sy, (sy - 1) / sy, sy, device=device, dtype=dtype).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + + return base_grid + + +def elastic_keypoints( + keypoints: torch.Tensor, canvas_size: tuple[int, int], displacement: torch.Tensor +) -> torch.Tensor: + expected_shape = (1, canvas_size[0], canvas_size[1], 2) + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + elif displacement.shape != expected_shape: + raise ValueError(f"Argument displacement shape should be {expected_shape}, but given {displacement.shape}") + + if keypoints.numel() == 0: + return keypoints + + device = keypoints.device + dtype = keypoints.dtype if torch.is_floating_point(keypoints) else torch.float32 + + if displacement.dtype != dtype or displacement.device != device: + displacement = displacement.to(dtype=dtype, device=device) + + original_shape = keypoints.shape + keypoints = keypoints.clone().reshape(-1, 2) + + id_grid = _create_identity_grid(canvas_size, device=device, dtype=dtype) + inv_grid = id_grid.sub_(displacement) + + index_xy = keypoints.to(dtype=torch.long) + index_x, index_y = index_xy[:, 0], index_xy[:, 1] + # Unlike bounding boxes, this may not work well. + index_x.clamp_(0, inv_grid.shape[2] - 1) + index_y.clamp_(0, inv_grid.shape[1] - 1) + + t_size = torch.tensor(canvas_size[::-1], device=displacement.device, dtype=displacement.dtype) + transformed_points = inv_grid[0, index_y, index_x, :].add_(1).mul_(0.5 * t_size).sub_(0.5) + + return transformed_points.to(keypoints.dtype).reshape(original_shape) + + +@_register_kernel_internal(elastic, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _elastic_keypoints_dispatch(inpt: tv_tensors.KeyPoints, displacement: torch.Tensor, **kwargs): + output = elastic_keypoints(inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size, displacement=displacement) + return tv_tensors.wrap(output, like=inpt) + + +def elastic_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + displacement: torch.Tensor, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> torch.Tensor: + expected_shape = (1, canvas_size[0], canvas_size[1], 2) + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + elif displacement.shape != expected_shape: + raise ValueError(f"Argument displacement shape should be {expected_shape}, but given {displacement.shape}") + + if bounding_boxes.numel() == 0: + return bounding_boxes + + # TODO: add in docstring about approximation we are doing for grid inversion + device = bounding_boxes.device + dtype = bounding_boxes.dtype if torch.is_floating_point(bounding_boxes) else torch.float32 + is_rotated = tv_tensors.is_rotated_bounding_format(format) + + if displacement.dtype != dtype or displacement.device != device: + displacement = displacement.to(dtype=dtype, device=device) + + original_shape = bounding_boxes.shape + # TODO: first cast to float if bbox is int64 before convert_bounding_box_format + intermediate_format = tv_tensors.BoundingBoxFormat.CXCYWHR if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + + bounding_boxes = ( + convert_bounding_box_format(bounding_boxes.clone(), old_format=format, new_format=intermediate_format) + ).reshape(-1, 5 if is_rotated else 4) + + id_grid = _create_identity_grid(canvas_size, device=device, dtype=dtype) + # We construct an approximation of inverse grid as inv_grid = id_grid - displacement + # This is not an exact inverse of the grid + inv_grid = id_grid.sub_(displacement) + + # Get points from bboxes + points = bounding_boxes[:, :2] if is_rotated else bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]] + points = points.reshape(-1, 2) + if points.is_floating_point(): + points = points.ceil_() + index_xy = points.to(dtype=torch.long) + index_x, index_y = index_xy[:, 0], index_xy[:, 1] + + # Transform points: + t_size = torch.tensor(canvas_size[::-1], device=displacement.device, dtype=displacement.dtype) + transformed_points = inv_grid[0, index_y, index_x, :].add_(1).mul_(0.5 * t_size).sub_(0.5) + + if is_rotated: + transformed_points = transformed_points.reshape(-1, 2) + out_bboxes = torch.cat([transformed_points, bounding_boxes[:, 2:]], dim=1).to(bounding_boxes.dtype) + else: + transformed_points = transformed_points.reshape(-1, 4, 2) + out_bbox_mins, out_bbox_maxs = torch.aminmax(transformed_points, dim=1) + out_bboxes = torch.cat([out_bbox_mins, out_bbox_maxs], dim=1).to(bounding_boxes.dtype) + + out_bboxes = clamp_bounding_boxes( + out_bboxes, format=intermediate_format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + + return convert_bounding_box_format( + out_bboxes, old_format=intermediate_format, new_format=format, inplace=False + ).reshape(original_shape) + + +@_register_kernel_internal(elastic, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _elastic_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, displacement: torch.Tensor, **kwargs +) -> tv_tensors.BoundingBoxes: + output = elastic_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + displacement=displacement, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + + +def elastic_mask( + mask: torch.Tensor, + displacement: torch.Tensor, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = elastic_image(mask, displacement=displacement, interpolation=InterpolationMode.NEAREST, fill=fill) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(elastic, tv_tensors.Mask, tv_tensor_wrapper=False) +def _elastic_mask_dispatch( + inpt: tv_tensors.Mask, displacement: torch.Tensor, fill: _FillTypeJIT = None, **kwargs +) -> tv_tensors.Mask: + output = elastic_mask(inpt.as_subclass(torch.Tensor), displacement=displacement, fill=fill) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(elastic, tv_tensors.Video) +def elastic_video( + video: torch.Tensor, + displacement: torch.Tensor, + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + return elastic_image(video, displacement, interpolation=interpolation, fill=fill) + + +def center_crop(inpt: torch.Tensor, output_size: list[int]) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomCrop` for details.""" + if torch.jit.is_scripting(): + return center_crop_image(inpt, output_size=output_size) + + _log_api_usage_once(center_crop) + + kernel = _get_kernel(center_crop, type(inpt)) + return kernel(inpt, output_size=output_size) + + +def _center_crop_parse_output_size(output_size: list[int]) -> list[int]: + if isinstance(output_size, numbers.Number): + s = int(output_size) + return [s, s] + elif isinstance(output_size, (tuple, list)) and len(output_size) == 1: + return [output_size[0], output_size[0]] + else: + return list(output_size) + + +def _center_crop_compute_padding(crop_height: int, crop_width: int, image_height: int, image_width: int) -> list[int]: + return [ + (crop_width - image_width) // 2 if crop_width > image_width else 0, + (crop_height - image_height) // 2 if crop_height > image_height else 0, + (crop_width - image_width + 1) // 2 if crop_width > image_width else 0, + (crop_height - image_height + 1) // 2 if crop_height > image_height else 0, + ] + + +def _center_crop_compute_crop_anchor( + crop_height: int, crop_width: int, image_height: int, image_width: int +) -> tuple[int, int]: + crop_top = int(round((image_height - crop_height) / 2.0)) + crop_left = int(round((image_width - crop_width) / 2.0)) + return crop_top, crop_left + + +@_register_kernel_internal(center_crop, torch.Tensor) +@_register_kernel_internal(center_crop, tv_tensors.Image) +def center_crop_image(image: torch.Tensor, output_size: list[int]) -> torch.Tensor: + crop_height, crop_width = _center_crop_parse_output_size(output_size) + shape = image.shape + if image.numel() == 0: + return image.reshape(shape[:-2] + (crop_height, crop_width)) + image_height, image_width = shape[-2:] + + if crop_height > image_height or crop_width > image_width: + padding_ltrb = _center_crop_compute_padding(crop_height, crop_width, image_height, image_width) + image = torch_pad(image, _parse_pad_padding(padding_ltrb), value=0.0) + + image_height, image_width = image.shape[-2:] + if crop_width == image_width and crop_height == image_height: + return image + + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, image_height, image_width) + return image[..., crop_top : (crop_top + crop_height), crop_left : (crop_left + crop_width)] + + +@_register_kernel_internal(center_crop, PIL.Image.Image) +def _center_crop_image_pil(image: PIL.Image.Image, output_size: list[int]) -> PIL.Image.Image: + crop_height, crop_width = _center_crop_parse_output_size(output_size) + image_height, image_width = _get_size_image_pil(image) + + if crop_height > image_height or crop_width > image_width: + padding_ltrb = _center_crop_compute_padding(crop_height, crop_width, image_height, image_width) + image = _pad_image_pil(image, padding_ltrb, fill=0) + + image_height, image_width = _get_size_image_pil(image) + if crop_width == image_width and crop_height == image_height: + return image + + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, image_height, image_width) + return _crop_image_pil(image, crop_top, crop_left, crop_height, crop_width) + + +def center_crop_keypoints(inpt: torch.Tensor, canvas_size: tuple[int, int], output_size: list[int]): + crop_height, crop_width = _center_crop_parse_output_size(output_size) + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, *canvas_size) + return crop_keypoints(inpt, top=crop_top, left=crop_left, height=crop_height, width=crop_width) + + +@_register_kernel_internal(center_crop, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _center_crop_keypoints_dispatch(inpt: tv_tensors.KeyPoints, output_size: list[int]) -> tv_tensors.KeyPoints: + output, canvas_size = center_crop_keypoints( + inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size, output_size=output_size + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def center_crop_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + output_size: list[int], + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + crop_height, crop_width = _center_crop_parse_output_size(output_size) + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, *canvas_size) + return crop_bounding_boxes( + bounding_boxes, + format, + top=crop_top, + left=crop_left, + height=crop_height, + width=crop_width, + clamping_mode=clamping_mode, + ) + + +@_register_kernel_internal(center_crop, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _center_crop_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, output_size: list[int] +) -> tv_tensors.BoundingBoxes: + output, canvas_size = center_crop_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + output_size=output_size, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(center_crop, tv_tensors.Mask) +def center_crop_mask(mask: torch.Tensor, output_size: list[int]) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = center_crop_image(image=mask, output_size=output_size) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(center_crop, tv_tensors.Video) +def center_crop_video(video: torch.Tensor, output_size: list[int]) -> torch.Tensor: + return center_crop_image(video, output_size) + + +def resized_crop( + inpt: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomResizedCrop` for details.""" + if torch.jit.is_scripting(): + return resized_crop_image( + inpt, + top=top, + left=left, + height=height, + width=width, + size=size, + interpolation=interpolation, + antialias=antialias, + ) + + _log_api_usage_once(resized_crop) + + kernel = _get_kernel(resized_crop, type(inpt)) + return kernel( + inpt, + top=top, + left=left, + height=height, + width=width, + size=size, + interpolation=interpolation, + antialias=antialias, + ) + + +@_register_kernel_internal(resized_crop, torch.Tensor) +@_register_kernel_internal(resized_crop, tv_tensors.Image) +def resized_crop_image( + image: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> torch.Tensor: + image = crop_image(image, top, left, height, width) + return resize_image(image, size, interpolation=interpolation, antialias=antialias) + + +def _resized_crop_image_pil( + image: PIL.Image.Image, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, +) -> PIL.Image.Image: + image = _crop_image_pil(image, top, left, height, width) + return _resize_image_pil(image, size, interpolation=interpolation) + + +@_register_kernel_internal(resized_crop, PIL.Image.Image) +def _resized_crop_image_pil_dispatch( + image: PIL.Image.Image, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> PIL.Image.Image: + if antialias is False: + warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.") + return _resized_crop_image_pil( + image, + top=top, + left=left, + height=height, + width=width, + size=size, + interpolation=interpolation, + ) + + +def resized_crop_keypoints( + keypoints: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], +) -> tuple[torch.Tensor, tuple[int, int]]: + keypoints, canvas_size = crop_keypoints(keypoints, top, left, height, width) + return resize_keypoints(keypoints, size=size, canvas_size=canvas_size) + + +@_register_kernel_internal(resized_crop, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _resized_crop_keypoints_dispatch( + inpt: tv_tensors.BoundingBoxes, top: int, left: int, height: int, width: int, size: list[int], **kwargs +): + output, canvas_size = resized_crop_keypoints( + inpt.as_subclass(torch.Tensor), top=top, left=left, height=height, width=width, size=size + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def resized_crop_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + top: int, + left: int, + height: int, + width: int, + size: list[int], + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + bounding_boxes, canvas_size = crop_bounding_boxes( + bounding_boxes, format, top, left, height, width, clamping_mode=clamping_mode + ) + return resize_bounding_boxes( + bounding_boxes, format=format, canvas_size=canvas_size, size=size, clamping_mode=clamping_mode + ) + + +@_register_kernel_internal(resized_crop, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _resized_crop_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, top: int, left: int, height: int, width: int, size: list[int], **kwargs +) -> tv_tensors.BoundingBoxes: + output, canvas_size = resized_crop_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + top=top, + left=left, + height=height, + width=width, + size=size, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def resized_crop_mask( + mask: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], +) -> torch.Tensor: + mask = crop_mask(mask, top, left, height, width) + return resize_mask(mask, size) + + +@_register_kernel_internal(resized_crop, tv_tensors.Mask, tv_tensor_wrapper=False) +def _resized_crop_mask_dispatch( + inpt: tv_tensors.Mask, top: int, left: int, height: int, width: int, size: list[int], **kwargs +) -> tv_tensors.Mask: + output = resized_crop_mask( + inpt.as_subclass(torch.Tensor), top=top, left=left, height=height, width=width, size=size + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(resized_crop, tv_tensors.Video) +def resized_crop_video( + video: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> torch.Tensor: + return resized_crop_image( + video, top, left, height, width, antialias=antialias, size=size, interpolation=interpolation + ) + + +def five_crop( + inpt: torch.Tensor, size: list[int] +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """See :class:`~torchvision.transforms.v2.FiveCrop` for details.""" + if torch.jit.is_scripting(): + return five_crop_image(inpt, size=size) + + _log_api_usage_once(five_crop) + + kernel = _get_kernel(five_crop, type(inpt)) + return kernel(inpt, size=size) + + +def _parse_five_crop_size(size: list[int]) -> list[int]: + if isinstance(size, numbers.Number): + s = int(size) + size = [s, s] + elif isinstance(size, (tuple, list)) and len(size) == 1: + s = size[0] + size = [s, s] + + if len(size) != 2: + raise ValueError("Please provide only two dimensions (h, w) for size.") + + return size + + +@_register_five_ten_crop_kernel_internal(five_crop, torch.Tensor) +@_register_five_ten_crop_kernel_internal(five_crop, tv_tensors.Image) +def five_crop_image( + image: torch.Tensor, size: list[int] +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + crop_height, crop_width = _parse_five_crop_size(size) + image_height, image_width = image.shape[-2:] + + if crop_width > image_width or crop_height > image_height: + raise ValueError(f"Requested crop size {size} is bigger than input size {(image_height, image_width)}") + + tl = crop_image(image, 0, 0, crop_height, crop_width) + tr = crop_image(image, 0, image_width - crop_width, crop_height, crop_width) + bl = crop_image(image, image_height - crop_height, 0, crop_height, crop_width) + br = crop_image(image, image_height - crop_height, image_width - crop_width, crop_height, crop_width) + center = center_crop_image(image, [crop_height, crop_width]) + + return tl, tr, bl, br, center + + +@_register_five_ten_crop_kernel_internal(five_crop, PIL.Image.Image) +def _five_crop_image_pil( + image: PIL.Image.Image, size: list[int] +) -> tuple[PIL.Image.Image, PIL.Image.Image, PIL.Image.Image, PIL.Image.Image, PIL.Image.Image]: + crop_height, crop_width = _parse_five_crop_size(size) + image_height, image_width = _get_size_image_pil(image) + + if crop_width > image_width or crop_height > image_height: + raise ValueError(f"Requested crop size {size} is bigger than input size {(image_height, image_width)}") + + tl = _crop_image_pil(image, 0, 0, crop_height, crop_width) + tr = _crop_image_pil(image, 0, image_width - crop_width, crop_height, crop_width) + bl = _crop_image_pil(image, image_height - crop_height, 0, crop_height, crop_width) + br = _crop_image_pil(image, image_height - crop_height, image_width - crop_width, crop_height, crop_width) + center = _center_crop_image_pil(image, [crop_height, crop_width]) + + return tl, tr, bl, br, center + + +@_register_five_ten_crop_kernel_internal(five_crop, tv_tensors.Video) +def five_crop_video( + video: torch.Tensor, size: list[int] +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + return five_crop_image(video, size) + + +def ten_crop( + inpt: torch.Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + """See :class:`~torchvision.transforms.v2.TenCrop` for details.""" + if torch.jit.is_scripting(): + return ten_crop_image(inpt, size=size, vertical_flip=vertical_flip) + + _log_api_usage_once(ten_crop) + + kernel = _get_kernel(ten_crop, type(inpt)) + return kernel(inpt, size=size, vertical_flip=vertical_flip) + + +@_register_five_ten_crop_kernel_internal(ten_crop, torch.Tensor) +@_register_five_ten_crop_kernel_internal(ten_crop, tv_tensors.Image) +def ten_crop_image( + image: torch.Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + non_flipped = five_crop_image(image, size) + + if vertical_flip: + image = vertical_flip_image(image) + else: + image = horizontal_flip_image(image) + + flipped = five_crop_image(image, size) + + return non_flipped + flipped + + +@_register_five_ten_crop_kernel_internal(ten_crop, PIL.Image.Image) +def _ten_crop_image_pil( + image: PIL.Image.Image, size: list[int], vertical_flip: bool = False +) -> tuple[ + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, +]: + non_flipped = _five_crop_image_pil(image, size) + + if vertical_flip: + image = _vertical_flip_image_pil(image) + else: + image = _horizontal_flip_image_pil(image) + + flipped = _five_crop_image_pil(image, size) + + return non_flipped + flipped + + +@_register_five_ten_crop_kernel_internal(ten_crop, tv_tensors.Video) +def ten_crop_video( + video: torch.Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + return ten_crop_image(video, size, vertical_flip=vertical_flip) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_meta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..4568b39ab5991afd41f456944ee96e273e229e0b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_meta.py @@ -0,0 +1,685 @@ +from typing import Optional, Union + +import PIL.Image +import torch +from torchvision import tv_tensors +from torchvision.transforms import _functional_pil as _FP +from torchvision.tv_tensors import BoundingBoxFormat +from torchvision.tv_tensors._bounding_boxes import CLAMPING_MODE_TYPE + +from torchvision.utils import _log_api_usage_once + +from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor + + +def get_dimensions(inpt: torch.Tensor) -> list[int]: + if torch.jit.is_scripting(): + return get_dimensions_image(inpt) + + _log_api_usage_once(get_dimensions) + + kernel = _get_kernel(get_dimensions, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_dimensions, torch.Tensor) +@_register_kernel_internal(get_dimensions, tv_tensors.Image, tv_tensor_wrapper=False) +def get_dimensions_image(image: torch.Tensor) -> list[int]: + chw = list(image.shape[-3:]) + ndims = len(chw) + if ndims == 3: + return chw + elif ndims == 2: + chw.insert(0, 1) + return chw + else: + raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}") + + +_get_dimensions_image_pil = _register_kernel_internal(get_dimensions, PIL.Image.Image)(_FP.get_dimensions) + + +@_register_kernel_internal(get_dimensions, tv_tensors.Video, tv_tensor_wrapper=False) +def get_dimensions_video(video: torch.Tensor) -> list[int]: + return get_dimensions_image(video) + + +def get_num_channels(inpt: torch.Tensor) -> int: + if torch.jit.is_scripting(): + return get_num_channels_image(inpt) + + _log_api_usage_once(get_num_channels) + + kernel = _get_kernel(get_num_channels, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_num_channels, torch.Tensor) +@_register_kernel_internal(get_num_channels, tv_tensors.Image, tv_tensor_wrapper=False) +def get_num_channels_image(image: torch.Tensor) -> int: + chw = image.shape[-3:] + ndims = len(chw) + if ndims == 3: + return chw[0] + elif ndims == 2: + return 1 + else: + raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}") + + +_get_num_channels_image_pil = _register_kernel_internal(get_num_channels, PIL.Image.Image)(_FP.get_image_num_channels) + + +@_register_kernel_internal(get_num_channels, tv_tensors.Video, tv_tensor_wrapper=False) +def get_num_channels_video(video: torch.Tensor) -> int: + return get_num_channels_image(video) + + +# We changed the names to ensure it can be used not only for images but also videos. Thus, we just alias it without +# deprecating the old names. +get_image_num_channels = get_num_channels + + +def get_size(inpt: torch.Tensor) -> list[int]: + if torch.jit.is_scripting(): + return get_size_image(inpt) + + _log_api_usage_once(get_size) + + kernel = _get_kernel(get_size, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_size, torch.Tensor) +@_register_kernel_internal(get_size, tv_tensors.Image, tv_tensor_wrapper=False) +def get_size_image(image: torch.Tensor) -> list[int]: + hw = list(image.shape[-2:]) + ndims = len(hw) + if ndims == 2: + return hw + else: + raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}") + + +@_register_kernel_internal(get_size, PIL.Image.Image) +def _get_size_image_pil(image: PIL.Image.Image) -> list[int]: + width, height = _FP.get_image_size(image) + return [height, width] + + +@_register_kernel_internal(get_size, tv_tensors.Video, tv_tensor_wrapper=False) +def get_size_video(video: torch.Tensor) -> list[int]: + return get_size_image(video) + + +@_register_kernel_internal(get_size, tv_tensors.Mask, tv_tensor_wrapper=False) +def get_size_mask(mask: torch.Tensor) -> list[int]: + return get_size_image(mask) + + +@_register_kernel_internal(get_size, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def get_size_bounding_boxes(bounding_box: tv_tensors.BoundingBoxes) -> list[int]: + return list(bounding_box.canvas_size) + + +@_register_kernel_internal(get_size, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def get_size_keypoints(keypoints: tv_tensors.KeyPoints) -> list[int]: + return list(keypoints.canvas_size) + + +def get_num_frames(inpt: torch.Tensor) -> int: + if torch.jit.is_scripting(): + return get_num_frames_video(inpt) + + _log_api_usage_once(get_num_frames) + + kernel = _get_kernel(get_num_frames, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_num_frames, torch.Tensor) +@_register_kernel_internal(get_num_frames, tv_tensors.Video, tv_tensor_wrapper=False) +def get_num_frames_video(video: torch.Tensor) -> int: + return video.shape[-4] + + +def _xywh_to_xyxy(xywh: torch.Tensor, inplace: bool) -> torch.Tensor: + xyxy = xywh if inplace else xywh.clone() + xyxy[..., 2:] += xyxy[..., :2] + return xyxy + + +def _xyxy_to_xywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor: + xywh = xyxy if inplace else xyxy.clone() + xywh[..., 2:] -= xywh[..., :2] + return xywh + + +def _cxcywh_to_xyxy(cxcywh: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + cxcywh = cxcywh.clone() + + # Trick to do fast division by 2 and ceil, without casting. It produces the same result as + # `torchvision.ops._box_convert._box_cxcywh_to_xyxy`. + half_wh = cxcywh[..., 2:].div(-2, rounding_mode=None if cxcywh.is_floating_point() else "floor").abs_() + # (cx - width / 2) = x1, same for y1 + cxcywh[..., :2].sub_(half_wh) + # (x1 + width) = x2, same for y2 + cxcywh[..., 2:].add_(cxcywh[..., :2]) + + return cxcywh + + +def _xyxy_to_cxcywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + xyxy = xyxy.clone() + + # (x2 - x1) = width, same for height + xyxy[..., 2:].sub_(xyxy[..., :2]) + # (x1 * 2 + width) / 2 = x1 + width / 2 = x1 + (x2-x1)/2 = (x1 + x2)/2 = cx, same for cy + xyxy[..., :2].mul_(2).add_(xyxy[..., 2:]).div_(2, rounding_mode=None if xyxy.is_floating_point() else "floor") + + return xyxy + + +def _xyxy_to_keypoints(bounding_boxes: torch.Tensor) -> torch.Tensor: + return bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]] + + +def _xyxyxyxy_to_keypoints(bounding_boxes: torch.Tensor) -> torch.Tensor: + return bounding_boxes[:, [[0, 1], [2, 3], [4, 5], [6, 7]]] + + +def _cxcywhr_to_xywhr(cxcywhr: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + cxcywhr = cxcywhr.clone() + + half_wh = cxcywhr[..., 2:-1].div(-2, rounding_mode=None if cxcywhr.is_floating_point() else "floor").abs_() + r_rad = cxcywhr[..., 4].mul(torch.pi).div(180.0) + cos, sin = r_rad.cos(), r_rad.sin() + # (cx - width / 2 * cos - height / 2 * sin) = x1 + cxcywhr[..., 0].sub_(half_wh[..., 0].mul(cos)).sub_(half_wh[..., 1].mul(sin)) + # (cy + width / 2 * sin - height / 2 * cos) = y1 + cxcywhr[..., 1].add_(half_wh[..., 0].mul(sin)).sub_(half_wh[..., 1].mul(cos)) + + return cxcywhr + + +def _xywhr_to_cxcywhr(xywhr: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + xywhr = xywhr.clone() + + half_wh = xywhr[..., 2:-1].div(-2, rounding_mode=None if xywhr.is_floating_point() else "floor").abs_() + r_rad = xywhr[..., 4].mul(torch.pi).div(180.0) + cos, sin = r_rad.cos(), r_rad.sin() + # (x1 + width / 2 * cos + height / 2 * sin) = cx + xywhr[..., 0].add_(half_wh[..., 0].mul(cos)).add_(half_wh[..., 1].mul(sin)) + # (y1 - width / 2 * sin + height / 2 * cos) = cy + xywhr[..., 1].sub_(half_wh[..., 0].mul(sin)).add_(half_wh[..., 1].mul(cos)) + + return xywhr + + +def _xywhr_to_xyxyxyxy(xywhr: torch.Tensor, inplace: bool) -> torch.Tensor: + # NOTE: This function cannot modify the input tensor inplace as it requires a dimension change. + if not inplace: + xywhr = xywhr.clone() + + wh = xywhr[..., 2:-1] + r_rad = xywhr[..., 4].mul(torch.pi).div(180.0) + cos, sin = r_rad.cos(), r_rad.sin() + xywhr = xywhr[..., :2].tile((1, 4)) + # x1 + w * cos = x2 + xywhr[..., 2].add_(wh[..., 0].mul(cos)) + # y1 - w * sin = y2 + xywhr[..., 3].sub_(wh[..., 0].mul(sin)) + # x1 + w * cos + h * sin = x3 + xywhr[..., 4].add_(wh[..., 0].mul(cos).add(wh[..., 1].mul(sin))) + # y1 - w * sin + h * cos = y3 + xywhr[..., 5].sub_(wh[..., 0].mul(sin).sub(wh[..., 1].mul(cos))) + # x1 + h * sin = x4 + xywhr[..., 6].add_(wh[..., 1].mul(sin)) + # y1 + h * cos = y4 + xywhr[..., 7].add_(wh[..., 1].mul(cos)) + + return xywhr + + +def _xyxyxyxy_to_xywhr(xyxyxyxy: torch.Tensor, inplace: bool) -> torch.Tensor: + # NOTE: This function cannot modify the input tensor inplace as it requires a dimension change. + if not inplace: + xyxyxyxy = xyxyxyxy.clone() + + dtype = xyxyxyxy.dtype + acceptable_dtypes = [torch.float32, torch.float64] # Ensure consistency between CPU and GPU. + need_cast = dtype not in acceptable_dtypes + if need_cast: + # Up-case to avoid overflow for square operations + xyxyxyxy = xyxyxyxy.to(torch.float32) + + r_rad = torch.atan2(xyxyxyxy[..., 1].sub(xyxyxyxy[..., 3]), xyxyxyxy[..., 2].sub(xyxyxyxy[..., 0])) + # x1, y1, (x2 - x1), (y2 - y1), (x3 - x2), (y3 - y2) x4, y4 + xyxyxyxy[..., 4:6].sub_(xyxyxyxy[..., 2:4]) + xyxyxyxy[..., 2:4].sub_(xyxyxyxy[..., :2]) + # sqrt((x2 - x1) ** 2 + (y1 - y2) ** 2) = w + xyxyxyxy[..., 2] = xyxyxyxy[..., 2].pow(2).add(xyxyxyxy[..., 3].pow(2)).sqrt() + # sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2) = h + xyxyxyxy[..., 3] = xyxyxyxy[..., 4].pow(2).add(xyxyxyxy[..., 5].pow(2)).sqrt() + xyxyxyxy[..., 4] = r_rad.div_(torch.pi).mul_(180.0) + + if need_cast: + xyxyxyxy = xyxyxyxy.to(dtype) + + return xyxyxyxy[..., :5] + + +def _convert_bounding_box_format( + bounding_boxes: torch.Tensor, old_format: BoundingBoxFormat, new_format: BoundingBoxFormat, inplace: bool = False +) -> torch.Tensor: + + if new_format == old_format: + return bounding_boxes + + if tv_tensors.is_rotated_bounding_format(old_format) ^ tv_tensors.is_rotated_bounding_format(new_format): + raise ValueError("Cannot convert between rotated and unrotated bounding boxes.") + + # TODO: Add _xywh_to_cxcywh and _cxcywh_to_xywh to improve performance + if old_format == BoundingBoxFormat.XYWH: + bounding_boxes = _xywh_to_xyxy(bounding_boxes, inplace) + elif old_format == BoundingBoxFormat.CXCYWH: + bounding_boxes = _cxcywh_to_xyxy(bounding_boxes, inplace) + elif old_format == BoundingBoxFormat.CXCYWHR: + bounding_boxes = _cxcywhr_to_xywhr(bounding_boxes, inplace) + elif old_format == BoundingBoxFormat.XYXYXYXY: + bounding_boxes = _xyxyxyxy_to_xywhr(bounding_boxes, inplace) + + if new_format == BoundingBoxFormat.XYWH: + bounding_boxes = _xyxy_to_xywh(bounding_boxes, inplace) + elif new_format == BoundingBoxFormat.CXCYWH: + bounding_boxes = _xyxy_to_cxcywh(bounding_boxes, inplace) + elif new_format == BoundingBoxFormat.CXCYWHR: + bounding_boxes = _xywhr_to_cxcywhr(bounding_boxes, inplace) + elif new_format == BoundingBoxFormat.XYXYXYXY: + bounding_boxes = _xywhr_to_xyxyxyxy(bounding_boxes, inplace) + + return bounding_boxes + + +def convert_bounding_box_format( + inpt: torch.Tensor, + old_format: Optional[BoundingBoxFormat] = None, + new_format: Optional[BoundingBoxFormat] = None, + inplace: bool = False, +) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ConvertBoundingBoxFormat` for details.""" + # This being a kernel / functional hybrid, we need an option to pass `old_format` explicitly for pure tensor + # inputs as well as extract it from `tv_tensors.BoundingBoxes` inputs. However, putting a default value on + # `old_format` means we also need to put one on `new_format` to have syntactically correct Python. Here we mimic the + # default error that would be thrown if `new_format` had no default value. + if new_format is None: + raise TypeError("convert_bounding_box_format() missing 1 required argument: 'new_format'") + + if not torch.jit.is_scripting(): + _log_api_usage_once(convert_bounding_box_format) + + if isinstance(old_format, str): + old_format = BoundingBoxFormat[old_format.upper()] + if isinstance(new_format, str): + new_format = BoundingBoxFormat[new_format.upper()] + + if torch.jit.is_scripting() or is_pure_tensor(inpt): + if old_format is None: + raise ValueError("For pure tensor inputs, `old_format` has to be passed.") + return _convert_bounding_box_format(inpt, old_format=old_format, new_format=new_format, inplace=inplace) + elif isinstance(inpt, tv_tensors.BoundingBoxes): + if old_format is not None: + raise ValueError("For bounding box tv_tensor inputs, `old_format` must not be passed.") + output = _convert_bounding_box_format( + inpt.as_subclass(torch.Tensor), old_format=inpt.format, new_format=new_format, inplace=inplace + ) + return tv_tensors.wrap(output, like=inpt, format=new_format) + else: + raise TypeError( + f"Input can either be a plain tensor or a bounding box tv_tensor, but got {type(inpt)} instead." + ) + + +def _clamp_bounding_boxes( + bounding_boxes: torch.Tensor, + format: BoundingBoxFormat, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + if clamping_mode is None: + return bounding_boxes.clone() + # TODO: Investigate if it makes sense from a performance perspective to have an implementation for every + # BoundingBoxFormat instead of converting back and forth + in_dtype = bounding_boxes.dtype + bounding_boxes = bounding_boxes.clone() if bounding_boxes.is_floating_point() else bounding_boxes.float() + xyxy_boxes = convert_bounding_box_format( + bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYXY, inplace=True + ) + # hard and soft modes are equivalent for non-rotated boxes + xyxy_boxes[..., 0::2].clamp_(min=0, max=canvas_size[1]) + xyxy_boxes[..., 1::2].clamp_(min=0, max=canvas_size[0]) + out_boxes = convert_bounding_box_format( + xyxy_boxes, old_format=BoundingBoxFormat.XYXY, new_format=format, inplace=True + ) + return out_boxes.to(in_dtype) + + +def _order_bounding_boxes_points( + bounding_boxes: torch.Tensor, indices: Optional[torch.Tensor] = None +) -> tuple[torch.Tensor, torch.Tensor]: + """Re-order points in bounding boxes based on specific criteria or provided indices. + + This function reorders the points of bounding boxes either according to provided indices or + by a default ordering strategy. In the default strategy, (x1, y1) corresponds to the point + with the lowest x value. If multiple points have the same lowest x value, the point with the + lowest y value is chosen. + + Args: + bounding_boxes (torch.Tensor): A tensor containing bounding box coordinates in format [x1, y1, x2, y2, x3, y3, x4, y4]. + indices (torch.Tensor | None): Optional tensor containing indices for reordering. If None, default ordering is applied. + + Returns: + tuple[torch.Tensor, torch.Tensor]: A tuple containing: + - indices: The indices used for reordering + - reordered_boxes: The bounding boxes with reordered points + """ + if indices is None: + output_xyxyxyxy = bounding_boxes.reshape(-1, 8) + x, y = output_xyxyxyxy[..., 0::2], output_xyxyxyxy[..., 1::2] + y_max = torch.max(y.abs(), dim=1, keepdim=True)[0] + x_max = torch.max(x.abs(), dim=1, keepdim=True)[0] + _, x1 = (y / y_max + (x / x_max) * 100).min(dim=1) + indices = torch.ones_like(output_xyxyxyxy) + indices[..., 0] = x1.mul(2) + indices.cumsum_(1).remainder_(8) + return indices, bounding_boxes.gather(1, indices.to(torch.int64)) + + +def _get_slope_and_intercept(box: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """ + Calculate the slope and y-intercept of the lines defined by consecutive vertices in a bounding box. + This function computes the slope (a) and y-intercept (b) for each line segment in a bounding box, + where each line is defined by two consecutive vertices. + """ + x, y = box[..., ::2], box[..., 1::2] + a = y.diff(append=y[..., 0:1]) / x.diff(append=x[..., 0:1]) + b = y - a * x + return a, b + + +def _get_intersection_point(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """ + Calculate the intersection point of two lines defined by their slopes and y-intercepts. + This function computes the intersection points between pairs of lines, where each line + is defined by the equation y = ax + b (slope and y-intercept form). + """ + batch_size = a.shape[0] + x = b.diff(prepend=b[..., 3:4]).neg() / a.diff(prepend=a[..., 3:4]) + y = a * x + b + return torch.cat((x.unsqueeze(-1), y.unsqueeze(-1)), dim=-1).view(batch_size, 8) + + +def _clamp_y_intercept( + bounding_boxes: torch.Tensor, + original_bounding_boxes: torch.Tensor, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + """ + Apply clamping to bounding box y-intercepts. This function handles two clamping strategies: + - Hard clamping: Ensures all box vertices stay within canvas boundaries, finding the largest + angle-preserving box enclosed within the original box and the image canvas. + - Soft clamping: Allows some vertices to extend beyond the canvas, finding the smallest + angle-preserving box that encloses the intersection of the original box and the image canvas. + + The function first calculates the slopes and y-intercepts of the lines forming the bounding box, + then applies various constraints to ensure the clamping conditions are respected. + """ + + # Calculate slopes and y-intercepts for bounding boxes + a, b = _get_slope_and_intercept(bounding_boxes) + a1, a2, a3, a4 = a.unbind(-1) + b1, b2, b3, b4 = b.unbind(-1) + + # Get y-intercepts from original bounding boxes + _, bm = _get_slope_and_intercept(original_bounding_boxes) + b1m, b2m, b3m, b4m = bm.unbind(-1) + + # Soft clamping: Clamp y-intercepts within canvas boundaries + b1 = b2.clamp(b1, b3).clamp(0, canvas_size[0]) + b4 = b3.clamp(b2, b4).clamp(0, canvas_size[0]) + + if clamping_mode is not None and clamping_mode == "hard": + # Hard clamping: Average b1 and b4, and adjust b2 and b3 for maximum area + b1 = b4 = (b1 + b4) / 2 + + # Calculate candidate values for b2 based on geometric constraints + b2_candidates = torch.stack( + [ + b1 * a2 / a1, # Constraint at y=0 + b3 * a2 / a3, # Constraint at y=0 + (a1 - a2) * canvas_size[1] + b1, # Constraint at x=canvas_width + (a3 - a2) * canvas_size[1] + b3, # Constraint at x=canvas_width + ], + dim=1, + ) + # Take maximum value that doesn't exceed original b2 + b2 = torch.max(b2_candidates, dim=1)[0].clamp(max=b2) + + # Calculate candidate values for b3 based on geometric constraints + b3_candidates = torch.stack( + [ + canvas_size[0] * (1 - a3 / a4) + b4 * a3 / a4, # Constraint at y=canvas_height + canvas_size[0] * (1 - a3 / a2) + b2 * a3 / a2, # Constraint at y=canvas_height + (a2 - a3) * canvas_size[1] + b2, # Constraint at x=canvas_width + (a4 - a3) * canvas_size[1] + b4, # Constraint at x=canvas_width + ], + dim=1, + ) + # Take minimum value that doesn't go below original b3 + b3 = torch.min(b3_candidates, dim=1)[0].clamp(min=b3) + + # Final clamping to ensure y-intercepts are within original box bounds + b1.clamp_(b1m, b3m) + b3.clamp_(b1m, b3m) + b2.clamp_(b2m, b4m) + b4.clamp_(b2m, b4m) + + return torch.stack([b1, b2, b3, b4], dim=-1) + + +def _clamp_along_y_axis( + bounding_boxes: torch.Tensor, + original_bounding_boxes: torch.Tensor, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + """ + Adjusts bounding boxes along the y-axis based on specific conditions. + + This function modifies the bounding boxes by evaluating different cases + and applying the appropriate transformation to ensure the bounding boxes + are clamped correctly along the y-axis. + + Args: + bounding_boxes (torch.Tensor): A tensor containing bounding box coordinates. + original_bounding_boxes (torch.Tensor): The original bounding boxes before any clamping is applied. + canvas_size (tuple[int, int]): The size of the canvas as (height, width). + clamping_mode (str, optional): The clamping strategy to use. + + Returns: + torch.Tensor: The adjusted bounding boxes. + """ + original_shape = bounding_boxes.shape + bounding_boxes = bounding_boxes.reshape(-1, 8) + original_bounding_boxes = original_bounding_boxes.reshape(-1, 8) + + # Calculate slopes (a) and y-intercepts (b) for all lines in the bounding boxes + a, b = _get_slope_and_intercept(bounding_boxes) + x1, y1, x2, y2, x3, y3, x4, y4 = bounding_boxes.unbind(-1) + b = _clamp_y_intercept(bounding_boxes, original_bounding_boxes, canvas_size, clamping_mode) + + case_a = _get_intersection_point(a, b) + case_b = bounding_boxes.clone() + case_b[..., 0].clamp_(0) # Clamp x1 to 0 + case_b[..., 6].clamp_(0) # Clamp x4 to 0 + case_c = torch.zeros_like(case_b) + + cond_a = (x1 < 0) & ~case_a.isnan().any(-1) # First point is outside left boundary + cond_b = y1.isclose(y2) | y3.isclose(y4) # First line is nearly vertical + cond_c = (x1 <= 0) & (x2 <= 0) & (x3 <= 0) & (x4 <= 0) # All points outside left boundary + cond_c = cond_c | y1.isclose(y4) | y2.isclose(y3) | (cond_b & x1.isclose(x2)) # First line is nearly horizontal + + for (cond, case) in zip( + [cond_a, cond_b, cond_c], + [case_a, case_b, case_c], + ): + bounding_boxes = torch.where(cond.unsqueeze(1).repeat(1, 8), case.reshape(-1, 8), bounding_boxes) + + return bounding_boxes.reshape(original_shape) + + +def _clamp_rotated_bounding_boxes( + bounding_boxes: torch.Tensor, + format: BoundingBoxFormat, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + """ + Clamp rotated bounding boxes to ensure they stay within the canvas boundaries. + + This function handles rotated bounding boxes by: + 1. Converting them to XYXYXYXY format (8 coordinates representing 4 corners). + 2. Re-ordering the points in the bounding boxes to ensure (x1, y1) corresponds to the point with the lowest x value + 2. Translates the points (x1, y1), (x2, y2) and (x3, y3) + to ensure the bounding box does not go out beyond the left boundary of the canvas. + 3. Rotate the bounding box four times and apply the same transformation to each vertex to ensure + the box does not go beyond the top, right, and bottom boundaries. + 3. Converting back to the original format and re-order the points as in the original input. + + Args: + bounding_boxes (torch.Tensor): Tensor containing rotated bounding box coordinates + format (BoundingBoxFormat): The format of the input bounding boxes + canvas_size (tuple[int, int]): The size of the canvas as (height, width) + + Returns: + torch.Tensor: Clamped bounding boxes in the original format and shape + """ + if clamping_mode is None: + return bounding_boxes.clone() + original_shape = bounding_boxes.shape + bounding_boxes = bounding_boxes.clone() + out_boxes = ( + convert_bounding_box_format( + bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, inplace=True + ) + ).reshape(-1, 8) + + original_boxes = out_boxes.clone() + for _ in range(4): # Iterate over the 4 vertices. + indices, out_boxes = _order_bounding_boxes_points(out_boxes) + _, original_boxes = _order_bounding_boxes_points(original_boxes, indices) + out_boxes = _clamp_along_y_axis(out_boxes, original_boxes, canvas_size, clamping_mode) + _, out_boxes = _order_bounding_boxes_points(out_boxes, indices) + _, original_boxes = _order_bounding_boxes_points(original_boxes, indices) + # rotate 90 degrees counter clock wise + out_boxes[:, ::2], out_boxes[:, 1::2] = ( + out_boxes[:, 1::2].clone(), + canvas_size[1] - out_boxes[:, ::2].clone(), + ) + original_boxes[:, ::2], original_boxes[:, 1::2] = ( + original_boxes[:, 1::2].clone(), + canvas_size[1] - original_boxes[:, ::2].clone(), + ) + canvas_size = (canvas_size[1], canvas_size[0]) + + out_boxes = convert_bounding_box_format( + out_boxes, old_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, new_format=format, inplace=True + ).reshape(original_shape) + + return out_boxes + + +def clamp_bounding_boxes( + inpt: torch.Tensor, + format: Optional[BoundingBoxFormat] = None, + canvas_size: Optional[tuple[int, int]] = None, + clamping_mode: Union[CLAMPING_MODE_TYPE, str] = "auto", +) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ClampBoundingBoxes` for details.""" + if not torch.jit.is_scripting(): + _log_api_usage_once(clamp_bounding_boxes) + + if clamping_mode is not None and clamping_mode not in ("soft", "hard", "auto"): + raise ValueError(f"clamping_mode must be soft, hard, auto or None, got {clamping_mode}") + + if torch.jit.is_scripting() or is_pure_tensor(inpt): + + if format is None or canvas_size is None or (clamping_mode is not None and clamping_mode == "auto"): + raise ValueError("For pure tensor inputs, `format`, `canvas_size` and `clamping_mode` have to be passed.") + if tv_tensors.is_rotated_bounding_format(format): + return _clamp_rotated_bounding_boxes( + inpt, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + else: + return _clamp_bounding_boxes(inpt, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode) + elif isinstance(inpt, tv_tensors.BoundingBoxes): + if format is not None or canvas_size is not None: + raise ValueError("For bounding box tv_tensor inputs, `format` and `canvas_size` must not be passed.") + if clamping_mode is not None and clamping_mode == "auto": + clamping_mode = inpt.clamping_mode + if tv_tensors.is_rotated_bounding_format(inpt.format): + output = _clamp_rotated_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + clamping_mode=clamping_mode, + ) + else: + output = _clamp_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + clamping_mode=clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + else: + raise TypeError( + f"Input can either be a plain tensor or a bounding box tv_tensor, but got {type(inpt)} instead." + ) + + +def _clamp_keypoints(keypoints: torch.Tensor, canvas_size: tuple[int, int]) -> torch.Tensor: + dtype = keypoints.dtype + keypoints = keypoints.clone() if keypoints.is_floating_point() else keypoints.float() + # Note that max is canvas_size[i] - 1 and not can canvas_size[i] like for + # bounding boxes. + keypoints[..., 0].clamp_(min=0, max=canvas_size[1] - 1) + keypoints[..., 1].clamp_(min=0, max=canvas_size[0] - 1) + return keypoints.to(dtype=dtype) + + +def clamp_keypoints( + inpt: torch.Tensor, + canvas_size: Optional[tuple[int, int]] = None, +) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ClampKeyPoints` for details.""" + if not torch.jit.is_scripting(): + _log_api_usage_once(clamp_keypoints) + + if torch.jit.is_scripting() or is_pure_tensor(inpt): + + if canvas_size is None: + raise ValueError("For pure tensor inputs, `canvas_size` has to be passed.") + return _clamp_keypoints(inpt, canvas_size=canvas_size) + elif isinstance(inpt, tv_tensors.KeyPoints): + if canvas_size is not None: + raise ValueError("For keypoints tv_tensor inputs, `canvas_size` must not be passed.") + output = _clamp_keypoints(inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size) + return tv_tensors.wrap(output, like=inpt) + else: + raise TypeError(f"Input can either be a plain tensor or a keypoints tv_tensor, but got {type(inpt)} instead.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_misc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..daf263df046f2767a65ef0a7ee70ea2b62d813f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_misc.py @@ -0,0 +1,517 @@ +import math +from typing import Optional + +import PIL.Image +import torch +from torch.nn.functional import conv2d, pad as torch_pad + +from torchvision import tv_tensors +from torchvision.transforms._functional_tensor import _max_value +from torchvision.transforms.functional import pil_to_tensor, to_pil_image + +from torchvision.utils import _log_api_usage_once + +from ._meta import _convert_bounding_box_format + +from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor + + +def normalize( + inpt: torch.Tensor, + mean: list[float], + std: list[float], + inplace: bool = False, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Normalize` for details.""" + if torch.jit.is_scripting(): + return normalize_image(inpt, mean=mean, std=std, inplace=inplace) + + _log_api_usage_once(normalize) + + kernel = _get_kernel(normalize, type(inpt)) + return kernel(inpt, mean=mean, std=std, inplace=inplace) + + +@_register_kernel_internal(normalize, torch.Tensor) +@_register_kernel_internal(normalize, tv_tensors.Image) +def normalize_image(image: torch.Tensor, mean: list[float], std: list[float], inplace: bool = False) -> torch.Tensor: + if not image.is_floating_point(): + raise TypeError(f"Input tensor should be a float tensor. Got {image.dtype}.") + + if image.ndim < 3: + raise ValueError(f"Expected tensor to be a tensor image of size (..., C, H, W). Got {image.shape}.") + + if isinstance(std, (tuple, list)): + divzero = not all(std) + elif isinstance(std, (int, float)): + divzero = std == 0 + else: + divzero = False + if divzero: + raise ValueError("std evaluated to zero, leading to division by zero.") + + dtype = image.dtype + device = image.device + mean = torch.as_tensor(mean, dtype=dtype, device=device) + std = torch.as_tensor(std, dtype=dtype, device=device) + if mean.ndim == 1: + mean = mean.view(-1, 1, 1) + if std.ndim == 1: + std = std.view(-1, 1, 1) + + if inplace: + image = image.sub_(mean) + else: + image = image.sub(mean) + + return image.div_(std) + + +@_register_kernel_internal(normalize, tv_tensors.Video) +def normalize_video(video: torch.Tensor, mean: list[float], std: list[float], inplace: bool = False) -> torch.Tensor: + return normalize_image(video, mean, std, inplace=inplace) + + +def gaussian_blur(inpt: torch.Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.GaussianBlur` for details.""" + if torch.jit.is_scripting(): + return gaussian_blur_image(inpt, kernel_size=kernel_size, sigma=sigma) + + _log_api_usage_once(gaussian_blur) + + kernel = _get_kernel(gaussian_blur, type(inpt)) + return kernel(inpt, kernel_size=kernel_size, sigma=sigma) + + +def _get_gaussian_kernel1d(kernel_size: int, sigma: float, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + lim = (kernel_size - 1) / (2.0 * math.sqrt(2.0)) + x = torch.linspace(-lim, lim, steps=kernel_size, dtype=dtype, device=device) + kernel1d = torch.softmax(x.div(sigma).pow(2).neg(), dim=0) + return kernel1d + + +def _get_gaussian_kernel2d( + kernel_size: list[int], sigma: list[float], dtype: torch.dtype, device: torch.device +) -> torch.Tensor: + kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0], dtype, device) + kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1], dtype, device) + kernel2d = kernel1d_y.unsqueeze(-1) * kernel1d_x + return kernel2d + + +@_register_kernel_internal(gaussian_blur, torch.Tensor) +@_register_kernel_internal(gaussian_blur, tv_tensors.Image) +def gaussian_blur_image( + image: torch.Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None +) -> torch.Tensor: + # TODO: consider deprecating integers from sigma on the future + if isinstance(kernel_size, int): + kernel_size = [kernel_size, kernel_size] + elif len(kernel_size) != 2: + raise ValueError(f"If kernel_size is a sequence its length should be 2. Got {len(kernel_size)}") + for ksize in kernel_size: + if ksize % 2 == 0 or ksize < 0: + raise ValueError(f"kernel_size should have odd and positive integers. Got {kernel_size}") + + if sigma is None: + sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size] + else: + if isinstance(sigma, (list, tuple)): + length = len(sigma) + if length == 1: + s = sigma[0] + sigma = [s, s] + elif length != 2: + raise ValueError(f"If sigma is a sequence, its length should be 2. Got {length}") + elif isinstance(sigma, (int, float)): + s = float(sigma) + sigma = [s, s] + else: + raise TypeError(f"sigma should be either float or sequence of floats. Got {type(sigma)}") + for s in sigma: + if s <= 0.0: + raise ValueError(f"sigma should have positive values. Got {sigma}") + + if image.numel() == 0: + return image + + dtype = image.dtype + shape = image.shape + ndim = image.ndim + if ndim == 3: + image = image.unsqueeze(dim=0) + elif ndim > 4: + image = image.reshape((-1,) + shape[-3:]) + + fp = torch.is_floating_point(image) + kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype if fp else torch.float32, device=image.device) + kernel = kernel.expand(shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + output = image if fp else image.to(dtype=torch.float32) + + # padding = (left, right, top, bottom) + padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2] + output = torch_pad(output, padding, mode="reflect") + output = conv2d(output, kernel, groups=shape[-3]) + + if ndim == 3: + output = output.squeeze(dim=0) + elif ndim > 4: + output = output.reshape(shape) + + if not fp: + output = output.round_().to(dtype=dtype) + + return output + + +@_register_kernel_internal(gaussian_blur, PIL.Image.Image) +def _gaussian_blur_image_pil( + image: PIL.Image.Image, kernel_size: list[int], sigma: Optional[list[float]] = None +) -> PIL.Image.Image: + t_img = pil_to_tensor(image) + output = gaussian_blur_image(t_img, kernel_size=kernel_size, sigma=sigma) + return to_pil_image(output, mode=image.mode) + + +@_register_kernel_internal(gaussian_blur, tv_tensors.Video) +def gaussian_blur_video( + video: torch.Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None +) -> torch.Tensor: + return gaussian_blur_image(video, kernel_size, sigma) + + +def gaussian_noise(inpt: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.GaussianNoise`""" + if torch.jit.is_scripting(): + return gaussian_noise_image(inpt, mean=mean, sigma=sigma) + + _log_api_usage_once(gaussian_noise) + + kernel = _get_kernel(gaussian_noise, type(inpt)) + return kernel(inpt, mean=mean, sigma=sigma, clip=clip) + + +@_register_kernel_internal(gaussian_noise, torch.Tensor) +@_register_kernel_internal(gaussian_noise, tv_tensors.Image) +def gaussian_noise_image(image: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True) -> torch.Tensor: + if sigma < 0: + raise ValueError(f"sigma shouldn't be negative. Got {sigma}") + + if image.is_floating_point(): + noise = mean + torch.randn_like(image) * sigma + out = image + noise + if clip: + out = torch.clamp(out, 0, 1) + return out + + elif image.dtype == torch.uint8: + # Convert to intermediate dtype int16 to add to input more efficiently + # See https://github.com/pytorch/vision/pull/9169 for alternative implementations and benchmark + noise = ((mean * 255) + torch.randn_like(image, dtype=torch.float32) * (sigma * 255)).to(torch.int16) + out = image + noise + + if clip: + out = torch.clamp(out, 0, 255) + return out.to(torch.uint8) + + else: + raise ValueError(f"Input tensor is expected to be in uint8 or float dtype, got dtype={image.dtype}") + + +@_register_kernel_internal(gaussian_noise, tv_tensors.Video) +def gaussian_noise_video(video: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True) -> torch.Tensor: + return gaussian_noise_image(video, mean=mean, sigma=sigma, clip=clip) + + +@_register_kernel_internal(gaussian_noise, PIL.Image.Image) +def _gaussian_noise_pil( + video: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True +) -> PIL.Image.Image: + raise ValueError("Gaussian Noise is not implemented for PIL images.") + + +def to_dtype(inpt: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ToDtype` for details.""" + if torch.jit.is_scripting(): + return to_dtype_image(inpt, dtype=dtype, scale=scale) + + _log_api_usage_once(to_dtype) + + kernel = _get_kernel(to_dtype, type(inpt)) + return kernel(inpt, dtype=dtype, scale=scale) + + +def _num_value_bits(dtype: torch.dtype) -> int: + if dtype == torch.uint8: + return 8 + elif dtype == torch.int8: + return 7 + elif dtype == torch.int16: + return 15 + elif dtype == torch.uint16: + return 16 + elif dtype == torch.int32: + return 31 + elif dtype == torch.int64: + return 63 + else: + raise TypeError(f"Number of value bits is only defined for integer dtypes, but got {dtype}.") + + +@_register_kernel_internal(to_dtype, torch.Tensor) +@_register_kernel_internal(to_dtype, tv_tensors.Image) +def to_dtype_image(image: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor: + + if image.dtype == dtype: + return image + elif not scale: + return image.to(dtype) + + float_input = image.is_floating_point() + if torch.jit.is_scripting(): + # TODO: remove this branch as soon as `dtype.is_floating_point` is supported by JIT + float_output = torch.tensor(0, dtype=dtype).is_floating_point() + else: + float_output = dtype.is_floating_point + + if float_input: + # float to float + if float_output: + return image.to(dtype) + + # float to int + if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or ( + image.dtype == torch.float64 and dtype == torch.int64 + ): + raise RuntimeError(f"The conversion from {image.dtype} to {dtype} cannot be performed safely.") + + # For data in the range `[0.0, 1.0]`, just multiplying by the maximum value of the integer range and converting + # to the integer dtype is not sufficient. For example, `torch.rand(...).mul(255).to(torch.uint8)` will only + # be `255` if the input is exactly `1.0`. See https://github.com/pytorch/vision/pull/2078#issuecomment-612045321 + # for a detailed analysis. + # To mitigate this, we could round before we convert to the integer dtype, but this is an extra operation. + # Instead, we can also multiply by the maximum value plus something close to `1`. See + # https://github.com/pytorch/vision/pull/2078#issuecomment-613524965 for details. + eps = 1e-3 + max_value = float(_max_value(dtype)) + # We need to scale first since the conversion would otherwise turn the input range `[0.0, 1.0]` into the + # discrete set `{0, 1}`. + return image.mul(max_value + 1.0 - eps).to(dtype) + else: + # int to float + if float_output: + return image.to(dtype).mul_(1.0 / _max_value(image.dtype)) + + # int to int + num_value_bits_input = _num_value_bits(image.dtype) + num_value_bits_output = _num_value_bits(dtype) + + # TODO: Remove if/else inner blocks once uint16 dtype supports bitwise shift operations. + shift_by = abs(num_value_bits_input - num_value_bits_output) + if num_value_bits_input > num_value_bits_output: + if image.dtype == torch.uint16: + return (image / 2 ** (shift_by)).to(dtype) + else: + return image.bitwise_right_shift(shift_by).to(dtype) + else: + if dtype == torch.uint16: + return image.to(dtype) * 2 ** (shift_by) + else: + return image.to(dtype).bitwise_left_shift_(shift_by) + + +# We encourage users to use to_dtype() instead but we keep this for BC +def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor: + """[DEPRECATED] Use to_dtype() instead.""" + return to_dtype_image(image, dtype=dtype, scale=True) + + +@_register_kernel_internal(to_dtype, tv_tensors.Video) +def to_dtype_video(video: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor: + return to_dtype_image(video, dtype, scale=scale) + + +@_register_kernel_internal(to_dtype, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +@_register_kernel_internal(to_dtype, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +@_register_kernel_internal(to_dtype, tv_tensors.Mask, tv_tensor_wrapper=False) +def _to_dtype_tensor_dispatch(inpt: torch.Tensor, dtype: torch.dtype, scale: bool = False) -> torch.Tensor: + # We don't need to unwrap and rewrap here, since TVTensor.to() preserves the type + return inpt.to(dtype) + + +def sanitize_bounding_boxes( + bounding_boxes: torch.Tensor, + format: Optional[tv_tensors.BoundingBoxFormat] = None, + canvas_size: Optional[tuple[int, int]] = None, + min_size: float = 1.0, + min_area: float = 1.0, +) -> tuple[torch.Tensor, torch.Tensor]: + """Remove degenerate/invalid bounding boxes and return the corresponding indexing mask. + + This removes bounding boxes that: + + - are below a given ``min_size`` or ``min_area``: by default this also removes degenerate boxes that have e.g. X2 <= X1. + - have any coordinate outside of their corresponding image. You may want to + call :func:`~torchvision.transforms.v2.functional.clamp_bounding_boxes` first to avoid undesired removals. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. It is critical to call this transform if + :class:`~torchvision.transforms.v2.RandomIoUCrop` was called. + If you want to be extra careful, you may call it after all transforms that + may modify bounding boxes but once at the end should be enough in most + cases. + + Args: + bounding_boxes (Tensor or :class:`~torchvision.tv_tensors.BoundingBoxes`): The bounding boxes to be sanitized. + format (str or :class:`~torchvision.tv_tensors.BoundingBoxFormat`, optional): The format of the bounding boxes. + Must be left to none if ``bounding_boxes`` is a :class:`~torchvision.tv_tensors.BoundingBoxes` object. + canvas_size (tuple of int, optional): The canvas_size of the bounding boxes + (size of the corresponding image/video). + Must be left to none if ``bounding_boxes`` is a :class:`~torchvision.tv_tensors.BoundingBoxes` object. + min_size (float, optional) The size below which bounding boxes are removed. Default is 1. + min_area (float, optional) The area below which bounding boxes are removed. Default is 1. + + Returns: + out (tuple of Tensors): The subset of valid bounding boxes, and the corresponding indexing mask. + The mask can then be used to subset other tensors (e.g. labels) that are associated with the bounding boxes. + """ + if torch.jit.is_scripting() or is_pure_tensor(bounding_boxes): + if format is None or canvas_size is None: + raise ValueError( + "format and canvas_size cannot be None if bounding_boxes is a pure tensor. " + f"Got format={format} and canvas_size={canvas_size}." + "Set those to appropriate values or pass bounding_boxes as a tv_tensors.BoundingBoxes object." + ) + if isinstance(format, str): + format = tv_tensors.BoundingBoxFormat[format.upper()] + valid = _get_sanitize_bounding_boxes_mask( + bounding_boxes, format=format, canvas_size=canvas_size, min_size=min_size, min_area=min_area + ) + bounding_boxes = bounding_boxes[valid] + else: + if not isinstance(bounding_boxes, tv_tensors.BoundingBoxes): + raise ValueError("bounding_boxes must be a tv_tensors.BoundingBoxes instance or a pure tensor.") + if format is not None or canvas_size is not None: + raise ValueError( + "format and canvas_size must be None when bounding_boxes is a tv_tensors.BoundingBoxes instance. " + f"Got format={format} and canvas_size={canvas_size}. " + "Leave those to None or pass bounding_boxes as a pure tensor." + ) + valid = _get_sanitize_bounding_boxes_mask( + bounding_boxes, + format=bounding_boxes.format, + canvas_size=bounding_boxes.canvas_size, + min_size=min_size, + min_area=min_area, + ) + bounding_boxes = tv_tensors.wrap(bounding_boxes[valid], like=bounding_boxes) + + return bounding_boxes, valid + + +def _get_sanitize_bounding_boxes_mask( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + min_size: float = 1.0, + min_area: float = 1.0, +) -> torch.Tensor: + + is_rotated = tv_tensors.is_rotated_bounding_format(format) + intermediate_format = tv_tensors.BoundingBoxFormat.XYXYXYXY if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + bounding_boxes = _convert_bounding_box_format(bounding_boxes, new_format=intermediate_format, old_format=format) + + image_h, image_w = canvas_size + if is_rotated: + dx12 = bounding_boxes[..., 0] - bounding_boxes[..., 2] + dy12 = bounding_boxes[..., 1] - bounding_boxes[..., 3] + dx23 = bounding_boxes[..., 3] - bounding_boxes[..., 5] + dy23 = bounding_boxes[..., 4] - bounding_boxes[..., 6] + ws = torch.sqrt(dx12**2 + dy12**2) + hs = torch.sqrt(dx23**2 + dy23**2) + else: + ws, hs = bounding_boxes[:, 2] - bounding_boxes[:, 0], bounding_boxes[:, 3] - bounding_boxes[:, 1] + valid = (ws >= min_size) & (hs >= min_size) & (bounding_boxes >= 0).all(dim=-1) & (ws * hs >= min_area) + # TODO: Do we really need to check for out of bounds here? All + # transforms should be clamping anyway, so this should never happen? + image_h, image_w = canvas_size + valid &= (bounding_boxes[:, 0] <= image_w) & (bounding_boxes[:, 2] <= image_w) + valid &= (bounding_boxes[:, 1] <= image_h) & (bounding_boxes[:, 3] <= image_h) + if is_rotated: + valid &= (bounding_boxes[..., 4] <= image_w) & (bounding_boxes[..., 5] <= image_h) + valid &= (bounding_boxes[..., 6] <= image_w) & (bounding_boxes[..., 7] <= image_h) + return valid + + +def sanitize_keypoints( + key_points: torch.Tensor, + canvas_size: Optional[tuple[int, int]] = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Remove keypoints outside of the image area and their corresponding labels (if any). + + This transform removes keypoints or groups of keypoints and their associated labels that + have coordinates outside of their corresponding image. + If you would instead like to clamp such keypoints to the image edges, use + :class:`~torchvision.transforms.v2.ClampKeyPoints`. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. + + Keypoints can be passed as a set of individual keypoints or as a set of objects + (e.g., polygons or polygonal chains) consisting of a fixed number of keypoints of shape ``[..., 2]``. + When groups of keypoints are passed (i.e., an at least 3-dimensional tensor), + this transform will only remove entire groups, not individual keypoints within a group. + + Args: + key_points (Tensor or :class:`~torchvision.tv_tensors.KeyPoints`): The keypoints to be sanitized. + canvas_size (tuple of int, optional): The canvas_size of the keypoints + (size of the corresponding image/video). + Must be left to none if ``key_points`` is a :class:`~torchvision.tv_tensors.KeyPoints` object. + + Returns: + out (tuple of Tensors): The subset of valid keypoints, and the corresponding indexing mask. + The mask can then be used to subset other tensors (e.g. labels) that are associated with the keypoints. + """ + if torch.jit.is_scripting() or is_pure_tensor(key_points): + if canvas_size is None: + raise ValueError( + "canvas_size cannot be None if key_points is a pure tensor. " + "Set it to an appropriate value or pass key_points as a tv_tensors.KeyPoints object." + ) + valid = _get_sanitize_keypoints_mask( + key_points, + canvas_size=canvas_size, + ) + key_points = key_points[valid] + else: + if not isinstance(key_points, tv_tensors.KeyPoints): + raise ValueError("key_points must be a tv_tensors.KeyPoints instance or a pure tensor.") + if canvas_size is not None: + raise ValueError( + "canvas_size must be None when key_points is a tv_tensors.KeyPoints instance. " + f"Got canvas_size={canvas_size}. " + "Leave it to None or pass key_points as a pure tensor." + ) + valid = _get_sanitize_keypoints_mask( + key_points, + canvas_size=key_points.canvas_size, + ) + key_points = tv_tensors.wrap(key_points[valid], like=key_points) + + return key_points, valid + + +def _get_sanitize_keypoints_mask( + key_points: torch.Tensor, + canvas_size: tuple[int, int], +) -> torch.Tensor: + + h, w = canvas_size + + x, y = key_points[..., 0], key_points[..., 1] + valid = (x >= 0) & (x < w) & (y >= 0) & (y < h) + + valid = valid.flatten(start_dim=1).all(dim=1) if valid.ndim > 1 else valid + + return valid diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_temporal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_temporal.py new file mode 100644 index 0000000000000000000000000000000000000000..f932b06a295fd10316fba3e796ec4649053e92db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_temporal.py @@ -0,0 +1,27 @@ +import torch + +from torchvision import tv_tensors + +from torchvision.utils import _log_api_usage_once + +from ._utils import _get_kernel, _register_kernel_internal + + +def uniform_temporal_subsample(inpt: torch.Tensor, num_samples: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.UniformTemporalSubsample` for details.""" + if torch.jit.is_scripting(): + return uniform_temporal_subsample_video(inpt, num_samples=num_samples) + + _log_api_usage_once(uniform_temporal_subsample) + + kernel = _get_kernel(uniform_temporal_subsample, type(inpt)) + return kernel(inpt, num_samples=num_samples) + + +@_register_kernel_internal(uniform_temporal_subsample, torch.Tensor) +@_register_kernel_internal(uniform_temporal_subsample, tv_tensors.Video) +def uniform_temporal_subsample_video(video: torch.Tensor, num_samples: int) -> torch.Tensor: + # Reference: https://github.com/facebookresearch/pytorchvideo/blob/a0a131e/pytorchvideo/transforms/functional.py#L19 + t_max = video.shape[-4] - 1 + indices = torch.linspace(0, t_max, num_samples, device=video.device).long() + return torch.index_select(video, -4, indices) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_type_conversion.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_type_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a731fe143c365400d5905db8370c538097583a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_type_conversion.py @@ -0,0 +1,27 @@ +from typing import Union + +import numpy as np +import PIL.Image +import torch +from torchvision import tv_tensors +from torchvision.transforms import functional as _F + + +@torch.jit.unused +def to_image(inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray]) -> tv_tensors.Image: + """See :class:`~torchvision.transforms.v2.ToImage` for details.""" + if isinstance(inpt, np.ndarray): + output = torch.from_numpy(np.atleast_3d(inpt)).permute((2, 0, 1)).contiguous() + elif isinstance(inpt, PIL.Image.Image): + output = pil_to_tensor(inpt) + elif isinstance(inpt, torch.Tensor): + output = inpt + else: + raise TypeError( + f"Input can either be a pure Tensor, a numpy array, or a PIL image, but got {type(inpt)} instead." + ) + return tv_tensors.Image(output) + + +to_pil_image = _F.to_pil_image +pil_to_tensor = _F.pil_to_tensor diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b857285c891c8502ff95ed7c3ac998953aa04170 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_utils.py @@ -0,0 +1,142 @@ +import functools +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import torch +from torchvision import tv_tensors + +_FillType = Union[int, float, Sequence[int], Sequence[float], None] +_FillTypeJIT = Optional[list[float]] + + +def is_pure_tensor(inpt: Any) -> bool: + return isinstance(inpt, torch.Tensor) and not isinstance(inpt, tv_tensors.TVTensor) + + +# {functional: {input_type: type_specific_kernel}} +_KERNEL_REGISTRY: dict[Callable, dict[type, Callable]] = {} + + +def _kernel_tv_tensor_wrapper(kernel): + @functools.wraps(kernel) + def wrapper(inpt, *args, **kwargs): + # If you're wondering whether we could / should get rid of this wrapper, + # the answer is no: we want to pass pure Tensors to avoid the overhead + # of the __torch_function__ machinery. Note that this is always valid, + # regardless of whether we override __torch_function__ in our base class + # or not. + # Also, even if we didn't call `as_subclass` here, we would still need + # this wrapper to call wrap(), because the TVTensor type would be + # lost after the first operation due to our own __torch_function__ + # logic. + output = kernel(inpt.as_subclass(torch.Tensor), *args, **kwargs) + return tv_tensors.wrap(output, like=inpt) + + return wrapper + + +def _register_kernel_internal(functional, input_type, *, tv_tensor_wrapper=True): + registry = _KERNEL_REGISTRY.setdefault(functional, {}) + if input_type in registry: + raise ValueError(f"Functional {functional} already has a kernel registered for type {input_type}.") + + def decorator(kernel): + registry[input_type] = ( + _kernel_tv_tensor_wrapper(kernel) + if issubclass(input_type, tv_tensors.TVTensor) and tv_tensor_wrapper + else kernel + ) + return kernel + + return decorator + + +def _name_to_functional(name): + import torchvision.transforms.v2.functional # noqa + + try: + return getattr(torchvision.transforms.v2.functional, name) + except AttributeError: + raise ValueError( + f"Could not find functional with name '{name}' in torchvision.transforms.v2.functional." + ) from None + + +_BUILTIN_DATAPOINT_TYPES = { + obj for obj in tv_tensors.__dict__.values() if isinstance(obj, type) and issubclass(obj, tv_tensors.TVTensor) +} + + +def register_kernel(functional, tv_tensor_cls): + """Decorate a kernel to register it for a functional and a (custom) tv_tensor type. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_tv_tensors.py` for usage + details. + """ + if isinstance(functional, str): + functional = _name_to_functional(name=functional) + elif not ( + callable(functional) + and getattr(functional, "__module__", "").startswith("torchvision.transforms.v2.functional") + ): + raise ValueError( + f"Kernels can only be registered on functionals from the torchvision.transforms.v2.functional namespace, " + f"but got {functional}." + ) + + if not (isinstance(tv_tensor_cls, type) and issubclass(tv_tensor_cls, tv_tensors.TVTensor)): + raise ValueError( + f"Kernels can only be registered for subclasses of torchvision.tv_tensors.TVTensor, " + f"but got {tv_tensor_cls}." + ) + + if tv_tensor_cls in _BUILTIN_DATAPOINT_TYPES: + raise ValueError(f"Kernels cannot be registered for the builtin tv_tensor classes, but got {tv_tensor_cls}") + + return _register_kernel_internal(functional, tv_tensor_cls, tv_tensor_wrapper=False) + + +def _get_kernel(functional, input_type, *, allow_passthrough=False): + registry = _KERNEL_REGISTRY.get(functional) + if not registry: + raise ValueError(f"No kernel registered for functional {functional.__name__}.") + + for cls in input_type.__mro__: + if cls in registry: + return registry[cls] + elif cls is tv_tensors.TVTensor: + # We don't want user-defined tv_tensors to dispatch to the pure Tensor kernels, so we explicit stop the + # MRO traversal before hitting torch.Tensor. We can even stop at tv_tensors.TVTensor, since we don't + # allow kernels to be registered for tv_tensors.TVTensor anyway. + break + + if allow_passthrough: + return lambda inpt, *args, **kwargs: inpt + + raise TypeError( + f"Functional F.{functional.__name__} supports inputs of type {registry.keys()}, " + f"but got {input_type} instead." + ) + + +# This basically replicates _register_kernel_internal, but with a specialized wrapper for five_crop / ten_crop +# We could get rid of this by letting _register_kernel_internal take arbitrary functionals rather than wrap_kernel: bool +def _register_five_ten_crop_kernel_internal(functional, input_type): + registry = _KERNEL_REGISTRY.setdefault(functional, {}) + if input_type in registry: + raise TypeError(f"Functional '{functional}' already has a kernel registered for type '{input_type}'.") + + def wrap(kernel): + @functools.wraps(kernel) + def wrapper(inpt, *args, **kwargs): + output = kernel(inpt, *args, **kwargs) + container_type = type(output) + return container_type(tv_tensors.wrap(o, like=inpt) for o in output) + + return wrapper + + def decorator(kernel): + registry[input_type] = wrap(kernel) if issubclass(input_type, tv_tensors.TVTensor) else kernel + return kernel + + return decorator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..744e52411355ed4d20de1fb653da3123854fa16d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/__init__.py @@ -0,0 +1,39 @@ +import torch + +from ._bounding_boxes import BoundingBoxes, BoundingBoxFormat, is_rotated_bounding_format +from ._image import Image +from ._keypoints import KeyPoints +from ._mask import Mask +from ._torch_function_helpers import set_return_type +from ._tv_tensor import TVTensor +from ._video import Video + + +# TODO: Fix this. We skip this method as it leads to +# RecursionError: maximum recursion depth exceeded while calling a Python object +# Until `disable` is removed, there will be graph breaks after all calls to functional transforms +@torch.compiler.disable +def wrap(wrappee, *, like, **kwargs): + """Convert a :class:`torch.Tensor` (``wrappee``) into the same :class:`~torchvision.tv_tensors.TVTensor` subclass as ``like``. + + If ``like`` is a :class:`~torchvision.tv_tensors.BoundingBoxes`, the ``format`` and ``canvas_size`` of + ``like`` are assigned to ``wrappee``, unless they are passed as ``kwargs``. + + Args: + wrappee (Tensor): The tensor to convert. + like (:class:`~torchvision.tv_tensors.TVTensor`): The reference. + ``wrappee`` will be converted into the same subclass as ``like``. + kwargs: Can contain "format", "canvas_size" and "clamping_mode" if ``like`` is a :class:`~torchvision.tv_tensor.BoundingBoxes`. + Ignored otherwise. + """ + if isinstance(like, BoundingBoxes): + return BoundingBoxes._wrap( + wrappee, + format=kwargs.get("format", like.format), + canvas_size=kwargs.get("canvas_size", like.canvas_size), + clamping_mode=kwargs.get("clamping_mode", like.clamping_mode), + ) + elif isinstance(like, KeyPoints): + return KeyPoints._wrap(wrappee, canvas_size=kwargs.get("canvas_size", like.canvas_size)) + else: + return wrappee.as_subclass(type(like)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_bounding_boxes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_bounding_boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa3e50458d7677b0c986dcff2361f2f0ff72448 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_bounding_boxes.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +from enum import Enum +from typing import Any, Optional + +import torch +from torch.utils._pytree import tree_flatten + +from ._tv_tensor import TVTensor + + +class BoundingBoxFormat(Enum): + """Coordinate format of a bounding box. + + Available formats are: + + * ``XYXY``: bounding box represented via corners; x1, y1 being top left; + x2, y2 being bottom right. + * ``XYWH``: bounding box represented via corner, width and height; x1, y1 + being top left; w, h being width and height. + * ``CXCYWH``: bounding box represented via centre, width and height; cx, + cy being center of box; w, h being width and height. + * ``XYWHR``: rotated boxes represented via corner, width and height; x1, y1 + being top left; w, h being width and height. r is rotation angle in + degrees. + * ``CXCYWHR``: rotated boxes represented via center, width and height; cx, + cy being center of box; w, h being width and height. r is rotation angle + in degrees. + * ``XYXYXYXY``: rotated boxes represented via corners; x1, y1 being top + left; x2, y2 being top right; x3, y3 being bottom right; x4, y4 being + bottom left. + """ + + XYXY = "XYXY" + XYWH = "XYWH" + CXCYWH = "CXCYWH" + XYWHR = "XYWHR" + CXCYWHR = "CXCYWHR" + XYXYXYXY = "XYXYXYXY" + + +# TODO: Once torchscript supports Enums with staticmethod +# this can be put into BoundingBoxFormat as staticmethod +def is_rotated_bounding_format(format: BoundingBoxFormat | str) -> bool: + if isinstance(format, BoundingBoxFormat): + return ( + format == BoundingBoxFormat.XYWHR + or format == BoundingBoxFormat.CXCYWHR + or format == BoundingBoxFormat.XYXYXYXY + ) + elif isinstance(format, str): + return format in ("XYWHR", "CXCYWHR", "XYXYXYXY") + else: + raise ValueError(f"format should be str or BoundingBoxFormat, got {type(format)}") + + +# This should ideally be a Literal, but torchscript fails. +CLAMPING_MODE_TYPE = Optional[str] + + +class BoundingBoxes(TVTensor): + """:class:`torch.Tensor` subclass for bounding boxes with shape ``[N, K]``. + + .. note:: + Support for rotated bounding boxes was released in TorchVision 0.23 and + is currently a BETA feature. We don't expect the API to change, but + there may be some rare edge-cases. If you find any issues, please report + them on our bug tracker: + https://github.com/pytorch/vision/issues?q=is:open+is:issue + + Where ``N`` is the number of bounding boxes + and ``K`` is 4 for unrotated boxes, and 5 or 8 for rotated boxes. + + .. note:: + There should be only one :class:`~torchvision.tv_tensors.BoundingBoxes` + instance per sample e.g. ``{"img": img, "bbox": BoundingBoxes(...)}``, + although one :class:`~torchvision.tv_tensors.BoundingBoxes` object can + contain multiple bounding boxes. + + Args: + data: Any data that can be turned into a tensor with :func:`torch.as_tensor`. + format (BoundingBoxFormat, str): Format of the bounding box. + canvas_size (two-tuple of ints): Height and width of the corresponding image or video. + clamping_mode: The clamping mode to use when applying transforms that may result in bounding boxes + partially outside of the image. Possible values are: "soft", "hard", or ``None``. Read more in :ref:`clamping_mode_tuto`. + dtype (torch.dtype, optional): Desired data type of the bounding box. If omitted, will be inferred from + ``data``. + device (torch.device, optional): Desired device of the bounding box. If omitted and ``data`` is a + :class:`torch.Tensor`, the device is taken from it. Otherwise, the bounding box is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record operations on the bounding box. If omitted and + ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. + """ + + format: BoundingBoxFormat + canvas_size: tuple[int, int] + clamping_mode: CLAMPING_MODE_TYPE + + @classmethod + def _wrap(cls, tensor: torch.Tensor, *, format: BoundingBoxFormat | str, canvas_size: tuple[int, int], clamping_mode: CLAMPING_MODE_TYPE = "soft", check_dims: bool = True) -> BoundingBoxes: # type: ignore[override] + if check_dims: + if tensor.ndim == 1: + tensor = tensor.unsqueeze(0) + elif tensor.ndim != 2: + raise ValueError(f"Expected a 1D or 2D tensor, got {tensor.ndim}D") + if clamping_mode is not None and clamping_mode not in ("hard", "soft"): + raise ValueError(f"clamping_mode must be None, hard or soft, got {clamping_mode}.") + + if isinstance(format, str): + format = BoundingBoxFormat[format.upper()] + + bounding_boxes = tensor.as_subclass(cls) + bounding_boxes.format = format + bounding_boxes.canvas_size = canvas_size + bounding_boxes.clamping_mode = clamping_mode + return bounding_boxes + + def __new__( + cls, + data: Any, + *, + format: BoundingBoxFormat | str, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE = "soft", + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> BoundingBoxes: + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + if not torch.is_floating_point(tensor) and is_rotated_bounding_format(format): + raise ValueError(f"Rotated bounding boxes should be floating point tensors, got {tensor.dtype}.") + return cls._wrap(tensor, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode) + + @classmethod + def _wrap_output( + cls, + output: torch.Tensor, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> BoundingBoxes: + # If there are BoundingBoxes instances in the output, their metadata got lost when we called + # super().__torch_function__. We need to restore the metadata somehow, so we choose to take + # the metadata from the first bbox in the parameters. + # This should be what we want in most cases. When it's not, it's probably a mis-use anyway, e.g. + # something like some_xyxy_bbox + some_xywh_bbox; we don't guard against those cases. + flat_params, _ = tree_flatten(args + (tuple(kwargs.values()) if kwargs else ())) # type: ignore[operator] + first_bbox_from_args = next(x for x in flat_params if isinstance(x, BoundingBoxes)) + format, canvas_size, clamping_mode = ( + first_bbox_from_args.format, + first_bbox_from_args.canvas_size, + first_bbox_from_args.clamping_mode, + ) + + if isinstance(output, torch.Tensor) and not isinstance(output, BoundingBoxes): + output = BoundingBoxes._wrap( + output, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode, check_dims=False + ) + elif isinstance(output, (tuple, list)): + # This branch exists for chunk() and unbind() + output = type(output)( + BoundingBoxes._wrap( + part, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode, check_dims=False + ) + for part in output + ) + return output + + def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] + return self._make_repr(format=self.format, canvas_size=self.canvas_size, clamping_mode=self.clamping_mode) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_dataset_wrapper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_dataset_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..23683221f6005a9ce6a55e785e59409a649d7928 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_dataset_wrapper.py @@ -0,0 +1,666 @@ +# type: ignore + +from __future__ import annotations + +import collections.abc + +import contextlib +from collections import defaultdict +from copy import copy + +import torch + +from torchvision import datasets, tv_tensors +from torchvision.transforms.v2 import functional as F + +__all__ = ["wrap_dataset_for_transforms_v2"] + + +def wrap_dataset_for_transforms_v2(dataset, target_keys=None): + """Wrap a ``torchvision.dataset`` for usage with :mod:`torchvision.transforms.v2`. + + Example: + >>> dataset = torchvision.datasets.CocoDetection(...) + >>> dataset = wrap_dataset_for_transforms_v2(dataset) + + .. note:: + + For now, only the most popular datasets are supported. Furthermore, the wrapper only supports dataset + configurations that are fully supported by ``torchvision.transforms.v2``. If you encounter an error prompting you + to raise an issue to ``torchvision`` for a dataset or configuration that you need, please do so. + + The dataset samples are wrapped according to the description below. + + Special cases: + + * :class:`~torchvision.datasets.CocoDetection`: Instead of returning the target as list of dicts, the wrapper + returns a dict of lists. In addition, the key-value-pairs ``"boxes"`` (in ``XYXY`` coordinate format), + ``"masks"`` and ``"labels"`` are added and wrap the data in the corresponding ``torchvision.tv_tensors``. + The original keys are preserved. If ``target_keys`` is omitted, returns only the values for the + ``"image_id"``, ``"boxes"``, and ``"labels"``. + * :class:`~torchvision.datasets.VOCDetection`: The key-value-pairs ``"boxes"`` and ``"labels"`` are added to + the target and wrap the data in the corresponding ``torchvision.tv_tensors``. The original keys are + preserved. If ``target_keys`` is omitted, returns only the values for the ``"boxes"`` and ``"labels"``. + * :class:`~torchvision.datasets.CelebA`: The target for ``target_type="bbox"`` is converted to the ``XYXY`` + coordinate format and wrapped into a :class:`~torchvision.tv_tensors.BoundingBoxes` tv_tensor. + * :class:`~torchvision.datasets.Kitti`: Instead returning the target as list of dicts, the wrapper returns a + dict of lists. In addition, the key-value-pairs ``"boxes"`` and ``"labels"`` are added and wrap the data + in the corresponding ``torchvision.tv_tensors``. The original keys are preserved. If ``target_keys`` is + omitted, returns only the values for the ``"boxes"`` and ``"labels"``. + * :class:`~torchvision.datasets.OxfordIIITPet`: The target for ``target_type="segmentation"`` is wrapped into a + :class:`~torchvision.tv_tensors.Mask` tv_tensor. + * :class:`~torchvision.datasets.Cityscapes`: The target for ``target_type="semantic"`` is wrapped into a + :class:`~torchvision.tv_tensors.Mask` tv_tensor. The target for ``target_type="instance"`` is *replaced* by + a dictionary with the key-value-pairs ``"masks"`` (as :class:`~torchvision.tv_tensors.Mask` tv_tensor) and + ``"labels"``. + * :class:`~torchvision.datasets.WIDERFace`: The value for key ``"bbox"`` in the target is converted to ``XYXY`` + coordinate format and wrapped into a :class:`~torchvision.tv_tensors.BoundingBoxes` tv_tensor. + + Image classification datasets + + This wrapper is a no-op for image classification datasets, since they were already fully supported by + :mod:`torchvision.transforms` and thus no change is needed for :mod:`torchvision.transforms.v2`. + + Segmentation datasets + + Segmentation datasets, e.g. :class:`~torchvision.datasets.VOCSegmentation`, return a two-tuple of + :class:`PIL.Image.Image`'s. This wrapper leaves the image as is (first item), while wrapping the + segmentation mask into a :class:`~torchvision.tv_tensors.Mask` (second item). + + Video classification datasets + + Video classification datasets, e.g. :class:`~torchvision.datasets.Kinetics`, return a three-tuple containing a + :class:`torch.Tensor` for the video and audio and a :class:`int` as label. This wrapper wraps the video into a + :class:`~torchvision.tv_tensors.Video` while leaving the other items as is. + + .. note:: + + Only datasets constructed with ``output_format="TCHW"`` are supported, since the alternative + ``output_format="THWC"`` is not supported by :mod:`torchvision.transforms.v2`. + + Args: + dataset: the dataset instance to wrap for compatibility with transforms v2. + target_keys: Target keys to return in case the target is a dictionary. If ``None`` (default), selected keys are + specific to the dataset. If ``"all"``, returns the full target. Can also be a collection of strings for + fine grained access. Currently only supported for :class:`~torchvision.datasets.CocoDetection`, + :class:`~torchvision.datasets.VOCDetection`, :class:`~torchvision.datasets.Kitti`, and + :class:`~torchvision.datasets.WIDERFace`. See above for details. + """ + if not ( + target_keys is None + or target_keys == "all" + or (isinstance(target_keys, collections.abc.Collection) and all(isinstance(key, str) for key in target_keys)) + ): + raise ValueError( + f"`target_keys` can be None, 'all', or a collection of strings denoting the keys to be returned, " + f"but got {target_keys}" + ) + + # Imagine we have isinstance(dataset, datasets.ImageNet). This will create a new class with the name + # "WrappedImageNet" at runtime that doubly inherits from VisionDatasetTVTensorWrapper (see below) as well as the + # original ImageNet class. This allows the user to do regular isinstance(wrapped_dataset, datasets.ImageNet) checks, + # while we can still inject everything that we need. + wrapped_dataset_cls = type(f"Wrapped{type(dataset).__name__}", (VisionDatasetTVTensorWrapper, type(dataset)), {}) + # Since VisionDatasetTVTensorWrapper comes before ImageNet in the MRO, calling the class hits + # VisionDatasetTVTensorWrapper.__init__ first. Since we are never doing super().__init__(...), the constructor of + # ImageNet is never hit. That is by design, since we don't want to create the dataset instance again, but rather + # have the existing instance as attribute on the new object. + return wrapped_dataset_cls(dataset, target_keys) + + +class WrapperFactories(dict): + def register(self, dataset_cls): + def decorator(wrapper_factory): + self[dataset_cls] = wrapper_factory + return wrapper_factory + + return decorator + + +# We need this two-stage design, i.e. a wrapper factory producing the actual wrapper, since some wrappers depend on the +# dataset instance rather than just the class, since they require the user defined instance attributes. Thus, we can +# provide a wrapping from the dataset class to the factory here, but can only instantiate the wrapper at runtime when +# we have access to the dataset instance. +WRAPPER_FACTORIES = WrapperFactories() + + +class VisionDatasetTVTensorWrapper: + def __init__(self, dataset, target_keys): + dataset_cls = type(dataset) + + if not isinstance(dataset, datasets.VisionDataset): + raise TypeError( + f"This wrapper is meant for subclasses of `torchvision.datasets.VisionDataset`, " + f"but got a '{dataset_cls.__name__}' instead.\n" + f"For an example of how to perform the wrapping for custom datasets, see\n\n" + "https://pytorch.org/vision/main/auto_examples/plot_tv_tensors.html#do-i-have-to-wrap-the-output-of-the-datasets-myself" + ) + + for cls in dataset_cls.mro(): + if cls in WRAPPER_FACTORIES: + wrapper_factory = WRAPPER_FACTORIES[cls] + if target_keys is not None and cls not in { + datasets.CocoDetection, + datasets.VOCDetection, + datasets.Kitti, + datasets.WIDERFace, + }: + raise ValueError( + f"`target_keys` is currently only supported for `CocoDetection`, `VOCDetection`, `Kitti`, " + f"and `WIDERFace`, but got {cls.__name__}." + ) + break + elif cls is datasets.VisionDataset: + # TODO: If we have documentation on how to do that, put a link in the error message. + msg = f"No wrapper exists for dataset class {dataset_cls.__name__}. Please wrap the output yourself." + if dataset_cls in datasets.__dict__.values(): + msg = ( + f"{msg} If an automated wrapper for this dataset would be useful for you, " + f"please open an issue at https://github.com/pytorch/vision/issues." + ) + raise TypeError(msg) + + self._dataset = dataset + self._target_keys = target_keys + self._wrapper = wrapper_factory(dataset, target_keys) + + # We need to disable the transforms on the dataset here to be able to inject the wrapping before we apply them. + # Although internally, `datasets.VisionDataset` merges `transform` and `target_transform` into the joint + # `transforms` + # https://github.com/pytorch/vision/blob/135a0f9ea9841b6324b4fe8974e2543cbb95709a/torchvision/datasets/vision.py#L52-L54 + # some (if not most) datasets still use `transform` and `target_transform` individually. Thus, we need to + # disable all three here to be able to extract the untransformed sample to wrap. + self.transform, dataset.transform = dataset.transform, None + self.target_transform, dataset.target_transform = dataset.target_transform, None + self.transforms, dataset.transforms = dataset.transforms, None + + def __getattr__(self, item): + with contextlib.suppress(AttributeError): + return object.__getattribute__(self, item) + + return getattr(self._dataset, item) + + def __getitem__(self, idx): + # This gets us the raw sample since we disabled the transforms for the underlying dataset in the constructor + # of this class + sample = self._dataset[idx] + + sample = self._wrapper(idx, sample) + + # Regardless of whether the user has supplied the transforms individually (`transform` and `target_transform`) + # or joint (`transforms`), we can access the full functionality through `transforms` + if self.transforms is not None: + sample = self.transforms(*sample) + + return sample + + def __len__(self): + return len(self._dataset) + + # TODO: maybe we should use __getstate__ and __setstate__ instead of __reduce__, as recommended in the docs. + def __reduce__(self): + # __reduce__ gets called when we try to pickle the dataset. + # In a DataLoader with spawn context, this gets called `num_workers` times from the main process. + + # We have to reset the [target_]transform[s] attributes of the dataset + # to their original values, because we previously set them to None in __init__(). + dataset = copy(self._dataset) + dataset.transform = self.transform + dataset.transforms = self.transforms + dataset.target_transform = self.target_transform + + return wrap_dataset_for_transforms_v2, (dataset, self._target_keys) + + +def raise_not_supported(description): + raise RuntimeError( + f"{description} is currently not supported by this wrapper. " + f"If this would be helpful for you, please open an issue at https://github.com/pytorch/vision/issues." + ) + + +def identity(item): + return item + + +def identity_wrapper_factory(dataset, target_keys): + def wrapper(idx, sample): + return sample + + return wrapper + + +def pil_image_to_mask(pil_image): + return tv_tensors.Mask(pil_image) + + +def parse_target_keys(target_keys, *, available, default): + if target_keys is None: + target_keys = default + if target_keys == "all": + target_keys = available + else: + target_keys = set(target_keys) + extra = target_keys - available + if extra: + raise ValueError(f"Target keys {sorted(extra)} are not available") + + return target_keys + + +def list_of_dicts_to_dict_of_lists(list_of_dicts): + dict_of_lists = defaultdict(list) + for dct in list_of_dicts: + for key, value in dct.items(): + dict_of_lists[key].append(value) + return dict(dict_of_lists) + + +def wrap_target_by_type(target, *, target_types, type_wrappers): + if not isinstance(target, (tuple, list)): + target = [target] + + wrapped_target = tuple( + type_wrappers.get(target_type, identity)(item) for target_type, item in zip(target_types, target) + ) + + if len(wrapped_target) == 1: + wrapped_target = wrapped_target[0] + + return wrapped_target + + +def classification_wrapper_factory(dataset, target_keys): + return identity_wrapper_factory(dataset, target_keys) + + +for dataset_cls in [ + datasets.Caltech256, + datasets.CIFAR10, + datasets.CIFAR100, + datasets.ImageNet, + datasets.MNIST, + datasets.FashionMNIST, + datasets.GTSRB, + datasets.DatasetFolder, + datasets.ImageFolder, + datasets.Imagenette, +]: + WRAPPER_FACTORIES.register(dataset_cls)(classification_wrapper_factory) + + +def segmentation_wrapper_factory(dataset, target_keys): + def wrapper(idx, sample): + image, mask = sample + return image, pil_image_to_mask(mask) + + return wrapper + + +for dataset_cls in [ + datasets.VOCSegmentation, +]: + WRAPPER_FACTORIES.register(dataset_cls)(segmentation_wrapper_factory) + + +def video_classification_wrapper_factory(dataset, target_keys): + if dataset.video_clips.output_format == "THWC": + raise RuntimeError( + f"{type(dataset).__name__} with `output_format='THWC'` is not supported by this wrapper, " + f"since it is not compatible with the transformations. Please use `output_format='TCHW'` instead." + ) + + def wrapper(idx, sample): + video, audio, label = sample + + video = tv_tensors.Video(video) + + return video, audio, label + + return wrapper + + +for dataset_cls in [ + datasets.HMDB51, + datasets.Kinetics, + datasets.UCF101, +]: + WRAPPER_FACTORIES.register(dataset_cls)(video_classification_wrapper_factory) + + +@WRAPPER_FACTORIES.register(datasets.Caltech101) +def caltech101_wrapper_factory(dataset, target_keys): + if "annotation" in dataset.target_type: + raise_not_supported("Caltech101 dataset with `target_type=['annotation', ...]`") + + return classification_wrapper_factory(dataset, target_keys) + + +@WRAPPER_FACTORIES.register(datasets.CocoDetection) +def coco_dectection_wrapper_factory(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + # native + "segmentation", + "area", + "iscrowd", + "image_id", + "bbox", + "category_id", + # added by the wrapper + "boxes", + "masks", + "labels", + }, + default={"image_id", "boxes", "labels"}, + ) + + def segmentation_to_mask(segmentation, *, canvas_size): + from pycocotools import mask + + if isinstance(segmentation, dict): + # if counts is a string, it is already an encoded RLE mask + if not isinstance(segmentation["counts"], str): + segmentation = mask.frPyObjects(segmentation, *canvas_size) + elif isinstance(segmentation, list): + segmentation = mask.merge(mask.frPyObjects(segmentation, *canvas_size)) + else: + raise ValueError(f"COCO segmentation expected to be a dict or a list, got {type(segmentation)}") + return torch.from_numpy(mask.decode(segmentation)) + + def wrapper(idx, sample): + image_id = dataset.ids[idx] + + image, target = sample + + if not target: + return image, dict(image_id=image_id) + + canvas_size = tuple(F.get_size(image)) + + batched_target = list_of_dicts_to_dict_of_lists(target) + target = {} + + if "image_id" in target_keys: + target["image_id"] = image_id + + if "boxes" in target_keys: + target["boxes"] = F.convert_bounding_box_format( + tv_tensors.BoundingBoxes( + batched_target["bbox"], + format=tv_tensors.BoundingBoxFormat.XYWH, + canvas_size=canvas_size, + ), + new_format=tv_tensors.BoundingBoxFormat.XYXY, + ) + + if "masks" in target_keys: + target["masks"] = tv_tensors.Mask( + torch.stack( + [ + segmentation_to_mask(segmentation, canvas_size=canvas_size) + for segmentation in batched_target["segmentation"] + ] + ), + ) + + if "labels" in target_keys: + target["labels"] = torch.tensor(batched_target["category_id"]) + + for target_key in target_keys - {"image_id", "boxes", "masks", "labels"}: + target[target_key] = batched_target[target_key] + + return image, target + + return wrapper + + +WRAPPER_FACTORIES.register(datasets.CocoCaptions)(identity_wrapper_factory) + + +VOC_DETECTION_CATEGORIES = [ + "__background__", + "aeroplane", + "bicycle", + "bird", + "boat", + "bottle", + "bus", + "car", + "cat", + "chair", + "cow", + "diningtable", + "dog", + "horse", + "motorbike", + "person", + "pottedplant", + "sheep", + "sofa", + "train", + "tvmonitor", +] +VOC_DETECTION_CATEGORY_TO_IDX = dict(zip(VOC_DETECTION_CATEGORIES, range(len(VOC_DETECTION_CATEGORIES)))) + + +@WRAPPER_FACTORIES.register(datasets.VOCDetection) +def voc_detection_wrapper_factory(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + # native + "annotation", + # added by the wrapper + "boxes", + "labels", + }, + default={"boxes", "labels"}, + ) + + def wrapper(idx, sample): + image, target = sample + + batched_instances = list_of_dicts_to_dict_of_lists(target["annotation"]["object"]) + + if "annotation" not in target_keys: + target = {} + + if "boxes" in target_keys: + target["boxes"] = tv_tensors.BoundingBoxes( + [ + [int(bndbox[part]) for part in ("xmin", "ymin", "xmax", "ymax")] + for bndbox in batched_instances["bndbox"] + ], + format=tv_tensors.BoundingBoxFormat.XYXY, + canvas_size=(image.height, image.width), + ) + + if "labels" in target_keys: + target["labels"] = torch.tensor( + [VOC_DETECTION_CATEGORY_TO_IDX[category] for category in batched_instances["name"]] + ) + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.SBDataset) +def sbd_wrapper(dataset, target_keys): + if dataset.mode == "boundaries": + raise_not_supported("SBDataset with mode='boundaries'") + + return segmentation_wrapper_factory(dataset, target_keys) + + +@WRAPPER_FACTORIES.register(datasets.CelebA) +def celeba_wrapper_factory(dataset, target_keys): + if any(target_type in dataset.target_type for target_type in ["attr", "landmarks"]): + raise_not_supported("`CelebA` dataset with `target_type=['attr', 'landmarks', ...]`") + + def wrapper(idx, sample): + image, target = sample + + target = wrap_target_by_type( + target, + target_types=dataset.target_type, + type_wrappers={ + "bbox": lambda item: F.convert_bounding_box_format( + tv_tensors.BoundingBoxes( + item, + format=tv_tensors.BoundingBoxFormat.XYWH, + canvas_size=(image.height, image.width), + ), + new_format=tv_tensors.BoundingBoxFormat.XYXY, + ), + }, + ) + + return image, target + + return wrapper + + +KITTI_CATEGORIES = ["Car", "Van", "Truck", "Pedestrian", "Person_sitting", "Cyclist", "Tram", "Misc", "DontCare"] +KITTI_CATEGORY_TO_IDX = dict(zip(KITTI_CATEGORIES, range(len(KITTI_CATEGORIES)))) + + +@WRAPPER_FACTORIES.register(datasets.Kitti) +def kitti_wrapper_factory(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + # native + "type", + "truncated", + "occluded", + "alpha", + "bbox", + "dimensions", + "location", + "rotation_y", + # added by the wrapper + "boxes", + "labels", + }, + default={"boxes", "labels"}, + ) + + def wrapper(idx, sample): + image, target = sample + + if target is None: + return image, target + + batched_target = list_of_dicts_to_dict_of_lists(target) + target = {} + + if "boxes" in target_keys: + target["boxes"] = tv_tensors.BoundingBoxes( + batched_target["bbox"], + format=tv_tensors.BoundingBoxFormat.XYXY, + canvas_size=(image.height, image.width), + ) + + if "labels" in target_keys: + target["labels"] = torch.tensor([KITTI_CATEGORY_TO_IDX[category] for category in batched_target["type"]]) + + for target_key in target_keys - {"boxes", "labels"}: + target[target_key] = batched_target[target_key] + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.OxfordIIITPet) +def oxford_iiit_pet_wrapper_factor(dataset, target_keys): + def wrapper(idx, sample): + image, target = sample + + if target is not None: + target = wrap_target_by_type( + target, + target_types=dataset._target_types, + type_wrappers={ + "segmentation": pil_image_to_mask, + }, + ) + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.Cityscapes) +def cityscapes_wrapper_factory(dataset, target_keys): + if any(target_type in dataset.target_type for target_type in ["polygon", "color"]): + raise_not_supported("`Cityscapes` dataset with `target_type=['polygon', 'color', ...]`") + + def instance_segmentation_wrapper(mask): + # See https://github.com/mcordts/cityscapesScripts/blob/8da5dd00c9069058ccc134654116aac52d4f6fa2/cityscapesscripts/preparation/json2instanceImg.py#L7-L21 + data = pil_image_to_mask(mask) + masks = [] + labels = [] + for id in data.unique(): + masks.append(data == id) + label = id + if label >= 1_000: + label //= 1_000 + labels.append(label) + return dict(masks=tv_tensors.Mask(torch.stack(masks)), labels=torch.stack(labels)) + + def wrapper(idx, sample): + image, target = sample + + target = wrap_target_by_type( + target, + target_types=dataset.target_type, + type_wrappers={ + "instance": instance_segmentation_wrapper, + "semantic": pil_image_to_mask, + }, + ) + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.WIDERFace) +def widerface_wrapper(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + "bbox", + "blur", + "expression", + "illumination", + "occlusion", + "pose", + "invalid", + }, + default="all", + ) + + def wrapper(idx, sample): + image, target = sample + + if target is None: + return image, target + + target = {key: target[key] for key in target_keys} + + if "bbox" in target_keys: + target["bbox"] = F.convert_bounding_box_format( + tv_tensors.BoundingBoxes( + target["bbox"], format=tv_tensors.BoundingBoxFormat.XYWH, canvas_size=(image.height, image.width) + ), + new_format=tv_tensors.BoundingBoxFormat.XYXY, + ) + + return image, target + + return wrapper diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_image.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_image.py new file mode 100644 index 0000000000000000000000000000000000000000..19fe468ac8103035ebb9dd87faa4f454f286de92 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_image.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from typing import Any + +import PIL.Image +import torch + +from ._tv_tensor import TVTensor + + +class Image(TVTensor): + """:class:`torch.Tensor` subclass for images with shape ``[..., C, H, W]``. + + .. note:: + + In the :ref:`transforms `, ``Image`` instances are largely + interchangeable with pure :class:`torch.Tensor`. See + :ref:`this note ` for more details. + + Args: + data (tensor-like, PIL.Image.Image): Any data that can be turned into a tensor with :func:`torch.as_tensor` as + well as PIL images. + dtype (torch.dtype, optional): Desired data type. If omitted, will be inferred from + ``data``. + device (torch.device, optional): Desired device. If omitted and ``data`` is a + :class:`torch.Tensor`, the device is taken from it. Otherwise, the image is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record operations. If omitted and + ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. + """ + + def __new__( + cls, + data: Any, + *, + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> Image: + if isinstance(data, PIL.Image.Image): + from torchvision.transforms.v2 import functional as F + + data = F.pil_to_tensor(data) + + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + if tensor.ndim < 2: + raise ValueError(f"Tensor must be 2D or higher, got {tensor.ndim}D tensor.") + elif tensor.ndim == 2: + tensor = tensor.unsqueeze(0) + + return tensor.as_subclass(cls) + + def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] + return self._make_repr() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_keypoints.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_keypoints.py new file mode 100644 index 0000000000000000000000000000000000000000..aede31ad7db74b6aa4358fac8b9a1697c70ef88a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_keypoints.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from typing import Any, Mapping, Sequence + +import torch +from torch.utils._pytree import tree_flatten + +from ._tv_tensor import TVTensor + + +class KeyPoints(TVTensor): + """:class:`torch.Tensor` subclass for tensors with shape ``[..., 2]`` that represent points in an image. + + .. note:: + Support for keypoints was released in TorchVision 0.23 and is currently + a BETA feature. We don't expect the API to change, but there may be some + rare edge-cases. If you find any issues, please report them on our bug + tracker: https://github.com/pytorch/vision/issues?q=is:open+is:issue + Each point is represented by its X and Y coordinates along the width and + height dimensions, respectively. + + Each point is represented by its X and Y coordinates along the width and height dimensions, respectively. + + KeyPoints may represent any object that can be represented by sequences of 2D points: + + - `Polygonal chains `_, + including polylines, Bézier curves, etc., which can be of shape + ``[N_chains, N_points, 2]``. + - Polygons, which can be of shape ``[N_polygons, N_points, 2]``. + - Skeletons, which can be of shape ``[N_skeletons, N_bones, 2, 2]`` for + pose-estimation models. + + .. note:: + Like for :class:`torchvision.tv_tensors.BoundingBoxes`, there should + only be a single instance of the + :class:`torchvision.tv_tensors.KeyPoints` class per sample e.g. + ``{"img": img, "poins_of_interest": KeyPoints(...)}``, although one + :class:`torchvision.tv_tensors.KeyPoints` object can contain multiple + key points + + Args: + data: Any data that can be turned into a tensor with + :func:`torch.as_tensor`. + canvas_size (two-tuple of ints): Height and width of the corresponding + image or video. + dtype (torch.dtype, optional): Desired data type of the bounding box. If + omitted, will be inferred from ``data``. + device (torch.device, optional): Desired device of the bounding box. If + omitted and ``data`` is a :class:`torch.Tensor`, the device is taken + from it. Otherwise, the bounding box is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record + operations on the bounding box. If omitted and ``data`` is a + :class:`torch.Tensor`, the value is taken from it. Otherwise, + defaults to ``False``. + """ + + canvas_size: tuple[int, int] + + @classmethod + def _wrap(cls, tensor: torch.Tensor, *, canvas_size: tuple[int, int], check_dims: bool = True) -> KeyPoints: # type: ignore[override] + if check_dims: + if tensor.ndim == 1: + tensor = tensor.unsqueeze(0) + elif tensor.shape[-1] != 2: + raise ValueError(f"Expected a tensor of shape (..., 2), not {tensor.shape}") + points = tensor.as_subclass(cls) + points.canvas_size = canvas_size + return points + + def __new__( + cls, + data: Any, + *, + canvas_size: tuple[int, int], + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> KeyPoints: + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + return cls._wrap(tensor, canvas_size=canvas_size) + + @classmethod + def _wrap_output( + cls, + output: torch.Tensor, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> KeyPoints: + # Similar to BoundingBoxes._wrap_output(), see comment there. + flat_params, _ = tree_flatten(args + (tuple(kwargs.values()) if kwargs else ())) # type: ignore[operator] + first_keypoints_from_args = next(x for x in flat_params if isinstance(x, KeyPoints)) + canvas_size = first_keypoints_from_args.canvas_size + + if isinstance(output, torch.Tensor) and not isinstance(output, KeyPoints): + output = KeyPoints._wrap(output, canvas_size=canvas_size, check_dims=False) + elif isinstance(output, (tuple, list)): + # This branch exists for chunk() and unbind() + output = type(output)(KeyPoints._wrap(part, canvas_size=canvas_size, check_dims=False) for part in output) + return output + + def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] + return self._make_repr(canvas_size=self.canvas_size) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_mask.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..f43a5c7e2fd477fd129ef84df2117e1cd28b53e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_mask.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import Any + +import PIL.Image +import torch + +from ._tv_tensor import TVTensor + + +class Mask(TVTensor): + """:class:`torch.Tensor` subclass for segmentation and detection masks with shape ``[..., H, W]``. + + Args: + data (tensor-like, PIL.Image.Image): Any data that can be turned into a tensor with :func:`torch.as_tensor` as + well as PIL images. + dtype (torch.dtype, optional): Desired data type. If omitted, will be inferred from + ``data``. + device (torch.device, optional): Desired device. If omitted and ``data`` is a + :class:`torch.Tensor`, the device is taken from it. Otherwise, the mask is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record operations. If omitted and + ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. + """ + + def __new__( + cls, + data: Any, + *, + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> Mask: + if isinstance(data, PIL.Image.Image): + from torchvision.transforms.v2 import functional as F + + data = F.pil_to_tensor(data) + + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + return tensor.as_subclass(cls) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_torch_function_helpers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_torch_function_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..66812fb5ca641fc4dabd10aad281ee6614229168 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/tv_tensors/_torch_function_helpers.py @@ -0,0 +1,78 @@ +import torch + +_TORCHFUNCTION_SUBCLASS = False + + +class _ReturnTypeCM: + def __init__(self, to_restore): + self.to_restore = to_restore + + def __enter__(self): + return self + + def __exit__(self, *args): + global _TORCHFUNCTION_SUBCLASS + _TORCHFUNCTION_SUBCLASS = self.to_restore + + +def set_return_type(return_type: str): + """Set the return type of torch operations on :class:`~torchvision.tv_tensors.TVTensor`. + + This only affects the behaviour of torch operations. It has no effect on + ``torchvision`` transforms or functionals, which will always return as + output the same type that was passed as input. + + .. warning:: + + We recommend using :class:`~torchvision.transforms.v2.ToPureTensor` at + the end of your transform pipelines if you use + ``set_return_type("TVTensor")``. This will avoid the + ``__torch_function__`` overhead in the models ``forward()``. + + Can be used as a global flag for the entire program: + + .. code:: python + + img = tv_tensors.Image(torch.rand(3, 5, 5)) + img + 2 # This is a pure Tensor (default behaviour) + + set_return_type("TVTensor") + img + 2 # This is an Image + + or as a context manager to restrict the scope: + + .. code:: python + + img = tv_tensors.Image(torch.rand(3, 5, 5)) + img + 2 # This is a pure Tensor + with set_return_type("TVTensor"): + img + 2 # This is an Image + img + 2 # This is a pure Tensor + + Args: + return_type (str): Can be "TVTensor" or "Tensor" (case-insensitive). + Default is "Tensor" (i.e. pure :class:`torch.Tensor`). + """ + global _TORCHFUNCTION_SUBCLASS + to_restore = _TORCHFUNCTION_SUBCLASS + + try: + _TORCHFUNCTION_SUBCLASS = {"tensor": False, "tvtensor": True}[return_type.lower()] + except KeyError: + raise ValueError(f"return_type must be 'TVTensor' or 'Tensor', got {return_type}") from None + + return _ReturnTypeCM(to_restore) + + +def _must_return_subclass(): + return _TORCHFUNCTION_SUBCLASS + + +# For those ops we always want to preserve the original subclass instead of returning a pure Tensor +_FORCE_TORCHFUNCTION_SUBCLASS = { + torch.Tensor.clone, + torch.Tensor.to, + torch.Tensor.detach, + torch.Tensor.requires_grad_, + torch.Tensor.pin_memory, +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e26b01a48c53e66ffa121cc7fb47d0a1e11cce2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/utils.py @@ -0,0 +1,807 @@ +import collections +import math +import pathlib +import warnings +from itertools import repeat +from types import FunctionType +from typing import Any, BinaryIO, Optional, Union + +import numpy as np +import torch +from PIL import __version__ as PILLOW_VERSION_STRING, Image, ImageColor, ImageDraw, ImageFont + +__all__ = [ + "_Image_fromarray", + "make_grid", + "save_image", + "draw_bounding_boxes", + "draw_segmentation_masks", + "draw_keypoints", + "flow_to_image", +] + + +@torch.no_grad() +def make_grid( + tensor: Union[torch.Tensor, list[torch.Tensor]], + nrow: int = 8, + padding: int = 2, + normalize: bool = False, + value_range: Optional[tuple[int, int]] = None, + scale_each: bool = False, + pad_value: float = 0.0, +) -> torch.Tensor: + """ + Make a grid of images. + + Args: + tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W) + or a list of images all of the same size. + nrow (int, optional): Number of images displayed in each row of the grid. + The final grid size is ``(B / nrow, nrow)``. Default: ``8``. + padding (int, optional): amount of padding. Default: ``2``. + normalize (bool, optional): If True, shift the image to the range (0, 1), + by the min and max values specified by ``value_range``. Default: ``False``. + value_range (tuple, optional): tuple (min, max) where min and max are numbers, + then these numbers are used to normalize the image. By default, min and max + are computed from the tensor. + scale_each (bool, optional): If ``True``, scale each image in the batch of + images separately rather than the (min, max) over all images. Default: ``False``. + pad_value (float, optional): Value for the padded pixels. Default: ``0``. + + Returns: + grid (Tensor): the tensor containing grid of images. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(make_grid) + if not torch.is_tensor(tensor): + if isinstance(tensor, list): + for t in tensor: + if not torch.is_tensor(t): + raise TypeError(f"tensor or list of tensors expected, got a list containing {type(t)}") + else: + raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}") + + # if list of tensors, convert to a 4D mini-batch Tensor + if isinstance(tensor, list): + tensor = torch.stack(tensor, dim=0) + + if tensor.dim() == 2: # single image H x W + tensor = tensor.unsqueeze(0) + if tensor.dim() == 3: # single image + if tensor.size(0) == 1: # if single-channel, convert to 3-channel + tensor = torch.cat((tensor, tensor, tensor), 0) + tensor = tensor.unsqueeze(0) + + if tensor.dim() == 4 and tensor.size(1) == 1: # single-channel images + tensor = torch.cat((tensor, tensor, tensor), 1) + + if normalize is True: + tensor = tensor.clone() # avoid modifying tensor in-place + if value_range is not None and not isinstance(value_range, tuple): + raise TypeError("value_range has to be a tuple (min, max) if specified. min and max are numbers") + + def norm_ip(img, low, high): + img.clamp_(min=low, max=high) + img.sub_(low).div_(max(high - low, 1e-5)) + + def norm_range(t, value_range): + if value_range is not None: + norm_ip(t, value_range[0], value_range[1]) + else: + norm_ip(t, float(t.min()), float(t.max())) + + if scale_each is True: + for t in tensor: # loop over mini-batch dimension + norm_range(t, value_range) + else: + norm_range(tensor, value_range) + + if not isinstance(tensor, torch.Tensor): + raise TypeError("tensor should be of type torch.Tensor") + if tensor.size(0) == 1: + return tensor.squeeze(0) + + # make the mini-batch of images into a grid + nmaps = tensor.size(0) + xmaps = min(nrow, nmaps) + ymaps = int(math.ceil(float(nmaps) / xmaps)) + height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding) + num_channels = tensor.size(1) + grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value) + k = 0 + for y in range(ymaps): + for x in range(xmaps): + if k >= nmaps: + break + # Tensor.copy_() is a valid method but seems to be missing from the stubs + # https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_ + grid.narrow(1, y * height + padding, height - padding).narrow( # type: ignore[attr-defined] + 2, x * width + padding, width - padding + ).copy_(tensor[k]) + k = k + 1 + return grid + + +class _ImageDrawTV(ImageDraw.ImageDraw): + """ + A wrapper around PIL.ImageDraw to add functionalities for drawing rotated bounding boxes. + """ + + def oriented_rectangle(self, xy, fill=None, outline=None, width=1): + self.dashed_line(((xy[0], xy[1]), (xy[2], xy[3])), width=width, fill=outline) + for i in range(2, len(xy), 2): + self.line( + ((xy[i], xy[i + 1]), (xy[(i + 2) % len(xy)], xy[(i + 3) % len(xy)])), + width=width, + fill=outline, + ) + self.polygon(xy, fill=fill, outline=None, width=0) + + def dashed_line(self, xy, fill=None, width=0, joint=None, dash_length=5, space_length=5): + # Calculate the total length of the line + total_length = 0 + for i in range(1, len(xy)): + x1, y1 = xy[i - 1] + x2, y2 = xy[i] + total_length += ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 + # Initialize the current position and the current dash + current_position = 0 + current_dash = True + # Iterate over the coordinates of the line + for i in range(1, len(xy)): + x1, y1 = xy[i - 1] + x2, y2 = xy[i] + # Calculate the length of this segment + segment_length = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 + # While there are still dashes to draw on this segment + while segment_length > 0: + # Calculate the length of this dash + dash_length_to_draw = min(segment_length, dash_length if current_dash else space_length) + # Calculate the end point of this dash + dx = x2 - x1 + dy = y2 - y1 + angle = math.atan2(dy, dx) + end_x = x1 + math.cos(angle) * dash_length_to_draw + end_y = y1 + math.sin(angle) * dash_length_to_draw + # If this is a dash, draw it + if current_dash: + self.line([(x1, y1), (end_x, end_y)], fill, width, joint) + # Update the current position and the current dash + current_position += dash_length_to_draw + segment_length -= dash_length_to_draw + x1, y1 = end_x, end_y + current_dash = not current_dash + + +def _Image_fromarray( + obj: np.ndarray, + mode: str, +) -> Image.Image: + """ + A wrapper around PIL.Image.fromarray to mitigate the deprecation of the + mode paramter. See: + https://pillow.readthedocs.io/en/stable/releasenotes/11.3.0.html#image-fromarray-mode-parameter + """ + + # This may throw if the version string is from an install that comes from a + # non-stable or development version. We'll fall back to the old behavior in + # such cases. + try: + PILLOW_VERSION = tuple(int(x) for x in PILLOW_VERSION_STRING.split(".")) + except Exception: + PILLOW_VERSION = None + + if PILLOW_VERSION is not None and PILLOW_VERSION >= (11, 3): + # The actual PR that implements the deprecation has more context for why + # it was done, and also points out some problems: + # + # https://github.com/python-pillow/Pillow/pull/9018 + # + # Our use case falls into those problems. We actually rely on the old + # behavior of Image.fromarray(): + # + # new behavior: PIL will infer the image mode from the data passed + # in. That is, the type and shape determines the mode. + # + # old behiavor: The mode will change how PIL reads the image, + # regardless of the data. That is, it will make the + # data work with the mode. + # + # Our uses of Image.fromarray() are effectively a "turn into PIL image + # AND convert the kind" operation. In particular, in + # functional.to_pil_image() and transforms.ToPILImage. + # + # However, Image.frombuffer() still performs this conversion. The code + # below is lifted from the new implementation of Image.fromarray(). We + # omit the code that infers the mode, and use the code that figures out + # from the data passed in (obj) what the correct parameters are to + # Image.frombuffer(). + # + # Note that the alternate solution below does not work: + # + # img = Image.fromarray(obj) + # img = img.convert(mode) + # + # The resulting image has very different actual pixel values than before. + # + # TODO: Issue #9151. Pillow has an open PR to restore the functionality + # we rely on: + # + # https://github.com/python-pillow/Pillow/pull/9063 + # + # When that is part of a release, we can revisit this hack below. + arr = obj.__array_interface__ + shape = arr["shape"] + ndim = len(shape) + size = 1 if ndim == 1 else shape[1], shape[0] + + strides = arr.get("strides", None) + contiguous_obj: Union[np.ndarray, bytes] = obj + if strides is not None: + # We require that the data is contiguous; if it is not, we need to + # convert it into a contiguous format. + if hasattr(obj, "tobytes"): + contiguous_obj = obj.tobytes() + elif hasattr(obj, "tostring"): + contiguous_obj = obj.tostring() + else: + raise ValueError("Unable to convert obj into contiguous format") + + return Image.frombuffer(mode, size, contiguous_obj, "raw", mode, 0, 1) + else: + return Image.fromarray(obj, mode) + + +@torch.no_grad() +def save_image( + tensor: Union[torch.Tensor, list[torch.Tensor]], + fp: Union[str, pathlib.Path, BinaryIO], + format: Optional[str] = None, + **kwargs, +) -> None: + """ + Save a given Tensor into an image file. + + Args: + tensor (Tensor or list): Image to be saved. If given a mini-batch tensor, + saves the tensor as a grid of images by calling ``make_grid``. + fp (string or file object): A filename or a file object + format(Optional): If omitted, the format to use is determined from the filename extension. + If a file object was used instead of a filename, this parameter should always be used. + **kwargs: Other arguments are documented in ``make_grid``. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(save_image) + grid = make_grid(tensor, **kwargs) + # Add 0.5 after unnormalizing to [0, 255] to round to the nearest integer + ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy() + im = Image.fromarray(ndarr) + im.save(fp, format=format) + + +@torch.no_grad() +def draw_bounding_boxes( + image: torch.Tensor, + boxes: torch.Tensor, + labels: Optional[list[str]] = None, + colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, + fill: Optional[bool] = False, + width: int = 1, + font: Optional[str] = None, + font_size: Optional[int] = None, + label_colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, + label_background_colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, + fill_labels: bool = False, +) -> torch.Tensor: + """ + Draws bounding boxes on given RGB image. + The image values should be uint8 in [0, 255] or float in [0, 1]. + If fill is True, Resulting Tensor should be saved as PNG image. + + Args: + image (Tensor): Tensor of shape (C, H, W) and dtype uint8 or float. + boxes (Tensor): Tensor of size (N, 4) or (N, 8) containing bounding boxes. + For (N, 4), the format is (xmin, ymin, xmax, ymax) and the boxes are absolute coordinates with respect to the image. + In other words: `0 <= xmin < xmax < W` and `0 <= ymin < ymax < H`. + For (N, 8), the format is (x1, y1, x2, y2, x3, y3, x4, y4) and the boxes are absolute coordinates with respect to the underlying + object, so no need to verify the latter inequalities. + labels (List[str]): List containing the labels of bounding boxes. + colors (color or list of colors, optional): List containing the colors + of the boxes or single color for all boxes. The color can be represented as + PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``. + By default, random colors are generated for boxes. + fill (bool): If `True` fills the bounding box with specified color. + width (int): Width of bounding box. + font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may + also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`, + `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS. + font_size (int): The requested font size in points. + label_colors (color or list of colors, optional): Colors for the label text. See the description of the + `colors` argument for details. Defaults to the same colors used for the boxes, or to black if ``fill_labels`` is True. + label_background_colors (color or list of colors, optional): Colors for the label text box fill. Defaults to the + same colors used for the boxes. Ignored when ``fill_labels`` is False. + fill_labels (bool): If `True` fills the label background with specified color (from the ``label_background_colors`` parameter, + or from the ``colors`` parameter if not specified). Default: False. + + Returns: + img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted. + + """ + import torchvision.transforms.v2.functional as F # noqa + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(draw_bounding_boxes) + if not isinstance(image, torch.Tensor): + raise TypeError(f"Tensor expected, got {type(image)}") + elif not (image.dtype == torch.uint8 or image.is_floating_point()): + raise ValueError(f"The image dtype must be uint8 or float, got {image.dtype}") + elif image.dim() != 3: + raise ValueError("Pass individual images, not batches") + elif image.size(0) not in {1, 3}: + raise ValueError("Only grayscale and RGB images are supported") + elif boxes.shape[-1] == 4 and ((boxes[:, 0] > boxes[:, 2]).any() or (boxes[:, 1] > boxes[:, 3]).any()): + raise ValueError( + "Boxes need to be in (xmin, ymin, xmax, ymax) format. Use torchvision.ops.box_convert to convert them" + ) + + num_boxes = boxes.shape[0] + + if num_boxes == 0: + warnings.warn("boxes doesn't contain any box. No box was drawn") + return image + + if labels is None: + labels: Union[list[str], list[None]] = [None] * num_boxes # type: ignore[no-redef] + elif len(labels) != num_boxes: + raise ValueError( + f"Number of boxes ({num_boxes}) and labels ({len(labels)}) mismatch. Please specify labels for each box." + ) + + colors = _parse_colors(colors, num_objects=num_boxes) # type: ignore[assignment] + if label_colors or fill_labels: + label_colors = _parse_colors(label_colors if label_colors else "black", num_objects=num_boxes) # type: ignore[assignment] + else: + label_colors = colors.copy() # type: ignore[assignment] + + if fill_labels and label_background_colors: + label_background_colors = _parse_colors(label_background_colors, num_objects=num_boxes) # type: ignore[assignment] + else: + label_background_colors = colors.copy() # type: ignore[assignment] + + if font is None: + if font_size is not None: + warnings.warn("Argument 'font_size' will be ignored since 'font' is not set.") + txt_font = ImageFont.load_default() + else: + txt_font = ImageFont.truetype(font=font, size=font_size or 10) + + # Handle Grayscale images + if image.size(0) == 1: + image = torch.tile(image, (3, 1, 1)) + + original_dtype = image.dtype + if original_dtype.is_floating_point: + image = F.to_dtype(image, dtype=torch.uint8, scale=True) + + img_to_draw = F.to_pil_image(image) + img_boxes = boxes.to(torch.int64).tolist() + + if fill: + draw = _ImageDrawTV(img_to_draw, "RGBA") + else: + draw = _ImageDrawTV(img_to_draw) + + for bbox, color, label, label_color, label_bg_color in zip(img_boxes, colors, labels, label_colors, label_background_colors): # type: ignore[arg-type] + draw_method = draw.oriented_rectangle if len(bbox) > 4 else draw.rectangle + fill_color = color + (100,) if fill else None + draw_method(bbox, width=width, outline=color, fill=fill_color) + + if label is not None: + box_margin = 1 + margin = width + box_margin + if fill_labels: + left, top, right, bottom = draw.textbbox((bbox[0] + margin, bbox[1] + margin), label, font=txt_font) + draw.rectangle( + (left - box_margin, top - box_margin, right + box_margin, bottom + box_margin), fill=label_bg_color # type: ignore[arg-type] + ) + draw.text((bbox[0] + margin, bbox[1] + margin), label, fill=label_color, font=txt_font) # type: ignore[arg-type] + + out = F.pil_to_tensor(img_to_draw) + if original_dtype.is_floating_point: + out = F.to_dtype(out, dtype=original_dtype, scale=True) + return out + + +@torch.no_grad() +def draw_segmentation_masks( + image: torch.Tensor, + masks: torch.Tensor, + alpha: float = 0.8, + colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, +) -> torch.Tensor: + """ + Draws segmentation masks on given RGB image. + The image values should be uint8 in [0, 255] or float in [0, 1]. + + Args: + image (Tensor): Tensor of shape (3, H, W) and dtype uint8 or float. + masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool. + alpha (float): Float number between 0 and 1 denoting the transparency of the masks. + 0 means full transparency, 1 means no transparency. + colors (color or list of colors, optional): List containing the colors + of the masks or single color for all masks. The color can be represented as + PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``. + By default, random colors are generated for each mask. + + Returns: + img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(draw_segmentation_masks) + if not isinstance(image, torch.Tensor): + raise TypeError(f"The image must be a tensor, got {type(image)}") + elif not (image.dtype == torch.uint8 or image.is_floating_point()): + raise ValueError(f"The image dtype must be uint8 or float, got {image.dtype}") + elif image.dim() != 3: + raise ValueError("Pass individual images, not batches") + elif image.size()[0] != 3: + raise ValueError("Pass an RGB image. Other Image formats are not supported") + if masks.ndim == 2: + masks = masks[None, :, :] + if masks.ndim != 3: + raise ValueError("masks must be of shape (H, W) or (batch_size, H, W)") + if masks.dtype != torch.bool: + raise ValueError(f"The masks must be of dtype bool. Got {masks.dtype}") + if masks.shape[-2:] != image.shape[-2:]: + raise ValueError("The image and the masks must have the same height and width") + + num_masks = masks.size()[0] + overlapping_masks = masks.sum(dim=0) > 1 + + if num_masks == 0: + warnings.warn("masks doesn't contain any mask. No mask was drawn") + return image + + original_dtype = image.dtype + colors = [ + torch.tensor(color, dtype=original_dtype, device=image.device) + for color in _parse_colors(colors, num_objects=num_masks, dtype=original_dtype) + ] + + img_to_draw = image.detach().clone() + # TODO: There might be a way to vectorize this + for mask, color in zip(masks, colors): + img_to_draw[:, mask] = color[:, None] + + img_to_draw[:, overlapping_masks] = 0 + + out = image * (1 - alpha) + img_to_draw * alpha + # Note: at this point, out is a float tensor in [0, 1] or [0, 255] depending on original_dtype + return out.to(original_dtype) + + +@torch.no_grad() +def draw_keypoints( + image: torch.Tensor, + keypoints: torch.Tensor, + connectivity: Optional[list[tuple[int, int]]] = None, + colors: Optional[Union[str, tuple[int, int, int]]] = None, + radius: int = 2, + width: int = 3, + visibility: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Draws Keypoints on given RGB image. + The image values should be uint8 in [0, 255] or float in [0, 1]. + Keypoints can be drawn for multiple instances at a time. + + This method allows that keypoints and their connectivity are drawn based on the visibility of this keypoint. + + Args: + image (Tensor): Tensor of shape (3, H, W) and dtype uint8 or float. + keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoint locations for each of the N instances, + in the format [x, y]. + connectivity (List[Tuple[int, int]]]): A List of tuple where each tuple contains a pair of keypoints + to be connected. + If at least one of the two connected keypoints has a ``visibility`` of False, + this specific connection is not drawn. + Exclusions due to invisibility are computed per-instance. + colors (str, Tuple): The color can be represented as + PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``. + radius (int): Integer denoting radius of keypoint. + width (int): Integer denoting width of line connecting keypoints. + visibility (Tensor): Tensor of shape (num_instances, K) specifying the visibility of the K + keypoints for each of the N instances. + True means that the respective keypoint is visible and should be drawn. + False means invisible, so neither the point nor possible connections containing it are drawn. + The input tensor will be cast to bool. + Default ``None`` means that all the keypoints are visible. + For more details, see :ref:`draw_keypoints_with_visibility`. + + Returns: + img (Tensor[C, H, W]): Image Tensor with keypoints drawn. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(draw_keypoints) + # validate image + if not isinstance(image, torch.Tensor): + raise TypeError(f"The image must be a tensor, got {type(image)}") + elif not (image.dtype == torch.uint8 or image.is_floating_point()): + raise ValueError(f"The image dtype must be uint8 or float, got {image.dtype}") + elif image.dim() != 3: + raise ValueError("Pass individual images, not batches") + elif image.size()[0] != 3: + raise ValueError("Pass an RGB image. Other Image formats are not supported") + + # validate keypoints + if keypoints.ndim != 3: + raise ValueError("keypoints must be of shape (num_instances, K, 2)") + + # validate visibility + if visibility is None: # set default + visibility = torch.ones(keypoints.shape[:-1], dtype=torch.bool) + if visibility.ndim == 3: + # If visibility was passed as pred.split([2, 1], dim=-1), it will be of shape (num_instances, K, 1). + # We make sure it is of shape (num_instances, K). This isn't documented, we're just being nice. + visibility = visibility.squeeze(-1) + if visibility.ndim != 2: + raise ValueError(f"visibility must be of shape (num_instances, K). Got ndim={visibility.ndim}") + if visibility.shape != keypoints.shape[:-1]: + raise ValueError( + "keypoints and visibility must have the same dimensionality for num_instances and K. " + f"Got {visibility.shape=} and {keypoints.shape=}" + ) + + original_dtype = image.dtype + if original_dtype.is_floating_point: + from torchvision.transforms.v2.functional import to_dtype # noqa + + image = to_dtype(image, dtype=torch.uint8, scale=True) + + ndarr = image.permute(1, 2, 0).cpu().numpy() + img_to_draw = Image.fromarray(ndarr) + draw = ImageDraw.Draw(img_to_draw) + img_kpts = keypoints.to(torch.int64).tolist() + img_vis = visibility.cpu().bool().tolist() + + for kpt_inst, vis_inst in zip(img_kpts, img_vis): + for kpt_coord, kp_vis in zip(kpt_inst, vis_inst): + if not kp_vis: + continue + x1 = kpt_coord[0] - radius + x2 = kpt_coord[0] + radius + y1 = kpt_coord[1] - radius + y2 = kpt_coord[1] + radius + draw.ellipse([x1, y1, x2, y2], fill=colors, outline=None, width=0) + + if connectivity: + for connection in connectivity: + if (not vis_inst[connection[0]]) or (not vis_inst[connection[1]]): + continue + start_pt_x = kpt_inst[connection[0]][0] + start_pt_y = kpt_inst[connection[0]][1] + + end_pt_x = kpt_inst[connection[1]][0] + end_pt_y = kpt_inst[connection[1]][1] + + draw.line( + ((start_pt_x, start_pt_y), (end_pt_x, end_pt_y)), + width=width, + ) + + out = torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1) + if original_dtype.is_floating_point: + out = to_dtype(out, dtype=original_dtype, scale=True) + return out + + +# Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization +@torch.no_grad() +def flow_to_image(flow: torch.Tensor) -> torch.Tensor: + """ + Converts a flow to an RGB image. + + Args: + flow (Tensor): Flow of shape (N, 2, H, W) or (2, H, W) and dtype torch.float. + + Returns: + img (Tensor): Image Tensor of dtype uint8 where each color corresponds + to a given flow direction. Shape is (N, 3, H, W) or (3, H, W) depending on the input. + """ + + if flow.dtype != torch.float: + raise ValueError(f"Flow should be of dtype torch.float, got {flow.dtype}.") + + orig_shape = flow.shape + if flow.ndim == 3: + flow = flow[None] # Add batch dim + + if flow.ndim != 4 or flow.shape[1] != 2: + raise ValueError(f"Input flow should have shape (2, H, W) or (N, 2, H, W), got {orig_shape}.") + + max_norm = torch.sum(flow**2, dim=1).sqrt().max() + epsilon = torch.finfo((flow).dtype).eps + normalized_flow = flow / (max_norm + epsilon) + img = _normalized_flow_to_image(normalized_flow) + + if len(orig_shape) == 3: + img = img[0] # Remove batch dim + return img + + +@torch.no_grad() +def _normalized_flow_to_image(normalized_flow: torch.Tensor) -> torch.Tensor: + """ + Converts a batch of normalized flow to an RGB image. + + Args: + normalized_flow (torch.Tensor): Normalized flow tensor of shape (N, 2, H, W) + Returns: + img (Tensor(N, 3, H, W)): Flow visualization image of dtype uint8. + """ + + N, _, H, W = normalized_flow.shape + device = normalized_flow.device + flow_image = torch.zeros((N, 3, H, W), dtype=torch.uint8, device=device) + colorwheel = _make_colorwheel().to(device) # shape [55x3] + num_cols = colorwheel.shape[0] + norm = torch.sum(normalized_flow**2, dim=1).sqrt() + a = torch.atan2(-normalized_flow[:, 1, :, :], -normalized_flow[:, 0, :, :]) / torch.pi + fk = (a + 1) / 2 * (num_cols - 1) + k0 = torch.floor(fk).to(torch.long) + k1 = k0 + 1 + k1[k1 == num_cols] = 0 + f = fk - k0 + + for c in range(colorwheel.shape[1]): + tmp = colorwheel[:, c] + col0 = tmp[k0] / 255.0 + col1 = tmp[k1] / 255.0 + col = (1 - f) * col0 + f * col1 + col = 1 - norm * (1 - col) + flow_image[:, c, :, :] = torch.floor(255 * col) + return flow_image + + +def _make_colorwheel() -> torch.Tensor: + """ + Generates a color wheel for optical flow visualization as presented in: + Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007) + URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf. + + Returns: + colorwheel (Tensor[55, 3]): Colorwheel Tensor. + """ + + RY = 15 + YG = 6 + GC = 4 + CB = 11 + BM = 13 + MR = 6 + + ncols = RY + YG + GC + CB + BM + MR + colorwheel = torch.zeros((ncols, 3)) + col = 0 + + # RY + colorwheel[0:RY, 0] = 255 + colorwheel[0:RY, 1] = torch.floor(255 * torch.arange(0, RY) / RY) + col = col + RY + # YG + colorwheel[col : col + YG, 0] = 255 - torch.floor(255 * torch.arange(0, YG) / YG) + colorwheel[col : col + YG, 1] = 255 + col = col + YG + # GC + colorwheel[col : col + GC, 1] = 255 + colorwheel[col : col + GC, 2] = torch.floor(255 * torch.arange(0, GC) / GC) + col = col + GC + # CB + colorwheel[col : col + CB, 1] = 255 - torch.floor(255 * torch.arange(CB) / CB) + colorwheel[col : col + CB, 2] = 255 + col = col + CB + # BM + colorwheel[col : col + BM, 2] = 255 + colorwheel[col : col + BM, 0] = torch.floor(255 * torch.arange(0, BM) / BM) + col = col + BM + # MR + colorwheel[col : col + MR, 2] = 255 - torch.floor(255 * torch.arange(MR) / MR) + colorwheel[col : col + MR, 0] = 255 + return colorwheel + + +def _generate_color_palette(num_objects: int): + palette = torch.tensor([2**25 - 1, 2**15 - 1, 2**21 - 1]) + return [tuple((i * palette) % 255) for i in range(num_objects)] + + +def _parse_colors( + colors: Union[None, str, tuple[int, int, int], list[Union[str, tuple[int, int, int]]]], + *, + num_objects: int, + dtype: torch.dtype = torch.uint8, +) -> list[tuple[int, int, int]]: + """ + Parses a specification of colors for a set of objects. + + Args: + colors: A specification of colors for the objects. This can be one of the following: + - None: to generate a color palette automatically. + - A list of colors: where each color is either a string (specifying a named color) or an RGB tuple. + - A string or an RGB tuple: to use the same color for all objects. + + If `colors` is a tuple, it should be a 3-tuple specifying the RGB values of the color. + If `colors` is a list, it should have at least as many elements as the number of objects to color. + + num_objects (int): The number of objects to color. + + Returns: + A list of 3-tuples, specifying the RGB values of the colors. + + Raises: + ValueError: If the number of colors in the list is less than the number of objects to color. + If `colors` is not a list, tuple, string or None. + """ + if colors is None: + colors = _generate_color_palette(num_objects) + elif isinstance(colors, list): + if len(colors) < num_objects: + raise ValueError( + f"Number of colors must be equal or larger than the number of objects, but got {len(colors)} < {num_objects}." + ) + elif not isinstance(colors, (tuple, str)): + raise ValueError(f"colors must be a tuple or a string, or a list thereof, but got {colors}.") + elif isinstance(colors, tuple) and len(colors) != 3: + raise ValueError(f"If passed as tuple, colors should be an RGB triplet, but got {colors}.") + else: # colors specifies a single color for all objects + colors = [colors] * num_objects + + colors = [ImageColor.getrgb(color) if isinstance(color, str) else color for color in colors] + if dtype.is_floating_point: # [0, 255] -> [0, 1] + colors = [tuple(v / 255 for v in color) for color in colors] # type: ignore[union-attr] + return colors # type: ignore[return-value] + + +def _log_api_usage_once(obj: Any) -> None: + """ + Logs API usage(module and name) within an organization. + In a large ecosystem, it's often useful to track the PyTorch and + TorchVision APIs usage. This API provides the similar functionality to the + logging module in the Python stdlib. It can be used for debugging purpose + to log which methods are used and by default it is inactive, unless the user + manually subscribes a logger via the `SetAPIUsageLogger method `_. + Please note it is triggered only once for the same API call within a process. + It does not collect any data from open-source users since it is no-op by default. + For more information, please refer to + * PyTorch note: https://pytorch.org/docs/stable/notes/large_scale_deployments.html#api-usage-logging; + * Logging policy: https://github.com/pytorch/vision/issues/5052; + + Args: + obj (class instance or method): an object to extract info from. + """ + module = obj.__module__ + if not module.startswith("torchvision"): + module = f"torchvision.internal.{module}" + name = obj.__class__.__name__ + if isinstance(obj, FunctionType): + name = obj.__name__ + torch._C._log_api_usage_once(f"{module}.{name}") + + +def _make_ntuple(x: Any, n: int) -> tuple[Any, ...]: + """ + Make n-tuple from input x. If x is an iterable, then we just convert it to tuple. + Otherwise, we will make a tuple of length n, all with value of x. + reference: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/utils.py#L8 + + Args: + x (Any): input value + n (int): length of the resulting tuple + """ + if isinstance(x, collections.abc.Iterable): + return tuple(x) + return tuple(repeat(x, n)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/version.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/version.py new file mode 100644 index 0000000000000000000000000000000000000000..d9351a61faa025f805776386e4afdc634dca80a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchvision/version.py @@ -0,0 +1,5 @@ +__version__ = '0.25.0+cu128' +git_version = '8ac84ee75afb1c327902156b5336f56ad63b7e2f' +from torchvision.extension import _check_cuda_version +if _check_cuda_version() > 0: + cuda = _check_cuda_version()