Skip to content

Commit

Permalink
release
Browse files Browse the repository at this point in the history
  • Loading branch information
ISosnovik committed Nov 23, 2021
0 parents commit 9ceb110
Show file tree
Hide file tree
Showing 31 changed files with 2,588 additions and 0 deletions.
134 changes: 134 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

*.pt
!precalculated_basis/*.pt
*.pth
.DS_Store
24 changes: 24 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
MIT License

Copyright (c) 2020-2021 Ivan Sosnovik, Artem Moskalev
Copyright (c) 2020 Ivan Sosnovik, Michał Szmaja
Copyright (c) 2019 Erik J Bekkers
Copyright (c) 2019 xternalz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
71 changes: 71 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
![](./src/logo.jpg)


This is the official implementation of

[DISCO: accurate Discrete Scale Convolutions](https://arxiv.org/abs/2106.02733)<br>
**Ivan Sosnovik, Artem Moskalev, and Arnold Smeulders**<br>
BMVC 2021 (**Oral**)

and

[How to Transform Kernels for Scale-Convolutions](https://openreview.net/forum?id=rTpTF_-fOwm)<br>
**Ivan Sosnovik, Artem Moskalev, and Arnold Smeulders**<br>
ICCV VIPriors 2021


*Scale is often seen as a given, disturbing factor in many vision tasks. When doing so it is one of the factors why we need more data during learning. In recent work scale equivariance was added to convolutional neural networks. We aim for accurate scale-equivariant convolutional neural networks (SE-CNNs). Current SE-CNNs rely on weight sharing and filter rescaling, the latter of which is accurate for integer scales only. To reach accurate scale equivariance, we derive general constraints under which scale-convolution remains equivariant to discrete rescaling. We find the exact solution for all cases where it exists, and compute the approximation for the rest.*

## Scale-Equivariant CNNs
![](./src/scheme.gif)

DISCO is a new class of scale-equivariant convolutional neural networks (SE-CNNs). To learn more about the backbone SE-CNNs we use, check [SESN](https://github.com/ISosnovik/sesn/). To use our models you first need to calculate the DISCO basis. You can do it by simply running
```bash
python calculate_disco_basis.py \
--basis_size 5 \ # actual size of the filters
--basis_effective_size 3 \ # the size of the filter for the conventional CNN
--basis_scales 1.0 1.41 2.0 \ # the scales hyperparameter for convolutional layers
--basis_save_dir precalculated_basis \
--cuda \

```
We provide the bases we have used for our experiments in the `./precalculated_basis` folder.

## Experiments
To reproduce the experiments on Scale-MNIST you first need to generate the datasets. Follow the instructions provided in [SESN](https://github.com/ISosnovik/sesn/). Once the datasets are generated, you can simply run
```
DATASET_SRC=path/to/datasets bash exp_mnist.sh
```
and for the STL-10 experiments, run
```
DATASET_SRC=path/to/datasets bash exp_stl.sh
```
The experiments on OTB-13 are coming soon



## Acknowledgements
The Robert Bosch GmbH is acknowledged for financial support.

## BibTeX
If you found this work useful in your research, please consider citing
```
@article{sosnovik2021disco,
title={DISCO: accurate Discrete Scale Convolutions},
author={Sosnovik, Ivan and Moskalev, Artem and Smeulders, Arnold},
journal={arXiv preprint arXiv:2106.02733},
year={2021}
}
```

and
```
@InProceedings{Sosnovik_2021_ICCV,
author = {Sosnovik, Ivan and Moskalev, Artem and Smeulders, Arnold},
title = {How To Transform Kernels for Scale-Convolutions},
booktitle = {Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV) Workshops},
month = {October},
year = {2021},
pages = {1092-1097}
}
```
143 changes: 143 additions & 0 deletions calculate_disco_basis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
'''
This file is a part of the official implementation of
1) "DISCO: accurate Discrete Scale Convolutions"
by Ivan Sosnovik, Artem Moskalev, Arnold Smeulders, BMVC 2021
arxiv: https://arxiv.org/abs/2106.02733
2) "How to Transform Kernels for Scale-Convolutions"
by Ivan Sosnovik, Artem Moskalev, Arnold Smeulders, ICCV VIPriors 2021
pdf: https://openaccess.thecvf.com/content/ICCV2021W/VIPriors/papers/Sosnovik_How_To_Transform_Kernels_for_Scale-Convolutions_ICCVW_2021_paper.pdf
---------------------------------------------------------------------------
MIT License. Copyright (c) 2021 Ivan Sosnovik, Artem Moskalev
'''

import os
import time
from argparse import ArgumentParser

import torch
import torch.optim as optim
import torch.backends.cudnn as cudnn

from models.basis import ApproximateProxyBasis
from models.basis.disco import get_basis_filename
from utils import loaders
from utils.train_utils import train_equi_loss
from utils.model_utils import get_num_parameters


#########################################
# arguments
#########################################
parser = ArgumentParser()
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--epochs', type=int, default=40)

parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--lr_steps', type=int, nargs='+', default=[20, 30])
parser.add_argument('--lr_gamma', type=float, default=0.1)

parser.add_argument('--cuda', action='store_true', default=False)

# basis hyperparameters
parser.add_argument('--basis_size', type=int, default=7)
parser.add_argument('--basis_effective_size', type=int, default=3)
parser.add_argument('--basis_scales', type=float, nargs='+', default=[1.0])
parser.add_argument('--basis_save_dir', type=str, required=True)


args = parser.parse_args()

print("Args:")
for k, v in vars(args).items():
print(" {}={}".format(k, v))

print(flush=True)


#########################################
# Data
#########################################
loader = loaders.random_loader(args.batch_size)


print('Dataset:')
print(loader.dataset)


#########################################
# Model
#########################################
basis = ApproximateProxyBasis(size=args.basis_size, scales=args.basis_scales,
effective_size=args.basis_effective_size)

print('\nBasis:')
print(basis)
print()

use_cuda = args.cuda and torch.cuda.is_available()
device = torch.device('cuda' if use_cuda else 'cpu')
print('Device: {}'.format(device))

if use_cuda:
cudnn.enabled = True
cudnn.benchmark = True
print('CUDNN is enabled. CUDNN benchmark is enabled')
basis.cuda()

print(flush=True)

#########################################
# optimizer
#########################################
parameters = filter(lambda x: x.requires_grad, basis.parameters())
optimizer = optim.Adam(parameters, lr=args.lr)
print(optimizer)
lr_scheduler = optim.lr_scheduler.MultiStepLR(optimizer, args.lr_steps, args.lr_gamma)


#########################################
# Paths
#########################################


save_basis_postfix = get_basis_filename(size=args.basis_size,
effective_size=args.basis_effective_size,
scales=args.basis_scales)
save_basis_path = os.path.join(args.basis_save_dir, save_basis_postfix)
print('Basis path: ', save_basis_path)
print()

if not os.path.isdir(args.basis_save_dir):
os.makedirs(args.basis_save_dir)

#########################################
# Training
#########################################

print('\nTraining\n' + '-' * 30)
start_time = time.time()
best_loss = float('inf')

for epoch in range(args.epochs):
loss = train_equi_loss(basis, optimizer, loader, device)
print('Epoch {:3d}/{:3d}| Loss: {:.2e}'.format(epoch + 1, args.epochs, loss), flush=True)
if loss < best_loss:
best_loss = loss

with torch.no_grad():
torch.save(basis.get_basis().cpu(), save_basis_path)

lr_scheduler.step()

print('-' * 30)
print('Training is finished')
print('Best Loss: {:.2e}'.format(best_loss), flush=True)
end_time = time.time()
elapsed_time = end_time - start_time
time_per_epoch = elapsed_time / args.epochs

print('Total Time Elapsed: {:.2f}'.format(elapsed_time))
print('Time per Epoch: {:.2f}'.format(time_per_epoch))
Loading

0 comments on commit 9ceb110

Please sign in to comment.