Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add ResNet-20, corruptions and improve docs #76

Merged
merged 35 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
0d1625f
:bug: Don't write CSV if no results
o-laurent Dec 19, 2023
dea9330
:sparkles: Add the Filter Response Norm layer
o-laurent Dec 19, 2023
63eaa3a
:sparkles: Add ResNet-20
o-laurent Dec 19, 2023
6cc8e34
:hammer: Refactor transforms folder
o-laurent Dec 20, 2023
268b283
:white_check_mark: Fix transforms tests
o-laurent Dec 20, 2023
fdc4251
Merge branch 'main' of github.com:ENSTA-U2IS/torch-uncertainty into dev
o-laurent Dec 20, 2023
0a684a4
:sparkles: Add some corruptions & start corresponding tutorial
o-laurent Dec 20, 2023
ce91b61
:fire: Remove useless folder
o-laurent Dec 20, 2023
af9aed5
:zap: Update actions
o-laurent Dec 20, 2023
be646bf
:shirt: Clean files
o-laurent Dec 20, 2023
223407a
:wrench: Add files to changed-files exclusion
o-laurent Dec 20, 2023
a1d2530
:sparkles: Add script for uploading ckpts
o-laurent Dec 22, 2023
69b675f
:shirt: Add a check in masksembles layers
o-laurent Dec 22, 2023
569be42
:zap: Update License
o-laurent Dec 24, 2023
20b94cc
:bug: Fix Sparsification metric
o-laurent Dec 24, 2023
e212876
:shirt: Refine the sparsification metric
o-laurent Dec 26, 2023
ea3d66a
:bug: Fix experiment scripts
o-laurent Dec 26, 2023
30317cc
:zap: Use new repo to get imagenet classes
o-laurent Dec 28, 2023
97ca4dc
:sparkles: Add more corruptions
o-laurent Dec 28, 2023
19c7b0f
:books: Improve the installation documentation
o-laurent Jan 3, 2024
7744996
:books: use init docstrings in autodoc
o-laurent Jan 3, 2024
76a7cec
:book: Standardize docstrings
o-laurent Jan 3, 2024
ad06558
:books: Add datamodules to the API
o-laurent Jan 3, 2024
57dab0d
:white_check_mark: Add tests for the corruptions
o-laurent Jan 3, 2024
69445d5
:bug: Fix build error
o-laurent Jan 3, 2024
354127c
:white_check_mark: Add tests for resnet20s
o-laurent Jan 3, 2024
33ae52d
:white_check_mark: Improve coverage
o-laurent Jan 3, 2024
e41309b
:white_check_mark: Continue improving coverage
o-laurent Jan 3, 2024
933d09a
:wrench: Don't compute the docs in draft PR
o-laurent Jan 3, 2024
4751622
:heavy_check_mark: Fix speckle noise
o-laurent Jan 3, 2024
61afc8c
:white_check_mark: Finish improving coverage
o-laurent Jan 3, 2024
f1f2762
:wrench: Fix building docs
o-laurent Jan 3, 2024
bbbca63
:white_check_mark: Fine-tune coverage
o-laurent Jan 3, 2024
8751d80
:fire: Remove useless code in tutorial
o-laurent Jan 3, 2024
57165a8
:fire: Avoid code copies in tutorial
o-laurent Jan 3, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .github/workflows/build-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ jobs:
documentation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: "pip"
cache-dependency-path: "pyproject.toml"

- name: Full Python version
run: |
Expand All @@ -40,9 +41,10 @@ jobs:
- name: Install dependencies
run: |
python3 -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cpu
python3 -m pip install .[dev,docs]
python3 -m pip install .[image,dev,docs]

- name: Sphinx build
if: github.event.pull_request.draft == false
run: |
cd docs && make clean && make html

Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/pypi-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.10"

Expand Down
16 changes: 10 additions & 6 deletions .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,14 @@ jobs:
env:
PYTHON_VERSION: ${{ matrix.python-version }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: "pip"
cache-dependency-path: "pyproject.toml"

# Update full Python version
- name: Full Python version
Expand All @@ -44,8 +45,11 @@ jobs:
auto_tutorials_source/**
data/**
experiments/**
README.md
CONTRIBUTING.md
*.md
*.yaml
*.yml
LICENSE
.gitignore

- name: Cache folder for Torch Uncertainty
if: steps.changed-files-specific.outputs.only_changed != 'true'
Expand All @@ -60,12 +64,12 @@ jobs:
if: steps.changed-files-specific.outputs.only_changed != 'true'
run: |
python3 -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cpu
python3 -m pip install .[dev,docs]
python3 -m pip install .[image,dev,docs]

- name: Check style & format
if: steps.changed-files-specific.outputs.only_changed != 'true'
run: |
python3 -m ruff check torch_uncertainty tests --no-fix --exit-non-zero-on-fix
python3 -m ruff check torch_uncertainty tests --no-fix
python3 -m ruff format torch_uncertainty tests --check

- name: Test with pytest and compute coverage
Expand Down
5 changes: 0 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,3 @@ repos:
language: python
types_or: [python, pyi]
exclude: ^auto_tutorials_source/
# - id: pytest-check
# name: pytest-check
# entry: pytest
# language: system
# pass_filenames: false
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright 2023 Adrien Lafage and Olivier Laurent
Copyright 2023-2024 Adrien Lafage and Olivier Laurent

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
2 changes: 0 additions & 2 deletions auto_tutorials_source/tutorial_bayesian.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

"""
Train a Bayesian Neural Network in Three Minutes
================================================
Expand Down
117 changes: 117 additions & 0 deletions auto_tutorials_source/tutorial_corruptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
"""
Image Corruptions
=================

This tutorial shows the impact of the different corruptions available in the
TorchUncertainty library. These corruptions were first proposed in the paper
Benchmarking Neural Network Robustness to Common Corruptions and Perturbations
by Dan Hendrycks and Thomas Dietterich.

For this tutorial, we will only load the corruption transforms available in
torch_uncertainty.transforms.corruptions. We also need to load utilities from
torchvision and matplotlib.
"""
import torch
from torchvision.datasets import CIFAR10
from torchvision.transforms import Compose, ToTensor, Resize

from torchvision.utils import make_grid
import matplotlib.pyplot as plt
plt.axis('off')
ds = CIFAR10("./data", train=False, download=True)

def get_images(main_transform, severity):
ds_transforms = Compose([ToTensor(), main_transform(severity), Resize(256)])
ds = CIFAR10("./data", train=False, download=False, transform=ds_transforms)
return make_grid([ds[i][0] for i in range(6)]).permute(1, 2, 0)

def show_images(transform):
print("Original Images")
with torch.no_grad():
plt.axis('off')
plt.imshow(get_images(transform, 0))
plt.show()

for severity in range(1, 6):
print(f"Severity {severity}")
with torch.no_grad():
plt.axis('off')
plt.imshow(get_images(transform, severity))
plt.show()

# %%
# 1. Gaussian Noise
# ~~~~~~~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import GaussianNoise

show_images(GaussianNoise)

# %%
# 2. Shot Noise
# ~~~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import ShotNoise

show_images(ShotNoise)

# %%
# 3. Impulse Noise
# ~~~~~~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import ImpulseNoise

show_images(ImpulseNoise)

# %%
# 4. Speckle Noise
# ~~~~~~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import SpeckleNoise

show_images(SpeckleNoise)

# %%
# 5. Gaussian Blur
# ~~~~~~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import GaussianBlur

show_images(GaussianBlur)

# %%
# 6. Glass Blur
# ~~~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import GlassBlur

show_images(GlassBlur)

# %%
# 7. Defocus Blur
# ~~~~~~~~~~~~~~~

from torch_uncertainty.transforms.corruptions import DefocusBlur

show_images(DefocusBlur)

#%%
# 8. JPEG Compression
# ~~~~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import JPEGCompression

show_images(JPEGCompression)

#%%
# 9. Pixelate
# ~~~~~~~~~~~
from torch_uncertainty.transforms.corruptions import Pixelate

show_images(Pixelate)

#%%
# 10. Frost
# ~~~~~~~~
from torch_uncertainty.transforms.corruptions import Frost

show_images(Frost)

# %%
# Reference
# ---------
#
# - **Benchmarking Neural Network Robustness to Common Corruptions and Perturbations**, Dan Hendrycks and Thomas Dietterich. `ICLR 2019 <https://arxiv.org/pdf/1903.12261>`_.
9 changes: 3 additions & 6 deletions auto_tutorials_source/tutorial_der_cubic.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#!/usr/bin/env python
# coding: utf-8

"""
Deep Evidential Regression on a Toy Example
===========================================
Expand Down Expand Up @@ -182,7 +179,7 @@ def optim_regression(
plt.grid()

# %%
# References
# ----------
# Reference
# ---------
#
# - **Deep Evidential Regression:** Alexander Amini, Wilko Schwarting, Ava Soleimany, & Daniela Rus (2022). Deep Evidential Regression. `NeurIPS 2020 <https://arxiv.org/pdf/1910.02600>`_.
# - **Deep Evidential Regression:** Alexander Amini, Wilko Schwarting, Ava Soleimany, & Daniela Rus. `NeurIPS 2020 <https://arxiv.org/pdf/1910.02600>`_.
4 changes: 1 addition & 3 deletions auto_tutorials_source/tutorial_evidential_classification.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#!/usr/bin/env python
# coding: utf-8

"""
Deep Evidential Classification on a Toy Example
===============================================
Expand Down Expand Up @@ -154,6 +151,7 @@ def rotated_mnist(angle: int) -> None:
"""
rotated_images = F.rotate(images, angle)
# print rotated images
plt.axis('off')
imshow(torchvision.utils.make_grid(rotated_images[:4, ...]))
print("Ground truth: ", " ".join(f"{labels[j]}" for j in range(4)))

Expand Down
2 changes: 0 additions & 2 deletions auto_tutorials_source/tutorial_mc_dropout.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

"""
Training a LeNet with Monte-Carlo Dropout
==========================================
Expand Down
2 changes: 0 additions & 2 deletions auto_tutorials_source/tutorial_pe_cifar10.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

"""
From a Vanilla Classifier to a Packed-Ensemble
==============================================
Expand Down
2 changes: 0 additions & 2 deletions auto_tutorials_source/tutorial_scaler.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

"""
Improve Top-label Calibration with Temperature Scaling
======================================================
Expand Down
5 changes: 0 additions & 5 deletions data/README.md

This file was deleted.

17 changes: 17 additions & 0 deletions docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,20 @@ Post-Processing Methods
TemperatureScaler
VectorScaler
MatrixScaler

Datamodules
-----------

.. currentmodule:: torch_uncertainty.datamodules

.. autosummary::
:toctree: generated/
:nosignatures:
:template: class.rst

CIFAR10DataModule
CIFAR100DataModule
MNISTDataModule
TinyImageNetDataModule
ImageNetDataModule
UCIDataModule
2 changes: 2 additions & 0 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
},
}

# Use both the docstrings of the init and the class
autoclass_content = "both"

autosummary_generate = True
napoleon_use_ivar = True
Expand Down
27 changes: 27 additions & 0 deletions docs/source/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,30 @@ Install the package using pip in editable mode:
pip install -e .

If PyTorch is not installed, the latest version will be installed automatically.

Options
-------

You can install the package with the following options:

* dev: includes all the dependencies for the development of the package
including ruff and the pre-commits hooks.
* docs: includes all the dependencies for the documentation of the package
based on sphinx
* image: includes all the dependencies for the image processing module
including opencv and scikit-image
* tabular: includes pandas
* full: includes all the aforementioned dependencies

For example, to install the package with the dependencies for the development
and the documentation, run:

.. parsed-literal::

pip install -e .[dev,docs]

To install the package with all the dependencies, run:

.. parsed-literal::

pip install -e .[full]
9 changes: 9 additions & 0 deletions docs/source/references.rst
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,12 @@ VGG

* Authors: *Karen Simonyan and Andrew Zisserman*
* Paper: `ICLR 2015 <https://arxiv.org/pdf/1409.1556.pdf>`__.

Layers
------

**Filter Response Normalization Layer: Eliminating Batch Dependence in the
Training of Deep Neural Networks**

* Authors: *Saurabh Singh and Shankar Krishnan*
* Paper: `CVPR 2020 <https://arxiv.org/pdf/1911.09737.pdf>`__.
12 changes: 7 additions & 5 deletions experiments/classification/cifar10/resnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
else:
calibration_set = None

results = None
if args.use_cv:
list_dm = dm.make_cross_val_splits(args.n_splits, args.train_over)
list_model = [
Expand Down Expand Up @@ -65,8 +66,9 @@

results = cli_main(model, dm, args.exp_dir, args.exp_name, args)

for dict_result in results:
csv_writer(
Path(args.exp_dir) / Path(args.exp_name) / "results.csv",
dict_result,
)
if results is not None:
for dict_result in results:
csv_writer(
Path(args.exp_dir) / Path(args.exp_name) / "results.csv",
dict_result,
)
2 changes: 1 addition & 1 deletion experiments/classification/cifar10/wideresnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@
**vars(args),
)

cli_main(model, dm, root, args.exp_dir, args.exp_name, args)
cli_main(model, dm, args.exp_dir, args.exp_name, args)
2 changes: 1 addition & 1 deletion experiments/classification/cifar100/resnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@
**vars(args),
)

cli_main(model, dm, root, args.exp_dir, args.exp_name, args)
cli_main(model, dm, args.exp_dir, args.exp_name, args)
Loading