Repository: vdumoulin/conv_arithmetic
Branch: master
Commit: af6f818b0bb3
Files: 14
Total size: 115.1 KB
Directory structure:
gitextract_8umkc94o/
├── .gitignore
├── LICENSE
├── README.md
├── bibliography.bib
├── bin/
│ ├── generate_makefile
│ └── produce_figure
├── conv_arithmetic.tex
├── gif/
│ └── .gitignore
├── natbib/
│ └── natbib.bst
├── pdf/
│ └── .gitignore
├── png/
│ └── .gitignore
└── templates/
├── arithmetic_figure.txt
├── numerical_figure.txt
└── unit.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
## Makefile
Makefile
## Core latex/pdflatex auxiliary files:
*.aux
*.lof
*.log
*.lot
*.fls
*.out
*.toc
*.fmt
## Intermediate documents:
*.dvi
*-converted-to.*
# these rules might exclude image files for figures etc.
# *.ps
# *.eps
*.pdf
## Bibliography auxiliary files (bibtex/biblatex/biber):
*.bbl
*.bcf
*.blg
*-blx.aux
*-blx.bib
*.brf
*.run.xml
## Build tool auxiliary files:
*.fdb_latexmk
*.synctex
*.synctex.gz
*.synctex.gz(busy)
*.pdfsync
## Auxiliary and intermediate files from other packages:
# algorithms
*.alg
*.loa
# achemso
acs-*.bib
# amsthm
*.thm
# beamer
*.nav
*.snm
*.vrb
# cprotect
*.cpt
#(e)ledmac/(e)ledpar
*.end
*.[1-9]
*.[1-9][0-9]
*.[1-9][0-9][0-9]
*.[1-9]R
*.[1-9][0-9]R
*.[1-9][0-9][0-9]R
*.eledsec[1-9]
*.eledsec[1-9]R
*.eledsec[1-9][0-9]
*.eledsec[1-9][0-9]R
*.eledsec[1-9][0-9][0-9]
*.eledsec[1-9][0-9][0-9]R
# glossaries
*.acn
*.acr
*.glg
*.glo
*.gls
# gnuplottex
*-gnuplottex-*
# hyperref
*.brf
# knitr
*-concordance.tex
*.tikz
*-tikzDictionary
# listings
*.lol
# makeidx
*.idx
*.ilg
*.ind
*.ist
# minitoc
*.maf
*.mtc
*.mtc[0-9]
*.mtc[1-9][0-9]
# minted
_minted*
*.pyg
# morewrites
*.mw
# mylatexformat
*.fmt
# nomencl
*.nlo
# sagetex
*.sagetex.sage
*.sagetex.py
*.sagetex.scmd
# sympy
*.sout
*.sympy
sympy-plots-for-*.tex/
# pdfcomment
*.upa
*.upb
#pythontex
*.pytxcode
pythontex-files-*/
# Texpad
.texpadtmp
# TikZ & PGF
*.dpth
*.md5
*.auxlock
# todonotes
*.tdo
# xindy
*.xdy
# xypic precompiled matrices
*.xyc
# WinEdt
*.bak
*.sav
# endfloat
*.ttt
*.fff
# Latexian
TSWLatexianTemp*
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2016
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.
================================================
FILE: README.md
================================================
# Convolution arithmetic
A technical report on convolution arithmetic in the context of deep learning.
The code and the images of this tutorial are free to use as regulated by the
licence and subject to proper attribution:
* \[1\] Vincent Dumoulin, Francesco Visin - [A guide to convolution arithmetic
for deep learning](https://arxiv.org/abs/1603.07285)
([BibTeX](https://gist.github.com/fvisin/165ca9935392fa9600a6c94664a01214))
## Convolution animations
_N.B.: Blue maps are inputs, and cyan maps are outputs._
 |
 |
 |
 |
| No padding, no strides |
Arbitrary padding, no strides |
Half padding, no strides |
Full padding, no strides |
 |
 |
 |
|
| No padding, strides |
Padding, strides |
Padding, strides (odd) |
|
## Transposed convolution animations
_N.B.: Blue maps are inputs, and cyan maps are outputs._
 |
 |
 |
 |
| No padding, no strides, transposed |
Arbitrary padding, no strides, transposed |
Half padding, no strides, transposed |
Full padding, no strides, transposed |
 |
 |
 |
|
| No padding, strides, transposed |
Padding, strides, transposed |
Padding, strides, transposed (odd) |
|
## Dilated convolution animations
_N.B.: Blue maps are inputs, and cyan maps are outputs._
 |
| No padding, no stride, dilation |
## Generating the Makefile
From the repository's root directory:
``` bash
$ ./bin/generate_makefile
```
## Generating the animations
From the repository's root directory:
``` bash
$ make all_animations
```
The animations will be output to the `gif` directory. Individual animation steps
will be output in PDF format to the `pdf` directory and in PNG format to the
`png` directory.
## Compiling the document
From the repository's root directory:
``` bash
$ make
```
================================================
FILE: bibliography.bib
================================================
@inproceedings{le1997reading,
title={Reading checks with multilayer graph transformer networks},
author={Le Cun, Yann and Bottou, L{\'e}on and Bengio, Yoshua},
booktitle={Acoustics, Speech, and Signal Processing, 1997. ICASSP-97., 1997 IEEE International Conference on},
volume={1},
pages={151--154},
year={1997},
organization={IEEE}
}
@inproceedings{bergstra2010theano,
title={Theano: A CPU and GPU math compiler in Python},
author={Bergstra, James and Breuleux, Olivier and Bastien, Fr{\'e}d{\'e}ric and Lamblin, Pascal and Pascanu, Razvan and Desjardins, Guillaume and Turian, Joseph and Warde-Farley, David and Bengio, Yoshua},
booktitle={Proc. 9th Python in Science Conf},
pages={1--7},
year={2010}
}
@inproceedings{collobert2011torch7,
title={Torch7: A matlab-like environment for machine learning},
author={Collobert, Ronan and Kavukcuoglu, Koray and Farabet, Cl{\'e}ment},
booktitle={BigLearn, NIPS Workshop},
number={EPFL-CONF-192376},
year={2011}
}
@inproceedings{zeiler2011adaptive,
title={Adaptive deconvolutional networks for mid and high level feature learning},
author={Zeiler, Matthew D and Taylor, Graham W and Fergus, Rob},
booktitle={Computer Vision (ICCV), 2011 IEEE International Conference on},
pages={2018--2025},
year={2011},
organization={IEEE}
}
@inproceedings{krizhevsky2012imagenet,
title={Imagenet classification with deep convolutional neural networks},
author={Krizhevsky, Alex and Sutskever, Ilya and Hinton, Geoffrey E},
booktitle={Advances in neural information processing systems},
pages={1097--1105},
year={2012}
}
@article{bastien2012theano,
title={Theano: new features and speed improvements},
author={Bastien, Fr{\'e}d{\'e}ric and Lamblin, Pascal and Pascanu, Razvan and Bergstra, James and Goodfellow, Ian and Bergeron, Arnaud and Bouchard, Nicolas and Warde-Farley, David and Bengio, Yoshua},
journal={arXiv preprint arXiv:1211.5590},
year={2012}
}
@inproceedings{jia2014caffe,
title={Caffe: Convolutional architecture for fast feature embedding},
author={Jia, Yangqing and Shelhamer, Evan and Donahue, Jeff and Karayev, Sergey and Long, Jonathan and Girshick, Ross and Guadarrama, Sergio and Darrell, Trevor},
booktitle={Proceedings of the ACM International Conference on Multimedia},
pages={675--678},
year={2014},
organization={ACM}
}
@incollection{zeiler2014visualizing,
title={Visualizing and understanding convolutional networks},
author={Zeiler, Matthew D and Fergus, Rob},
booktitle={Computer vision--ECCV 2014},
pages={818--833},
year={2014},
publisher={Springer}
}
@article{chen2014semantic,
title={Semantic image segmentation with deep convolutional nets and fully connected crfs},
author={Chen, Liang-Chieh and Papandreou, George and Kokkinos, Iasonas and Murphy, Kevin and Yuille, Alan L},
journal={arXiv preprint arXiv:1412.7062},
year={2014}
}
@article{abaditensorflow,
title={TensorFlow: Large-scale machine learning on heterogeneous systems},
author={Abadi, Mart{\i}n and Agarwal, Ashish and Barham, Paul and Brevdo, Eugene and Chen, Zhifeng and Citro, Craig and Corrado, Greg S and Davis, Andy and Dean, Jeffrey and Devin, Matthieu and others},
journal={Software available from tensorflow.org},
year={2015}
}
@inproceedings{long2015fully,
title={Fully convolutional networks for semantic segmentation},
author={Long, Jonathan and Shelhamer, Evan and Darrell, Trevor},
booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
pages={3431--3440},
year={2015}
}
@article{radford2015unsupervised,
title={Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks},
author={Radford, Alec and Metz, Luke and Chintala, Soumith},
journal={arXiv preprint arXiv:1511.06434},
year={2015}
}
@unpublished{Goodfellow-et-al-2016-Book,
title={Deep Learning},
author={Goodfellow, Ian and Bengio, Yoshua and Courville, Aaron},
note={Book in preparation for MIT Press},
url={http://goodfeli.github.io/dlbook/},
year={2016}
}
@article{im2016generating,
title={Generating images with recurrent adversarial networks},
author={Im, Daniel Jiwoong and Kim, Chris Dongjoo and Jiang, Hui and Memisevic, Roland},
journal={arXiv preprint arXiv:1602.05110},
year={2016}
}
@article{visin15,
author = {Francesco Visin and
Kyle Kastner and
Aaron C. Courville and
Yoshua Bengio and
Matteo Matteucci and
KyungHyun Cho},
title = {ReSeg: {A} Recurrent Neural Network for Object Segmentation},
year = {2015},
url = {http://arxiv.org/abs/1511.07053},
}
@article{yu2015multi,
title={Multi-scale context aggregation by dilated convolutions},
author={Yu, Fisher and Koltun, Vladlen},
journal={arXiv preprint arXiv:1511.07122},
year={2015}
}
@inproceedings {boureau-cvpr-10,
title = "Learning Mid-Level Features for Recognition",
author = "Boureau, {Y-Lan} and Bach, Francis and LeCun, Yann and Ponce, Jean",
booktitle = "Proc. International Conference on Computer Vision and Pattern Recognition (CVPR'10)",
publisher = "IEEE",
year = "2010"
}
@inproceedings {boureau-icml-10,
title = "A theoretical analysis of feature pooling in vision algorithms",
author = "Boureau, {Y-Lan} and Ponce, Jean and LeCun, Yann",
booktitle = "Proc. International Conference on Machine learning (ICML'10)",
year = "2010"
}
@inproceedings {boureau-iccv-11,
title = "Ask the locals: multi-way local pooling for image recognition",
author = "Boureau, {Y-Lan} and {Le Roux}, Nicolas and Bach, Francis and Ponce, Jean and LeCun, Yann",
booktitle = "Proc. International Conference on Computer Vision (ICCV'11)",
publisher = "IEEE",
year = "2011"
}
@InProceedings{ICML2011Saxe_551,
author = {Andrew Saxe and Pang Wei Koh and Zhenghao Chen and Maneesh Bhand and Bipin Suresh and Andrew Ng},
title = {On Random Weights and Unsupervised Feature Learning },
booktitle = {Proceedings of the 28th International Conference on Machine Learning (ICML-11)},
series = {ICML '11},
year = {2011},
editor = {Lise Getoor and Tobias Scheffer},
location = {Bellevue, Washington, USA},
isbn = {978-1-4503-0619-5},
month = {June},
publisher = {ACM},
address = {New York, NY, USA},
pages= {1089--1096},
}
@article{oord2016wavenet,
title={Wavenet: A generative model for raw audio},
author={Oord, Aaron van den and Dieleman, Sander and Zen, Heiga and Simonyan,
Karen and Vinyals, Oriol and Graves, Alex and Kalchbrenner, Nal and
Senior, Andrew and Kavukcuoglu, Koray},
journal={arXiv preprint arXiv:1609.03499},
year={2016}
}
================================================
FILE: bin/generate_makefile
================================================
#!/usr/bin/env python
from six import iteritems
from six.moves import range
arithmetic_files = ('bin/produce_figure templates/arithmetic_figure.txt '
'templates/unit.txt')
numerical_files = 'bin/produce_figure templates/numerical_figure.txt'
animations = (
('no_padding_no_strides',
('arithmetic', 4, 2, 0, 3, 1, 1, 'convolution', False)),
('no_padding_no_strides_transposed',
('arithmetic', 4, 2, 0, 3, 1, 1, 'convolution', True)),
('arbitrary_padding_no_strides',
('arithmetic', 5, 6, 2, 4, 1, 1, 'convolution', False)),
('arbitrary_padding_no_strides_transposed',
('arithmetic', 5, 6, 2, 4, 1, 1, 'convolution', True)),
('same_padding_no_strides',
('arithmetic', 5, 5, 1, 3, 1, 1, 'convolution', False)),
('same_padding_no_strides_transposed',
('arithmetic', 5, 5, 1, 3, 1, 1, 'convolution', True)),
('full_padding_no_strides',
('arithmetic', 5, 7, 2, 3, 1, 1, 'convolution', False)),
('full_padding_no_strides_transposed',
('arithmetic', 5, 7, 2, 3, 1, 1, 'convolution', True)),
('no_padding_strides',
('arithmetic', 5, 2, 0, 3, 2, 1, 'convolution', False)),
('no_padding_strides_transposed',
('arithmetic', 5, 2, 0, 3, 2, 1, 'convolution', True)),
('padding_strides',
('arithmetic', 5, 3, 1, 3, 2, 1, 'convolution', False)),
('padding_strides_transposed',
('arithmetic', 5, 3, 1, 3, 2, 1, 'convolution', True)),
('padding_strides_odd',
('arithmetic', 6, 3, 1, 3, 2, 1, 'convolution', False)),
('padding_strides_odd_transposed',
('arithmetic', 6, 3, 1, 3, 2, 1, 'convolution', True)),
('dilation',
('arithmetic', 7, 3, 0, 3, 1, 2, 'convolution', False)),
('numerical_no_padding_no_strides',
('numerical', 5, 3, 0, 3, 1, 1, 'convolution', False)),
('numerical_padding_strides',
('numerical', 5, 3, 1, 3, 2, 1, 'convolution', False)),
('numerical_average_pooling',
('numerical', 5, 3, 0, 3, 1, 1, 'average', False)),
('numerical_max_pooling',
('numerical', 5, 3, 0, 3, 1, 1, 'max', False)),
)
fields = ('type', 'input-size', 'output-size', 'padding', 'kernel-size',
'stride', 'dilation', 'mode', 'transposed')
animations = dict([(name, dict(zip(fields, config)))
for name, config in animations])
def make_header():
return ('.PHONY : all_animations\nall_animations : {}\n\n'.format(
' '.join(['gif/{}.gif'.format(name)
for name in animations.keys()])) +
'.SECONDARY : \n')
def make_report_section():
return ('conv_arithmetic.pdf : export BSTINPUTS=$BSTINPUTS:./natbib\n'
'conv_arithmetic.pdf : conv_arithmetic.tex\n'
'\tpdflatex conv_arithmetic\n'
'\tpdflatex conv_arithmetic\n'
'\tbibtex conv_arithmetic\n'
'\tpdflatex conv_arithmetic\n'
'\tpdflatex conv_arithmetic\n\n'
'.PHONY : clean\n'
'clean : \n'
'\trm -f conv_arithmetic.{aux,bbl,blg,log}\n')
def make_gif_section():
rules = []
for name, config in iteritems(animations):
if config['transposed']:
steps = config['input-size'] ** 2
else:
steps = config['output-size'] ** 2
rules.append(
'gif/{}.gif : '.format(name) +
' '.join(['png/{}_{:02d}.png'.format(name, i)
for i in range(steps)]) + '\n' +
'\tconvert -delay 100 -loop 0 -layers Optimize +map -dispose previous $^ $@\n' +
'\tgifsicle --batch -O3 $@\n')
return '\n'.join(rules)
def make_png_section():
return ('png/%.png : pdf/%.pdf\n'
'\tconvert -density 600 $< -flatten -resize 25% $@\n')
def make_pdf_section():
rules = []
for name, config in iteritems(animations):
if config['transposed']:
steps = config['input-size'] ** 2
else:
steps = config['output-size'] ** 2
if config['type'] == 'arithmetic':
dependencies = arithmetic_files
else:
dependencies = numerical_files
subrules = []
for i in range(steps):
subrules.append(
'pdf/{}_{:02d}.pdf : {}\n'.format(name, i, dependencies) +
'\t./bin/produce_figure ' +
'{} {} {} '.format(config['type'], name, i) +
'--input-size={} '.format(config['input-size']) +
'--output-size={} '.format(config['output-size']) +
'--padding={} '.format(config['padding']) +
'--kernel-size={} '.format(config['kernel-size']) +
'--stride={} '.format(config['stride']) +
('--dilation={} '.format(config['dilation'])
if config['dilation'] != 1 else '' ) +
('--mode={} '.format(config['mode'])
if config['type'] == 'numerical' else '') +
('--transposed\n' if config['transposed'] else '\n'))
rules.append('\n'.join(subrules))
return '\n'.join(rules)
def main():
with open('Makefile', 'w') as makefile:
makefile.write('\n'.join([make_report_section(), make_header(),
make_gif_section(), make_png_section(),
make_pdf_section()]))
if __name__ == "__main__":
main()
================================================
FILE: bin/produce_figure
================================================
#!/usr/bin/env python
import argparse
import itertools
import os
import subprocess
from glob import glob
import numpy
import six
numpy.random.seed(1234)
def make_numerical_tex_string(step, input_size, output_size, padding,
kernel_size, stride, dilation, mode):
"""Creates a LaTeX string for a numerical convolution animation.
Parameters
----------
step : int
Which step of the animation to generate the LaTeX string for.
input_size : int
Convolution input size.
output_size : int
Convolution output size.
padding : int
Zero padding.
kernel_size : int
Convolution kernel size.
stride : int
Convolution stride.
mode : str
Kernel mode, one of {'convolution', 'average', 'max'}.
Returns
-------
tex_string : str
A string to be compiled by LaTeX to produce one step of the
animation.
"""
if mode not in ('convolution', 'average', 'max'):
raise ValueError("wrong convolution mode, choices are 'convolution', "
"'average' or 'max'")
if dilation != 1:
raise ValueError("Only a dilation of 1 is currently supported for numerical output")
max_steps = output_size ** 2
if step >= max_steps:
raise ValueError('step {} out of bounds (there are '.format(step) +
'{} steps for this animation'.format(max_steps))
with open(os.path.join('templates', 'numerical_figure.txt'), 'r') as f:
tex_template = f.read()
total_input_size = input_size + 2 * padding
input_ = numpy.zeros((total_input_size, total_input_size), dtype='int32')
input_[padding: padding + input_size,
padding: padding + input_size] = numpy.random.randint(
low=0, high=4, size=(input_size, input_size))
kernel = numpy.random.randint(
low=0, high=3, size=(kernel_size, kernel_size))
output = numpy.empty((output_size, output_size), dtype='float32')
for offset_x, offset_y in itertools.product(range(output_size),
range(output_size)):
if mode == 'convolution':
output[offset_x, offset_y] = (
input_[stride * offset_x: stride * offset_x + kernel_size,
stride * offset_y: stride * offset_y + kernel_size] * kernel).sum()
elif mode == 'average':
output[offset_x, offset_y] = (
input_[stride * offset_x: stride * offset_x + kernel_size,
stride * offset_y: stride * offset_y + kernel_size]).mean()
else:
output[offset_x, offset_y] = (
input_[stride * offset_x: stride * offset_x + kernel_size,
stride * offset_y: stride * offset_y + kernel_size]).max()
offsets = list(itertools.product(range(output_size - 1, -1, -1),
range(output_size)))
offset_y, offset_x = offsets[step]
if mode == 'convolution':
kernel_values_string = ''.join(
"\\node (node) at ({0},{1}) {{\\tiny {2}}};\n".format(
i + 0.8 + stride * offset_x, j + 0.2 + stride * offset_y,
kernel[kernel_size - 1 - j, i])
for i, j in itertools.product(range(kernel_size),
range(kernel_size)))
else:
kernel_values_string = '\n'
return six.b(tex_template.format(**{
'PADDING_TO': '{0},{0}'.format(total_input_size),
'INPUT_FROM': '{0},{0}'.format(padding),
'INPUT_TO': '{0},{0}'.format(padding + input_size),
'INPUT_VALUES': ''.join(
"\\node (node) at ({0},{1}) {{\\footnotesize {2}}};\n".format(
i + 0.5, j + 0.5, input_[total_input_size - 1 - j, i])
for i, j in itertools.product(range(total_input_size),
range(total_input_size))),
'INPUT_GRID_FROM': '{},{}'.format(stride * offset_x,
stride * offset_y),
'INPUT_GRID_TO': '{},{}'.format(stride * offset_x + kernel_size,
stride * offset_y + kernel_size),
'KERNEL_VALUES': kernel_values_string,
'OUTPUT_TO': '{0},{0}'.format(output_size),
'OUTPUT_GRID_FROM': '{},{}'.format(offset_x, offset_y),
'OUTPUT_GRID_TO': '{},{}'.format(offset_x + 1, offset_y + 1),
'OUTPUT_VALUES': ''.join(
"\\node (node) at ({0},{1}) {{\\tiny {2:.1f}}};\n".format(
i + 0.5, j + 0.5, output[output_size - 1 - j, i])
for i, j in itertools.product(range(output_size),
range(output_size))),
'XSHIFT': '{}cm'.format(total_input_size + 1),
'YSHIFT': '{}cm'.format((total_input_size - output_size) // 2),
}))
def make_arithmetic_tex_string(step, input_size, output_size, padding,
kernel_size, stride, dilation, transposed):
"""Creates a LaTeX string for a convolution arithmetic animation.
Parameters
----------
step : int
Which step of the animation to generate the LaTeX string for.
input_size : int
Convolution input size.
output_size : int
Convolution output size.
padding : int
Zero padding.
kernel_size : int
Convolution kernel size.
stride : int
Convolution stride.
dilation: int
Input Dilation
transposed : bool
If ``True``, generate strings for the transposed convolution
animation.
Returns
-------
tex_string : str
A string to be compiled by LaTeX to produce one step of the
animation.
"""
kernel_size = (kernel_size - 1)*dilation + 1
if transposed:
# Used to add bottom-padding to account for odd shapes
bottom_pad = (input_size + 2 * padding - kernel_size) % stride
input_size, output_size, padding, spacing, stride = (
output_size, input_size, kernel_size - 1 - padding, stride, 1)
total_input_size = output_size + kernel_size - 1
y_adjustment = 0
else:
# Not used in convolutions
bottom_pad = 0
spacing = 1
total_input_size = input_size + 2 * padding
y_adjustment = (total_input_size - (kernel_size - stride)) % stride
max_steps = output_size ** 2
if step >= max_steps:
raise ValueError('step {} out of bounds (there are '.format(step) +
'{} steps for this animation'.format(max_steps))
with open(os.path.join('templates', 'arithmetic_figure.txt'), 'r') as f:
tex_template = f.read()
with open(os.path.join('templates', 'unit.txt'), 'r') as f:
unit_template = f.read()
offsets = list(itertools.product(range(output_size - 1, -1, -1),
range(output_size)))
offset_y, offset_x = offsets[step]
return six.b(tex_template.format(**{
'PADDING_TO': '{0},{0}'.format(total_input_size),
'INPUT_UNITS': ''.join(
unit_template.format(padding + spacing * i,
bottom_pad + padding + spacing * j,
padding + spacing * i + 1,
bottom_pad + padding + spacing * j + 1)
for i, j in itertools.product(range(input_size),
range(input_size))),
'INPUT_GRID_FROM_X': '{}'.format(
stride * offset_x),
'INPUT_GRID_FROM_Y': '{}'.format(
y_adjustment + stride * offset_y),
'INPUT_GRID_TO_X': '{}'.format(
stride * offset_x + kernel_size),
'INPUT_GRID_TO_Y': '{}'.format(
y_adjustment + stride * offset_y + kernel_size),
'DILATION': '{}'.format(dilation),
'OUTPUT_BOTTOM_LEFT': '{},{}'.format(offset_x, offset_y),
'OUTPUT_BOTTOM_RIGHT': '{},{}'.format(offset_x + 1, offset_y),
'OUTPUT_TOP_LEFT': '{},{}'.format(offset_x, offset_y + 1),
'OUTPUT_TOP_RIGHT': '{},{}'.format(offset_x + 1, offset_y + 1),
'OUTPUT_TO': '{0},{0}'.format(output_size),
'OUTPUT_GRID_FROM': '{},{}'.format(offset_x, offset_y),
'OUTPUT_GRID_TO': '{},{}'.format(offset_x + 1, offset_y + 1),
'OUTPUT_ELEVATION': '{}cm'.format(total_input_size + 1),
}))
def compile_figure(which_, name, step, **kwargs):
if which_ == 'arithmetic':
tex_string = make_arithmetic_tex_string(step, **kwargs)
else:
tex_string = make_numerical_tex_string(step, **kwargs)
jobname = '{}_{:02d}'.format(name, step)
p = subprocess.Popen(['pdflatex', '-jobname={}'.format(jobname),
'-output-directory', 'pdf'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdoutdata, stderrdata = p.communicate(input=tex_string)
# Remove logs and aux if compilation was successfull
if '! LaTeX Error' in stdoutdata or '! Emergency stop' in stdoutdata:
print('! LaTeX Error: check the log file in pdf/{}.log'.format(jobname))
else:
subprocess.call(['rm'] + glob('pdf/{}.aux'.format(jobname)) +
glob('pdf/{}.log'.format(jobname)))
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Compile a LaTeX figure as part of a convolution "
"animation.")
subparsers = parser.add_subparsers()
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("name", type=str, help="name for the animation")
parent_parser.add_argument("step", type=int, help="animation step")
parent_parser.add_argument("-i", "--input-size", type=int, default=5,
help="input size")
parent_parser.add_argument("-o", "--output-size", type=int, default=3,
help="output size")
parent_parser.add_argument("-p", "--padding", type=int, default=0,
help="zero padding")
parent_parser.add_argument("-k", "--kernel-size", type=int, default=3,
help="kernel size")
parent_parser.add_argument("-s", "--stride", type=int, default=1,
help="stride")
parent_parser.add_argument("-d", "--dilation", type=int, default=1,
help="dilation")
subparser = subparsers.add_parser('arithmetic', parents=[parent_parser],
help='convolution arithmetic animation')
subparser.add_argument("--transposed", action="store_true",
help="animate a transposed convolution")
subparser.set_defaults(which_='arithmetic')
subparser = subparsers.add_parser('numerical', parents=[parent_parser],
help='numerical convolution animation')
subparser.add_argument("-m", "--mode", type=str, default='convolution',
choices=('convolution', 'average', 'max'),
help="kernel mode")
subparser.set_defaults(which_='numerical')
args = parser.parse_args()
args_dict = vars(args)
which_ = args_dict.pop('which_')
name = args_dict.pop('name')
step = args_dict.pop('step')
compile_figure(which_, name, step, **args_dict)
================================================
FILE: conv_arithmetic.tex
================================================
\documentclass[notitlepage]{report}
\usepackage{amsmath,amsfonts,amsthm,amssymb}
\usepackage{authblk}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage[utf8]{inputenc}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{natbib}
\usepackage{subcaption}
\usepackage{tikz}
\usepackage{xcolor}
\usepackage{epigraph}
\usepackage{float}
\usepackage{hyperref}
\definecolor{blue}{RGB}{38,139,210}
\definecolor{cyan}{RGB}{42,161,152}
\definecolor{violet}{RGB}{108,113,196}
\definecolor{red}{RGB}{220,50,47}
\definecolor{base01}{RGB}{88,110,117}
\definecolor{base02}{RGB}{7,54,66}
\definecolor{base03}{RGB}{0,43,54}
\usetikzlibrary{calc,shapes,positioning}
\newcommand{\todo}[1]{\textcolor{red}{TODO: #1}}
\newtheorem{relationship}{Relationship}
\providecommand*{\relationshipautorefname}{Relationship}
\surroundwithmdframed[
topline=false,
bottomline=false,
middlelinewidth=0.5pt,
linecolor=base01,
roundcorner=5pt,
innertopmargin=0pt,
leftmargin=15pt,
rightmargin=15pt,
nobreak=true,
]{relationship}
\setcounter{MaxMatrixCols}{16}
\let\originalepigraph\epigraph
\renewcommand\epigraph[2]{\originalepigraph{\textit{#1}}{\textsc{#2}}}
% Use arabic numbers for thanks
\makeatletter
\let\@fnsymbol\@arabic
\makeatother
\title{A guide to convolution arithmetic for deep learning}
\author[$\bigstar$]{Vincent Dumoulin\thanks{dumouliv@iro.umontreal.ca}}
\author[$\bigstar\dagger$]{Francesco Visin\thanks{francesco.visin@polimi.it}}
\affil[$\bigstar$]{MILA, Universit\'{e} de Montr\'{e}al}
\affil[$\dagger$]{AIRLab, Politecnico di Milano}
\date{\today}
\begin{document}
\maketitle
\thispagestyle{empty}
\clearpage
\setlength{\epigraphwidth}{0.4\textwidth}
\epigraph{All models are wrong, but some are useful.}{George E. P. Box}
\clearpage
\renewcommand{\abstractname}{Acknowledgements}
\begin{abstract}
The authors of this guide would like to thank David Warde-Farley, Guillaume
Alain and Caglar Gulcehre for their valuable feedback. We are likewise
grateful to all those who helped improve this tutorial with helpful
comments, constructive criticisms and code contributions. Keep them coming!
Special thanks to Ethan Schoonover, creator of the Solarized color
scheme,\footnote{\url{http://ethanschoonover.com/solarized}} whose colors
were used for the figures.
\end{abstract}
\renewcommand{\abstractname}{Feedback}
\begin{abstract}
Your feedback is welcomed! We did our best to be as precise, informative and
up to the point as possible, but should there be anything you feel might be
an error or could be rephrased to be more precise or comprehensible, please
don't refrain from contacting us. Likewise, drop us a line if you think
there is something that might fit this technical report and you would like
us to discuss -- we will make our best effort to update this document.
\end{abstract}
\renewcommand{\abstractname}{Source code and animations}
\begin{abstract}
The code used to generate this guide along with its figures is available on
GitHub.\footnote{\url{https://github.com/vdumoulin/conv_arithmetic}} There
the reader can also find an animated version of the figures.
\end{abstract}
\tableofcontents
\chapter{Introduction}
Deep convolutional neural networks (CNNs) have been at the heart of spectacular
advances in deep learning. Although CNNs have been used as early as the nineties
to solve character recognition tasks \citep{le1997reading}, their current
widespread application is due to much more recent work, when a deep CNN was used
to beat state-of-the-art in the ImageNet image classification challenge
\citep{krizhevsky2012imagenet}.
Convolutional neural networks therefore constitute a very useful tool for
machine learning practitioners. However, learning to use CNNs for the first time
is generally an intimidating experience. A convolutional layer's output shape is
affected by the shape of its input as well as the choice of kernel shape, zero
padding and strides, and the relationship between these properties is not
trivial to infer. This contrasts with fully-connected layers, whose output size
is independent of the input size. Additionally, CNNs also usually feature a {\em
pooling\/} stage, adding yet another level of complexity with respect to
fully-connected networks. Finally, so-called transposed convolutional layers
(also known as fractionally strided convolutional layers) have been employed in
more and more work as of late \citep{zeiler2011adaptive,zeiler2014visualizing,
long2015fully,radford2015unsupervised,visin15,im2016generating}, and their
relationship with convolutional layers has been explained with various degrees
of clarity.
This guide's objective is twofold:
\begin{enumerate}
\item Explain the relationship between convolutional layers and transposed
convolutional layers.
\item Provide an intuitive understanding of the relationship between input
shape, kernel shape, zero padding, strides and output shape in
convolutional, pooling and transposed convolutional layers.
\end{enumerate}
In order to remain broadly applicable, the results shown in this guide are
independent of implementation details and apply to all commonly used machine
learning frameworks, such as Theano
\citep{bergstra2010theano,bastien2012theano}, Torch \citep{collobert2011torch7},
Tensorflow \citep{abaditensorflow} and Caffe \citep{jia2014caffe}.
This chapter briefly reviews the main building blocks of CNNs, namely discrete
convolutions and pooling. For an in-depth treatment of the subject, see Chapter
9 of the Deep Learning textbook \citep{Goodfellow-et-al-2016-Book}.
\section{Discrete convolutions}
The bread and butter of neural networks is \emph{affine transformations}: a
vector is received as input and is multiplied with a matrix to produce an
output (to which a bias vector is usually added before passing the result
through a nonlinearity). This is applicable to any type of input, be it an
image, a sound clip or an unordered collection of features: whatever their
dimensionality, their representation can always be flattened into a vector
before the transformation.
Images, sound clips and many other similar kinds of data have an intrinsic
structure. More formally, they share these important properties:
\begin{itemize}
\item They are stored as multi-dimensional arrays.
\item They feature one or more axes for which ordering matters (e.g., width
and height axes for an image, time axis for a sound clip).
\item One axis, called the channel axis, is used to access different views
of the data (e.g., the red, green and blue channels of a color image, or
the left and right channels of a stereo audio track).
\end{itemize}
These properties are not exploited when an affine transformation is applied; in
fact, all the axes are treated in the same way and the topological information
is not taken into account. Still, taking advantage of the implicit structure of
the data may prove very handy in solving some tasks, like computer vision and
speech recognition, and in these cases it would be best to preserve it. This is
where discrete convolutions come into play.
A discrete convolution is a linear transformation that preserves this notion of
ordering. It is sparse (only a few input units contribute to a given output
unit) and reuses parameters (the same weights are applied to multiple locations
in the input).
\autoref{fig:numerical_no_padding_no_strides} provides an example of a discrete
convolution. The light blue grid is called the {\em input feature map}. To keep
the drawing simple, a single input feature map is represented, but it is not
uncommon to have multiple feature maps stacked one onto another.\footnote{%
An example of this is what was referred to earlier as {\em channels\/} for
images and sound clips.}
A {\em kernel\/} (shaded area) of value
\begin{figure}[H]
\centering
\begin{tikzpicture}[scale=.4,every node/.style={minimum size=1cm}, on grid]
\draw[fill=base02,opacity=0.4] (0,0) rectangle (3,3);
\draw[draw=base03,thick] (0,0) grid (3,3);
\node (00) at (0.5,2.5) {\tiny 0};
\node (01) at (1.5,2.5) {\tiny 1};
\node (02) at (2.5,2.5) {\tiny 2};
\node (10) at (0.5,1.5) {\tiny 2};
\node (11) at (1.5,1.5) {\tiny 2};
\node (12) at (2.5,1.5) {\tiny 0};
\node (20) at (0.5,0.5) {\tiny 0};
\node (21) at (1.5,0.5) {\tiny 1};
\node (22) at (2.5,0.5) {\tiny 2};
\end{tikzpicture}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_00.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_01.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_02.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_03.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_04.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_05.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_06.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_07.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_no_padding_no_strides_08.pdf}
\caption{\label{fig:numerical_no_padding_no_strides} Computing the output
values of a discrete convolution.}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_00.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_01.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_02.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_03.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_04.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_05.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_06.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_07.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_padding_strides_08.pdf}
\caption{\label{fig:numerical_padding_strides} Computing the output values
of a discrete convolution for $N = 2$, $i_1 = i_2 = 5$, $k_1 = k_2 = 3$,
$s_1 = s_2 = 2$, and $p_1 = p_2 = 1$.}
\end{figure}
\noindent slides across the input feature map. At each location, the product
between each element of the kernel and the input element it overlaps is computed
and the results are summed up to obtain the output in the current location. The
procedure can be repeated using different kernels to form as many output feature
maps as desired (\autoref{fig:full_picture}). The final outputs of this procedure
are called {\em output feature maps}.\footnote{%
While there is a distinction between convolution and cross-correlation from
a signal processing perspective, the two become interchangeable when the
kernel is learned. For the sake of simplicity and to stay consistent with
most of the machine learning literature, the term {\em convolution\/}
will be used in this guide.}
If there are multiple input feature maps, the kernel will have to be
3-dimensional -- or, equivalently each one of the feature maps will be
convolved with a distinct kernel -- and the resulting feature maps will
be summed up elementwise to produce the output feature map.
The convolution depicted in \autoref{fig:numerical_no_padding_no_strides} is an
instance of a 2-D convolution, but it can be generalized to N-D convolutions.
For instance, in a 3-D convolution, the kernel would be a {\em cuboid\/} and
would slide across the height, width and depth of the input feature map.
The collection of kernels defining a discrete convolution has a shape
corresponding to some permutation of $(n, m, k_1, \ldots, k_N)$, where
\begin{equation*}
\begin{split}
n &\equiv \text{number of output feature maps},\\
m &\equiv \text{number of input feature maps},\\
k_j &\equiv \text{kernel size along axis $j$}.
\end{split}
\end{equation*}
The following properties affect the output size $o_j$ of a convolutional layer
along axis $j$:
\begin{itemize}
\item $i_j$: input size along axis $j$,
\item $k_j$: kernel size along axis $j$,
\item $s_j$: stride (distance between two consecutive positions of the
kernel) along axis $j$,
\item $p_j$: zero padding (number of zeros concatenated at the beginning and
at the end of an axis) along axis $j$.
\end{itemize}
\noindent For instance, \autoref{fig:numerical_padding_strides} shows a $3
\times 3$ kernel applied to a $5 \times 5$ input padded with a $1 \times 1$
border of zeros using $2 \times 2$ strides.
Note that strides constitute a form of \emph{subsampling}. As an alternative to
being interpreted as a measure of how much the kernel is translated, strides
can also be viewed as how much of the output is retained. For instance, moving
the kernel by hops of two is equivalent to moving the kernel by hops of one but
retaining only odd output elements (\autoref{fig:strides_subsampling}).
\begin{figure}[p]
\centering
\begin{tikzpicture}[scale=.35,every node/.style={minimum size=1cm}, on grid]
\begin{scope}[xshift=0cm,yshift=0cm]
\begin{scope}[xshift=0cm,yshift=0cm]
\draw[draw=base03,fill=violet,thick]
(0,0) grid (5,5) rectangle (0,0);
\end{scope}
\begin{scope}[xshift=0.5cm,yshift=0.5cm]
\draw[draw=base03,fill=blue,thick]
(0,0) grid (5,5) rectangle (0,0);
\end{scope}
\end{scope}
\foreach \x in {-10,1,11} {%
\begin{scope}[xshift=\x cm,yshift=10cm]
\begin{scope}[xshift=0cm,yshift=0cm]
\draw[draw=base03,fill=violet,thick]
(0,0) grid (3,3) rectangle (0,0);
\end{scope}
\begin{scope}[xshift=0.5cm,yshift=0.5cm]
\draw[draw=base03,fill=blue,thick]
(0,0) grid (3,3) rectangle (0,0);
\end{scope}
\end{scope}
\begin{scope}[xshift=\x cm,yshift=20cm]\begin{scope}[xshift=0.5cm]
\draw[draw=base03,fill=cyan,thick]
(0,0) grid (3,3) rectangle (0,0);
\end{scope}\end{scope}
}
\begin{scope}[xshift=1cm,yshift=30cm]
\foreach \s in {0.0,0.5,1.0} {%
\begin{scope}[xshift=\s cm,yshift=\s cm]
\draw[draw=base03,fill=cyan,thick]
(0,0) grid (3,3) rectangle (0,0);
\end{scope}
}
\end{scope}
\draw[->, thick] (-0.5,2.5) to (-8.5,9.5);
\draw[->, thick] (3,6) to (3,9.5);
\draw[->, thick] (6,3.5) to (12.5,9.5);
\draw[thick] (-8,14.5) to (-8,16);
\draw[->, thick] (-8,18) to (-8,19.5);
\node[thick] (p1) at (-8,17) {$+$};
\draw[thick] (3,14.5) to (3,16);
\draw[->, thick] (3,18) to (3,19.5);
\node[thick] (p2) at (3,17) {$+$};
\draw[thick] (13,14.5) to (13,16);
\draw[->, thick] (13,18) to (13,19.5);
\node[thick] (p3) at (13,17) {$+$};
\draw[->, thick] (-8,23.5) to (2,29.5);
\draw[->, thick] (3,23.5) to (2.5,29.5);
\draw[->, thick] (13,23.5) to (3,29.5);
\end{tikzpicture}
\caption{\label{fig:full_picture} A convolution mapping from two input
feature maps to three output feature maps using a $3 \times 2 \times 3
\times 3$ collection of kernels $\mathbf{w}$. In the left pathway, input
feature map 1 is convolved with kernel $\mathbf{w}_{1,1}$ and input
feature map 2 is convolved with kernel $\mathbf{w}_{1,2}$, and the
results are summed together elementwise to form the first output feature
map. The same is repeated for the middle and right pathways to form the
second and third feature maps, and all three output feature maps are
grouped together to form the output.}
\end{figure}
\begin{figure}[p]
\centering
\begin{tikzpicture}[scale=.35,every node/.style={minimum size=1cm}, on grid]
\begin{scope}[xshift=0,yshift=0cm]
\begin{scope}[xshift=0cm,yshift=0cm]
\draw[draw=base03,fill=blue,thick] (0,0) grid (5,5) rectangle (0,0);
\draw[fill=base02, opacity=0.4] (0,2) rectangle (3,5);
\end{scope}
\begin{scope}[xshift=7cm,yshift=1.5cm]
\draw[draw=base03,fill=cyan,thick] (0,0) grid (2,2) rectangle (0,0);
\end{scope}
\end{scope}
\draw[draw=base03, ->, thick] (2.6,3.5) to (4.5,3.5);
\draw[draw=base03, ->, thick] (1.5,2.4) to (1.5,0.5);
\draw[draw=base03, ->, thick] (5.25, 2.5) to (6.75, 2.5);
\begin{scope}[xshift=12cm,yshift=0cm]
\begin{scope}[xshift=0cm,yshift=0cm]
\draw[draw=base03,fill=blue,thick] (0,0) grid (5,5) rectangle (0,0);
\draw[fill=base02, opacity=0.4] (0,2) rectangle (3,5);
\end{scope}
\begin{scope}[xshift=7cm,yshift=1cm]
\draw[draw=base03,fill=cyan,thick] (0,0) grid (3,3) rectangle (0,0);
\draw[draw=base03] (1,0) -- (2,1) -- (2,0) -- (1,1);
\draw[draw=base03] (0,1) -- (1,2) -- (1,1) -- (0,2);
\draw[draw=base03] (1,1) -- (2,2) -- (2,1) -- (1,2);
\draw[draw=base03] (2,1) -- (3,2) -- (3,1) -- (2,2);
\draw[draw=base03] (1,2) -- (2,3) -- (2,2) -- (1,3);
\end{scope}
\begin{scope}[xshift=12cm,yshift=1.5cm]
\draw[draw=base03,fill=cyan,thick] (0,0) grid (2,2) rectangle (0,0);
\end{scope}
\end{scope}
\draw[draw=base03, ->, thick] (14.6,3.5) to (15.5,3.5);
\draw[draw=base03, ->, thick] (15.6,3.5) to (16.5,3.5);
\draw[draw=base03, ->, thick] (13.5,2.4) to (13.5,1.5);
\draw[draw=base03, ->, thick] (13.5,1.4) to (13.5,0.5);
\draw[draw=base03, ->, thick] (17.25, 2.5) to (18.75, 2.5);
\draw[draw=base03, ->, thick] (22.25, 2.5) to (23.75, 2.5);
\end{tikzpicture}
\caption{\label{fig:strides_subsampling} An alternative way of viewing
strides. Instead of translating the $3 \times 3$ kernel by increments of
$s = 2$ (left), the kernel is translated by increments of $1$ and only
one in $s = 2$ output elements is retained (right).}
\end{figure}
\section{Pooling}
In addition to discrete convolutions themselves, {\em pooling\/} operations
make up another important building block in CNNs. Pooling operations reduce
the size of feature maps by using some function to summarize subregions, such
as taking the average or the maximum value.
Pooling works by sliding a window across the input and feeding the content of
the window to a {\em pooling function}. In some sense, pooling works very much
like a discrete convolution, but replaces the linear combination described by
the kernel with some other function. \autoref{fig:numerical_average_pooling}
provides an example for average pooling, and \autoref{fig:numerical_max_pooling}
does the same for max pooling.
The following properties affect the output size $o_j$ of a pooling layer
along axis $j$:
\begin{itemize}
\item $i_j$: input size along axis $j$,
\item $k_j$: pooling window size along axis $j$,
\item $s_j$: stride (distance between two consecutive positions of the
pooling window) along axis $j$.
\end{itemize}
\begin{figure}[p]
\centering
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_00.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_01.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_02.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_03.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_04.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_05.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_06.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_07.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_average_pooling_08.pdf}
\caption{\label{fig:numerical_average_pooling} Computing the output values
of a $3 \times 3$ average pooling operation on a $5 \times 5$ input
using $1 \times 1$ strides.}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_00.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_01.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_02.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_03.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_04.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_05.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_06.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_07.pdf}
\includegraphics[width=0.32\textwidth]{pdf/numerical_max_pooling_08.pdf}
\caption{\label{fig:numerical_max_pooling} Computing the output values of a
$3 \times 3$ max pooling operation on a $5 \times 5$ input using $1
\times 1$ strides.}
\end{figure}
\chapter{Convolution arithmetic}
The analysis of the relationship between convolutional layer properties is eased
by the fact that they don't interact across axes, i.e., the choice of kernel
size, stride and zero padding along axis $j$ only affects the output size of
axis $j$. Because of that, this chapter will focus on the following simplified
setting:
\begin{itemize}
\item 2-D discrete convolutions ($N = 2$),
\item square inputs ($i_1 = i_2 = i$),
\item square kernel size ($k_1 = k_2 = k$),
\item same strides along both axes ($s_1 = s_2 = s$),
\item same zero padding along both axes ($p_1 = p_2 = p$).
\end{itemize}
This facilitates the analysis and the visualization, but keep in mind that the
results outlined here also generalize to the N-D and non-square cases.
\section{No zero padding, unit strides}
The simplest case to analyze is when the kernel just slides across every
position of the input (i.e., $s = 1$ and $p = 0$).
\autoref{fig:no_padding_no_strides} provides an example for $i = 4$ and $k =
3$.
One way of defining the output size in this case is by the number of possible
placements of the kernel on the input. Let's consider the width axis: the kernel
starts on the leftmost part of the input feature map and slides by steps of one
until it touches the right side of the input. The size of the output will be
equal to the number of steps made, plus one, accounting for the initial position
of the kernel (\autoref{fig:no_padding_no_strides_explained}). The same logic
applies for the height axis.
More formally, the following relationship can be inferred:
\begin{relationship}\label{rel:no_padding_no_strides}
For any $i$ and $k$, and for $s = 1$ and $p = 0$,
\begin{equation*}
o = (i - k) + 1.
\end{equation*}
\end{relationship}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_03.pdf}
\caption{\label{fig:no_padding_no_strides} (No padding, unit strides)
Convolving a $3 \times 3$ kernel over a $4 \times 4$ input using unit
strides (i.e., $i = 4$, $k = 3$, $s = 1$ and $p = 0$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_03.pdf}
\caption{\label{fig:arbitrary_padding_no_strides} (Arbitrary padding, unit
strides) Convolving a $4 \times 4$ kernel over a $5 \times 5$ input
padded with a $2 \times 2$ border of zeros using unit strides (i.e.,
$i = 5$, $k = 4$, $s = 1$ and $p = 2$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_03.pdf}
\caption{\label{fig:same_padding_no_strides} (Half padding, unit strides)
Convolving a $3 \times 3$ kernel over a $5 \times 5$ input using half
padding and unit strides (i.e., $i = 5$, $k = 3$, $s = 1$ and $p = 1$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_03.pdf}
\caption{\label{fig:full_padding_no_strides} (Full padding, unit strides)
Convolving a $3 \times 3$ kernel over a $5 \times 5$ input using full
padding and unit strides (i.e., $i = 5$, $k = 3$, $s = 1$ and $p = 2$).}
\end{figure}
\section{Zero padding, unit strides}
To factor in zero padding (i.e., only restricting to $s = 1$), let's consider
its effect on the effective input size: padding with $p$ zeros changes the
effective input size from $i$ to $i + 2p$. In the general case,
\autoref{rel:no_padding_no_strides} can then be used to infer the following
relationship:
\begin{relationship}\label{rel:arbitrary_padding_no_strides}
For any $i$, $k$ and $p$, and for $s = 1$,
\begin{equation*}
o = (i - k) + 2p + 1.
\end{equation*}
\end{relationship}
\noindent \autoref{fig:arbitrary_padding_no_strides} provides an example for $i
= 5$, $k = 4$ and $p = 2$.
In practice, two specific instances of zero padding are used quite extensively
because of their respective properties. Let's discuss them in more detail.
\subsection{Half (same) padding}
Having the output size be the same as the input size (i.e., $o = i$) can be a
desirable property:
\begin{relationship}\label{rel:same_padding_no_strides}
For any $i$ and for $k$ odd ($k = 2n + 1, \quad n \in \mathbb{N}$), $s = 1$ and
$p = \lfloor k / 2 \rfloor = n$,
\begin{equation*}
\begin{split}
o &= i + 2 \lfloor k / 2 \rfloor - (k - 1) \\
&= i + 2n - 2n \\
&= i.
\end{split}
\end{equation*}
\end{relationship}
\noindent This is sometimes referred to as {\em half\/} (or {\em same\/})
padding. \autoref{fig:same_padding_no_strides} provides an example for
$i = 5$, $k = 3$ and (therefore) $p = 1$.
\subsection{Full padding}
While convolving a kernel generally {\em decreases\/} the output size with
respect to the input size, sometimes the opposite is required. This can be
achieved with proper zero padding:
\begin{relationship}\label{rel:full_padding_no_strides}
For any $i$ and $k$, and for $p = k - 1$ and $s = 1$,
\begin{equation*}
\begin{split}
o &= i + 2(k - 1) - (k - 1) \\
&= i + (k - 1).
\end{split}
\end{equation*}
\end{relationship}
\noindent This is sometimes referred to as {\em full\/} padding, because in this
setting every possible partial or complete superimposition of the kernel on the
input feature map is taken into account. \autoref{fig:full_padding_no_strides}
provides an example for $i = 5$, $k = 3$ and (therefore) $p = 2$.
\section{No zero padding, non-unit strides}
All relationships derived so far only apply for unit-strided convolutions.
Incorporating non unitary strides requires another inference leap. To
facilitate the analysis, let's momentarily ignore zero padding (i.e., $s > 1$
and $p = 0$). \autoref{fig:no_padding_strides} provides an example for $i =
5$, $k = 3$ and $s = 2$.
Once again, the output size can be defined in terms of the number of possible
placements of the kernel on the input. Let's consider the width axis: the
kernel starts as usual on the leftmost part of the input, but this time it
slides by steps of size $s$ until it touches the right side of the input. The
size of the output is again equal to the number of steps made, plus one,
accounting for the initial position of the kernel
(\autoref{fig:no_padding_strides_explained}). The same logic applies for the
height axis.
From this, the following relationship can be inferred:
\begin{relationship}\label{rel:no_padding_strides}
For any $i$, $k$ and $s$, and for $p = 0$,
\begin{equation*}
o = \left\lfloor \frac{i - k}{s} \right\rfloor + 1.
\end{equation*}
\end{relationship}
\noindent The floor function accounts for the fact that sometimes the last
possible step does {\em not\/} coincide with the kernel reaching the end of the
input, i.e., some input units are left out (see
\autoref{fig:padding_strides_odd} for an example of such a case).
\section{Zero padding, non-unit strides}
The most general case (convolving over a zero padded input using non-unit
strides) can be derived by applying \autoref{rel:no_padding_strides} on an
effective input of size $i + 2p$, in analogy to what was done for
\autoref{rel:arbitrary_padding_no_strides}:
\begin{relationship}\label{rel:padding_strides}
For any $i$, $k$, $p$ and $s$,
\begin{equation*}
o = \left\lfloor \frac{i + 2p - k}{s} \right\rfloor + 1.
\end{equation*}
\end{relationship}
\noindent As before, the floor function means that in some cases a convolution
will produce the same output size for multiple input sizes. More specifically,
if $i + 2p - k$ is a multiple of $s$, then any input size $j = i + a, \quad a
\in \{0,\ldots,s - 1\}$ will produce the same output size. Note that this
ambiguity applies only for $s > 1$.
\autoref{fig:padding_strides} shows an example with $i = 5$, $k = 3$, $s = 2$
and $p = 1$, while \autoref{fig:padding_strides_odd} provides an example for
$i = 6$, $k = 3$, $s = 2$ and $p = 1$. Interestingly, despite having different
input sizes these convolutions share the same output size. While this doesn't
affect the analysis for {\em convolutions}, this will complicate the analysis
in the case of {\em transposed convolutions}.
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_03.pdf}
\caption{\label{fig:no_padding_strides} (No zero padding, arbitrary
strides) Convolving a $3 \times 3$ kernel over a $5 \times 5$ input
using $2 \times 2$ strides (i.e., $i = 5$, $k = 3$, $s = 2$ and
$p = 0$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_03.pdf}
\caption{\label{fig:padding_strides} (Arbitrary padding and strides)
Convolving a $3 \times 3$ kernel over a $5 \times 5$ input padded with
a $1 \times 1$ border of zeros using $2 \times 2$ strides (i.e.,
$i = 5$, $k = 3$, $s = 2$ and $p = 1$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_03.pdf}
\caption{\label{fig:padding_strides_odd} (Arbitrary padding and strides)
Convolving a $3 \times 3$ kernel over a $6 \times 6$ input padded with
a $1 \times 1$ border of zeros using $2 \times 2$ strides (i.e.,
$i = 6$, $k = 3$, $s = 2$ and $p = 1$). In this case, the bottom row
and right column of the zero padded input are not covered by the
kernel.}
\end{figure}
\begin{figure}[p]
\centering
\begin{subfigure}[t]{0.48\textwidth}
\centering
\begin{tikzpicture}[scale=.35,every node/.style={minimum size=1cm},
on grid]
\draw[fill=blue] (0,0) rectangle (5,5);
\draw[draw=base03, thick] (0,0) grid (5,5);
\draw[fill=base02, opacity=0.4] (0,2) rectangle (3,5);
\draw[step=10mm, base03, thick] (0,2) grid (3,5);
\draw[draw=base03, ->, thick] (2.6,3.5) to (3.5,3.5);
\draw[draw=base03, ->, thick] (3.6,3.5) to (4.5,3.5);
\draw[draw=base03, ->, thick] (1.5,2.4) to (1.5,1.5);
\draw[draw=base03, ->, thick] (1.5,1.4) to (1.5,0.5);
\end{tikzpicture}
\caption{\label{fig:no_padding_no_strides_explained} The kernel has to
slide two steps to the right to touch the right side of the input
(and equivalently downwards). Adding one to account for the
initial kernel position, the output size is $3 \times 3$.}
\end{subfigure}
~
\begin{subfigure}[t]{0.48\textwidth}
\centering
\begin{tikzpicture}[scale=.35,every node/.style={minimum size=1cm},
on grid]
\draw[fill=blue] (0,0) rectangle (5,5);
\draw[draw=base03, thick] (0,0) grid (5,5);
\draw[fill=base02, opacity=0.4] (0,2) rectangle (3,5);
\draw[step=10mm, base03, thick] (0,2) grid (3,5);
\draw[draw=base03, ->, thick] (2.5,3.5) to (4.5,3.5);
\draw[draw=base03, ->, thick] (1.5,2.5) to (1.5,0.5);
\end{tikzpicture}
\caption{\label{fig:no_padding_strides_explained} The kernel has to
slide one step of size two to the right to touch the right side of
the input (and equivalently downwards). Adding one to account for
the initial kernel position, the output size is $2 \times 2$.}
\end{subfigure}
\caption{Counting kernel positions.}
\end{figure}
\chapter{Pooling arithmetic}
In a neural network, pooling layers provide invariance to small translations of
the input. The most common kind of pooling is \emph{max pooling}, which
consists in splitting the input in (usually non-overlapping) patches and
outputting the maximum value of each patch. Other kinds of pooling exist, e.g.,
mean or average pooling, which all share the same idea of aggregating the input
locally by applying a non-linearity to the content of some patches \citep{%
boureau-cvpr-10,boureau-icml-10,boureau-iccv-11,ICML2011Saxe_551}.
Some readers may have noticed that the treatment of convolution arithmetic only
relies on the assumption that some function is repeatedly applied onto subsets
of the input. This means that the relationships derived in the previous chapter
can be reused in the case of pooling arithmetic. Since pooling does not involve
zero padding, the relationship describing the general case is as follows:
\begin{relationship}\label{rel:pooling}
For any $i$, $k$ and $s$,
\begin{equation*}
o = \left\lfloor \frac{i - k}{s} \right\rfloor + 1.
\end{equation*}
\end{relationship}
\noindent This relationship holds for any type of pooling.
\chapter{Transposed convolution arithmetic}
The need for transposed convolutions generally arises from the desire to use a
transformation going in the opposite direction of a normal convolution, i.e.,
from something that has the shape of the output of some convolution to
something that has the shape of its input while maintaining a connectivity
pattern that is compatible with said convolution. For instance, one might use
such a transformation as the decoding layer of a convolutional autoencoder or to
project feature maps to a higher-dimensional space.
Once again, the convolutional case is considerably more complex than the
fully-connected case, which only requires to use a weight matrix whose shape
has been transposed. However, since every convolution boils down to an
efficient implementation of a matrix operation, the insights gained from the
fully-connected case are useful in solving the convolutional case.
Like for convolution arithmetic, the dissertation about transposed convolution
arithmetic is simplified by the fact that transposed convolution properties
don't interact across axes.
The chapter will focus on the following setting:
\begin{itemize}
\item 2-D transposed convolutions ($N = 2$),
\item square inputs ($i_1 = i_2 = i$),
\item square kernel size ($k_1 = k_2 = k$),
\item same strides along both axes ($s_1 = s_2 = s$),
\item same zero padding along both axes ($p_1 = p_2 = p$).
\end{itemize}
\noindent Once again, the results outlined generalize to the N-D and non-square
cases.
\section{Convolution as a matrix operation}
Take for example the convolution represented in
\autoref{fig:no_padding_no_strides}. If the input and output were to be unrolled
into vectors from left to right, top to bottom, the convolution could be
represented as a sparse matrix $\mathbf{C}$ where the non-zero elements are the
elements $w_{i,j}$ of the kernel (with $i$ and $j$ being the row and column of
the kernel respectively):
\begin{equation*}
\resizebox{.98\hsize}{!}{$
\begin{pmatrix}
w_{0,0} & w_{0,1} & w_{0,2} & 0 & w_{1,0} & w_{1,1} & w_{1,2} & 0 &
w_{2,0} & w_{2,1} & w_{2,2} & 0 & 0 & 0 & 0 & 0 \\
0 & w_{0,0} & w_{0,1} & w_{0,2} & 0 & w_{1,0} & w_{1,1} & w_{1,2} &
0 & w_{2,0} & w_{2,1} & w_{2,2} & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & w_{0,0} & w_{0,1} & w_{0,2} & 0 &
w_{1,0} & w_{1,1} & w_{1,2} & 0 & w_{2,0} & w_{2,1} & w_{2,2} & 0 \\
0 & 0 & 0 & 0 & 0 & w_{0,0} & w_{0,1} & w_{0,2} &
0 & w_{1,0} & w_{1,1} & w_{1,2} & 0 & w_{2,0} & w_{2,1} & w_{2,2} \\
\end{pmatrix}$}
\end{equation*}
This linear operation takes the input matrix flattened as a 16-dimensional
vector and produces a 4-dimensional vector that is later reshaped as the $2
\times 2$ output matrix.
Using this representation, the backward pass is easily obtained by transposing
$\mathbf{C}$; in other words, the error is backpropagated by multiplying the
loss with $\mathbf{C}^T$. This operation takes a 4-dimensional vector as input
and produces a 16-dimensional vector as output, and its connectivity pattern is
compatible with $\mathbf{C}$ by construction.
Notably, the kernel $\mathbf{w}$ defines both the matrices $\mathbf{C}$ and
$\mathbf{C}^T$ used for the forward and backward passes.
\section{Transposed convolution}
Let's now consider what would be required to go the other way around, i.e., map
from a 4-dimensional space to a 16-dimensional space, while keeping the
connectivity pattern of the convolution depicted in
\autoref{fig:no_padding_no_strides}. This operation is known as a {\em
transposed convolution}.
Transposed convolutions -- also called {\em fractionally strided convolutions\/}
or {\em deconvolutions\/}\footnote{The term ``deconvolution'' is sometimes used
in the literature, but we advocate against it on the grounds that a
deconvolution is mathematically defined as the inverse of a convolution, which
is different from a transposed convolution.} -- work by swapping the forward and
backward passes of a convolution. One way to put it is to note that the kernel
defines a convolution, but whether it's a direct convolution or a transposed
convolution is determined by how the forward and backward passes are computed.
For instance, although the kernel $\mathbf{w}$ defines a convolution whose
forward and backward passes are computed by multiplying with $\mathbf{C}$ and
$\mathbf{C}^T$ respectively, it {\em also\/} defines a transposed convolution
whose forward and backward passes are computed by multiplying with
$\mathbf{C}^T$ and $(\mathbf{C}^T)^T = \mathbf{C}$ respectively.\footnote{The
transposed convolution operation can be thought of as the gradient of {\em
some\/} convolution with respect to its input, which is usually how
transposed convolutions are implemented in practice.}
Finally note that it is always possible to emulate a transposed convolution with
a direct convolution. The disadvantage is that it usually involves adding many
columns and rows of zeros to the input, resulting in a much less efficient
implementation.
Building on what has been introduced so far, this chapter will proceed somewhat
backwards with respect to the convolution arithmetic chapter, deriving the
properties of each transposed convolution by referring to the direct
convolution with which it shares the kernel, and defining the equivalent direct
convolution.
\section{No zero padding, unit strides, transposed}
The simplest way to think about a transposed convolution on a given input is to
imagine such an input as being the result of a direct convolution applied on
some initial feature map. The trasposed convolution can be then considered as
the operation that allows to recover the \emph{shape}~\footnote{Note that the
transposed convolution does not guarantee to recover the input itself, as it
is not defined as the inverse of the convolution, but rather just returns a
feature map that has the same width and height.} of this initial feature map.
Let's consider the convolution of a $3 \times 3$ kernel on a $4 \times 4$
input with unitary stride and no padding (i.e., $i = 4$, $k = 3$, $s = 1$ and
$p = 0$). As depicted in \autoref{fig:no_padding_no_strides}, this produces a
$2 \times 2$ output. The transpose of this convolution will then have an output
of shape $4 \times 4$ when applied on a $2 \times 2$ input.
Another way to obtain the result of a transposed convolution is to apply an
equivalent -- but much less efficient -- direct convolution. The example
described so far could be tackled by convolving a $3 \times 3$ kernel over a
$2 \times 2$ input padded with a $2 \times 2$ border of zeros using unit
strides (i.e., $i' = 2$, $k' = k$, $s' = 1$ and $p' = 2$), as shown in
\autoref{fig:no_padding_no_strides_transposed}. Notably, the kernel's and
stride's sizes remain the same, but the input of the transposed convolution is
now zero padded.\footnote{Note that although
equivalent to applying the transposed matrix, this visualization adds a lot
of zero multiplications in the form of zero padding. This is done here for
illustration purposes, but it is inefficient, and software implementations
will normally not perform the useless zero multiplications.}
One way to understand the logic behind zero padding is to consider the
connectivity pattern of the transposed convolution and use it to guide the
design of the equivalent convolution. For example, the top left pixel of the
input of the direct convolution only contribute to the top left pixel of the
output, the top right pixel is only connected to the top right output pixel,
and so on.
To maintain the same connectivity pattern in the equivalent convolution it is
necessary to zero pad the input in such a way that the first (top-left)
application of the kernel only touches the top-left pixel, i.e., the padding
has to be equal to the size of the kernel minus one.
Proceeding in the same fashion it is possible to determine similar observations
for the other elements of the image, giving rise to the following relationship:
\begin{relationship}\label{rel:no_padding_no_strides_transposed}
A convolution described by $s = 1$, $p = 0$ and $k$ has an associated
transposed convolution described by $k' = k$, $s' = s$ and $p' = k - 1$ and its
output size is
\begin{equation*}
o' = i' + (k - 1).
\end{equation*}
\end{relationship}
Interestingly, this corresponds to a fully padded convolution with unit
strides.
\section{Zero padding, unit strides, transposed}
Knowing that the transpose of a non-padded convolution is equivalent to
convolving a zero padded input, it would be reasonable to suppose that the
transpose of a zero padded convolution is equivalent to convolving an input
padded with {\em less\/} zeros.
It is indeed the case, as shown in
\autoref{fig:arbitrary_padding_no_strides_transposed} for $i = 5$, $k = 4$ and
$p = 2$.
Formally, the following relationship applies for zero padded convolutions:
\begin{relationship}\label{rel:arbitrary_padding_no_strides_transposed}
A convolution described by $s = 1$, $k$ and $p$ has an
associated transposed convolution described by $k' = k$, $s' = s$ and $p' = k -
p - 1$ and its output size is
\begin{equation*}
o' = i' + (k - 1) - 2p.
\end{equation*}
\end{relationship}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_transposed_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_transposed_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_transposed_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_no_strides_transposed_03.pdf}
\caption{\label{fig:no_padding_no_strides_transposed} The transpose of
convolving a $3 \times 3$ kernel over a $4 \times 4$ input using unit
strides (i.e., $i = 4$, $k = 3$, $s = 1$ and $p = 0$). It is equivalent
to convolving a $3 \times 3$ kernel over a $2 \times 2$ input padded
with a $2 \times 2$ border of zeros using unit strides (i.e., $i' = 2$,
$k' = k$, $s' = 1$ and $p' = 2$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_transposed_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_transposed_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_transposed_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/arbitrary_padding_no_strides_transposed_03.pdf}
\caption{\label{fig:arbitrary_padding_no_strides_transposed} The transpose
of convolving a $4 \times 4$ kernel over a $5 \times 5$ input padded
with a $2 \times 2$ border of zeros using unit strides (i.e., $i = 5$,
$k = 4$, $s = 1$ and $p = 2$). It is equivalent to convolving a $4
\times 4$ kernel over a $6 \times 6$ input padded with a $1 \times 1$
border of zeros using unit strides (i.e., $i' = 6$, $k' = k$, $s' = 1$
and $p' = 1$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_transposed_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_transposed_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_transposed_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/same_padding_no_strides_transposed_03.pdf}
\caption{\label{fig:same_padding_no_strides_transposed} The transpose of
convolving a $3 \times 3$ kernel over a $5 \times 5$ input using half
padding and unit strides (i.e., $i = 5$, $k = 3$, $s = 1$ and $p = 1$).
It is equivalent to convolving a $3 \times 3$ kernel over a $5 \times 5$
input using half padding and unit strides (i.e., $i' = 5$, $k' = k$, $s'
= 1$ and $p' = 1$).}
\end{figure}
\subsection{Half (same) padding, transposed}
By applying the same inductive reasoning as before, it is reasonable to expect
that the equivalent convolution of the transpose of a half padded convolution
is itself a half padded convolution, given that the output size of a half
padded convolution is the same as its input size. Thus the following relation
applies:
\begin{relationship}\label{rel:half_padding_no_strides_transposed}
A convolution described by $k = 2n + 1, \quad n \in \mathbb{N}$, $s = 1$ and $p
= \lfloor k / 2 \rfloor = n$ has an associated transposed convolution described
by $k' = k$, $s' = s$ and $p' = p$ and its output size is
\begin{equation*}
\begin{split}
o' &= i' + (k - 1) - 2p \\
&= i' + 2n - 2n \\
&= i'.
\end{split}
\end{equation*}
\end{relationship}
\autoref{fig:same_padding_no_strides_transposed} provides an example for $i =
5$, $k = 3$ and (therefore) $p = 1$.
\subsection{Full padding, transposed}
Knowing that the equivalent convolution of the transpose of a non-padded
convolution involves full padding, it is unsurprising that the equivalent of
the transpose of a fully padded convolution is a non-padded convolution:
\begin{relationship}\label{rel:full_padding_no_strides_transposed}
A convolution described by $s = 1$, $k$ and $p = k - 1$ has an
associated transposed convolution described by $k' = k$, $s' = s$ and $p' = 0$
and its output size is
\begin{equation*}
\begin{split}
o' &= i' + (k - 1) - 2p \\
&= i' - (k - 1)
\end{split}
\end{equation*}
\end{relationship}
\autoref{fig:full_padding_no_strides_transposed} provides an example for $i =
5$, $k = 3$ and (therefore) $p = 2$.
\section{No zero padding, non-unit strides, transposed}
Using the same kind of inductive logic as for zero padded convolutions, one
might expect that the transpose of a convolution with $s > 1$ involves an
equivalent convolution with $s < 1$. As will be explained, this is a valid
intuition, which is why transposed convolutions are sometimes called {\em
fractionally strided convolutions}.
\autoref{fig:no_padding_strides_transposed} provides an example for $i = 5$, $k
= 3$ and $s = 2$ which helps understand what fractional strides involve: zeros
are inserted {\em between\/} input units, which makes the kernel move around at
a slower pace than with unit strides.\footnote{Doing so is inefficient and
real-world implementations avoid useless multiplications by zero, but
conceptually it is how the transpose of a strided convolution can be
thought of.}
For the moment, it will be assumed that the convolution is non-padded ($p = 0$)
and that its input size $i$ is such that $i - k$ is a multiple of $s$. In that
case, the following relationship holds:
\begin{relationship}\label{rel:no_padding_strides_transposed}
A convolution described by $p = 0$, $k$ and $s$ and whose input
size is such that $i - k$ is a multiple of $s$, has an associated transposed
convolution described by $\tilde{i}'$, $k' = k$, $s' = 1$ and $p' = k - 1$,
where $\tilde{i}'$ is the size of the stretched input obtained by adding
$s - 1$ zeros between each input unit, and its output size is
\begin{equation*}
\begin{split}
o' = s (i' - 1) + k.
\end{split}
\end{equation*}
\end{relationship}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_transposed_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_transposed_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_transposed_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/full_padding_no_strides_transposed_03.pdf}
\caption{\label{fig:full_padding_no_strides_transposed} The transpose of
convolving a $3 \times 3$ kernel over a $5 \times 5$ input using full
padding and unit strides (i.e., $i = 5$, $k = 3$, $s = 1$ and $p = 2$).
It is equivalent to convolving a $3 \times 3$ kernel over a $7 \times 7$
input using unit strides (i.e., $i' = 7$, $k' = k$, $s' = 1$ and $p' =
0$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_transposed_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_transposed_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_transposed_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/no_padding_strides_transposed_03.pdf}
\caption{\label{fig:no_padding_strides_transposed} The transpose of
convolving a $3 \times 3$ kernel over a $5 \times 5$ input using $2
\times 2$ strides (i.e., $i = 5$, $k = 3$, $s = 2$ and $p = 0$). It is
equivalent to convolving a $3 \times 3$ kernel over a $2 \times 2$ input
(with $1$ zero inserted between inputs) padded with a $2 \times 2$
border of zeros using unit strides (i.e., $i' = 2$, $\tilde{i}' = 3$, $k'
= k$, $s' = 1$ and $p' = 2$).}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_transposed_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_transposed_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_transposed_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_transposed_03.pdf}
\caption{\label{fig:padding_strides_transposed} The transpose of convolving
a $3 \times 3$ kernel over a $5 \times 5$ input padded with a $1 \times
1$ border of zeros using $2 \times 2$ strides (i.e., $i = 5$, $k = 3$, $s
= 2$ and $p = 1$). It is equivalent to convolving a $3 \times 3$ kernel
over a $3 \times 3$ input (with $1$ zero inserted between inputs) padded
with a $1 \times 1$ border of zeros using unit strides (i.e., $i' = 3$,
$\tilde{i}' = 5$, $k' = k$, $s' = 1$ and $p' = 1$).}
\end{figure}
\section{Zero padding, non-unit strides, transposed}
When the convolution's input size $i$ is such that $i + 2p - k$ is a multiple
of $s$, the analysis can extended to the zero padded case by combining
\autoref{rel:arbitrary_padding_no_strides_transposed} and
\autoref{rel:no_padding_strides_transposed}:
\begin{relationship}\label{rel:padding_strides_transposed}
A convolution described by $k$, $s$ and $p$ and whose
input size $i$ is such that $i + 2p - k$ is a multiple of $s$ has an associated
transposed convolution described by $\tilde{i}'$, $k' = k$, $s' = 1$ and
$p' = k - p - 1$, where $\tilde{i}'$ is the size of the stretched input
obtained by adding $s - 1$ zeros between each input unit, and its output size
is
\begin{equation*}
\begin{split}
o' = s (i' - 1) + k - 2p.
\end{split}
\end{equation*}
\end{relationship}
\autoref{fig:padding_strides_transposed} provides an example for $i = 5$, $k =
3$, $s = 2$ and $p = 1$.
The constraint on the size of the input $i$ can be relaxed by introducing
another parameter $a \in \{0, \ldots, s - 1\}$ that allows to distinguish
between the $s$ different cases that all lead to the same $i'$:
\begin{relationship}\label{rel:padding_strides_transposed_odd}
A convolution described by $k$, $s$ and $p$ has an
associated transposed convolution described by $a$, $\tilde{i}'$, $k' = k$, $s'
= 1$ and $p' = k - p - 1$, where $\tilde{i}'$ is the size of the stretched
input obtained by adding $s - 1$ zeros between each input unit, and $a = (i +
2p - k) \mod s$ represents the number of zeros added to the bottom and right edges
of the input, and its output size is
\begin{equation*}
\begin{split}
o' = s (i' - 1) + a + k - 2p.
\end{split}
\end{equation*}
\end{relationship}
\autoref{fig:padding_strides_odd_transposed} provides an example for $i = 6$, $k
= 3$, $s = 2$ and $p = 1$.
\begin{figure}[p]
\centering
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_transposed_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_transposed_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_transposed_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/padding_strides_odd_transposed_03.pdf}
\caption{\label{fig:padding_strides_odd_transposed} The transpose of
convolving a $3 \times 3$ kernel over a $6 \times 6$ input padded with a
$1 \times 1$ border of zeros using $2 \times 2$ strides (i.e., $i = 6$,
$k = 3$, $s = 2$ and $p = 1$). It is equivalent to convolving a $3
\times 3$ kernel over a $2 \times 2$ input (with $1$ zero inserted
between inputs) padded with a $1 \times 1$ border of zeros (with an
additional border of size $1$ added to the bottom and right edges) using
unit strides (i.e., $i' = 3$, $\tilde{i}' = 5$, $a = 1$, $k' = k$, $s' =
1$ and $p' = 1$).}
\end{figure}
\chapter{Miscellaneous convolutions}
\section{Dilated convolutions}
Readers familiar with the deep learning literature may have noticed the term
``dilated convolutions'' (or ``atrous convolutions'', from the French expression
{\em convolutions \`{a} trous}) appear in recent papers. Here we attempt to
provide an intuitive understanding of dilated convolutions. For a more in-depth
description and to understand in what contexts they are applied, see
\citet{chen2014semantic,yu2015multi}.
Dilated convolutions ``inflate'' the kernel by inserting spaces between the
kernel elements. The dilation ``rate'' is controlled by an additional
hyperparameter $d$. Implementations may vary, but there are usually $d - 1$
spaces inserted between kernel elements such that $d = 1$ corresponds to a
regular convolution.
Dilated convolutions are used to cheaply increase the receptive field of output
units without increasing the kernel size, which is especially effective
when multiple dilated convolutions are stacked one after another. For a
concrete example, see \citet{oord2016wavenet}, in which the proposed WaveNet
model implements an autoregressive generative model for raw audio which uses
dilated convolutions to condition new audio frames on a large context of past
audio frames.
To understand the relationship tying the dilation rate $d$ and the output size
$o$, it is useful to think of the impact of $d$ on the {\em effective kernel
size}. A kernel of size $k$ dilated by a factor $d$ has an effective size
\begin{equation*}
\hat{k} = k + (k - 1)(d - 1).
\end{equation*}
This can be combined with \autoref{rel:padding_strides} to form the following
relationship for dilated convolutions:
\begin{relationship}\label{rel:dilation}
For any $i$, $k$, $p$ and $s$, and for a dilation rate $d$,
\begin{equation*}
o = \left\lfloor \frac{i + 2p - k - (k - 1)(d - 1)}{s} \right\rfloor + 1.
\end{equation*}
\end{relationship}
\begin{figure}[h]
\centering
\includegraphics[width=0.24\textwidth]{pdf/dilation_00.pdf}
\includegraphics[width=0.24\textwidth]{pdf/dilation_01.pdf}
\includegraphics[width=0.24\textwidth]{pdf/dilation_02.pdf}
\includegraphics[width=0.24\textwidth]{pdf/dilation_03.pdf}
\caption{\label{fig:dilation} (Dilated convolution)
Convolving a $3 \times 3$ kernel over a $7 \times 7$ input with a
dilation factor of 2 (i.e., $i = 7$, $k = 3$, $d = 2$, $s = 1$ and
$p = 0$).}
\end{figure}
\noindent \autoref{fig:dilation} provides an example for $i = 7$, $k = 3$ and
$d = 2$.
\bibliography{bibliography}
\bibliographystyle{natbib}
\end{document}
================================================
FILE: gif/.gitignore
================================================
# Ignore everything in this directory
*
# Except this file
!.gitignore
================================================
FILE: natbib/natbib.bst
================================================
%%
%% This is file `natbib.bst', generated
%% on <1994/9/16> with the docstrip utility (2.2h).
%%
%% The original source files were:
%%
%% genbst.mbs (with options: `ay,nat,seq-lab,nm-rev,dt-beg,yr-par,vol-bf,
%% volp-com,etal-it')
%% ----------------------------------------
%% *** Personal bib style, PWD ***
%%
%% (Here are the specifications of the source file)
%% \ProvidesFile{genbst.mbs}[1994/09/16 1.5 (PWD)]
%% For use with BibTeX version 0.99a or later
%% and with LaTeX 2.09 or 2e
%%-------------------------------------------------------------------
%% NOTICE:
%% This file may be used for non-profit purposes.
%% It may not be distributed in exchange for money,
%% other than distribution costs.
%%
%% The author provides it `as is' and does not guarantee it in any way.
%%
%% Copyright (C) 1994 Patrick W. Daly
%% Max-Planck-Institut f\"ur Aeronomie
%% Postfach 20
%% D-37189 Katlenburg-Lindau
%% Germany
%%
%% E-mail:
%% SPAN-- nsp::linmpi::daly (note nsp also known as ecd1)
%% Internet-- daly@linmpi.dnet.gwdg.de
%%-----------------------------------------------------------
%% \CharacterTable
%% {Upper-case \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%% Lower-case \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%% Digits \0\1\2\3\4\5\6\7\8\9
%% Exclamation \! Double quote \" Hash (number) \#
%% Dollar \$ Percent \% Ampersand \&
%% Acute accent \' Left paren \( Right paren \)
%% Asterisk \* Plus \+ Comma \,
%% Minus \- Point \. Solidus \/
%% Colon \: Semicolon \; Less than \<
%% Equals \= Greater than \> Question mark \?
%% Commercial at \@ Left bracket \[ Backslash \\
%% Right bracket \] Circumflex \^ Underscore \_
%% Grave accent \` Left brace \{ Vertical bar \|
%% Right brace \} Tilde \~}
%%---------------------------------------------------------------------
% This is an author-year citation style bibliography. As such, it is
% non-standard LaTeX, and requires a special package file to function properly.
% Such a package is natbib.sty by Patrick W. Daly
% The form of the \bibitem entries is
% \bibitem[Jones et al.(1990)]{key}...
% \bibitem[Jones et al.(1990)Jones, Baker, and Smith]{key}...
% The essential feature is that the label (the part in brackets) consists
% of the author names, as they should appear in the citation, with the year
% in parentheses following. There must be no space before the opening
% parenthesis!
% With natbib v5.3, a full list of authors may also follow the year.
% In natbib.sty, it is possible to define the type of enclosures that is
% really wanted (brackets or parentheses), but in either case, there must
% be parentheses in the label.
% The \cite command functions as follows:
% \cite{key} ==>> Jones et al. (1990)
% \cite[]{key} ==>> (Jones et al., 1990)
% \cite[chap. 2]{key} ==>> (Jones et al., 1990, chap. 2)
% \cite[e.g.][]{key} ==>> (e.g. Jones et al., 1990)
% \cite[e.g.][p. 32]{key} ==>> (e.g. Jones et al., p. 32)
% \citeauthor{key} Jones et al.
% \citefullauthor{key} Jones, Baker, and Smith
% \citeyear{key} 1990
%%---------------------------------------------------------------------
ENTRY
{ address
author
booktitle
chapter
edition
editor
howpublished
institution
journal
key
month
note
number
organization
pages
publisher
school
series
title
type
volume
year
}
{}
{ label extra.label sort.label }
INTEGERS { output.state before.all mid.sentence after.sentence after.block }
FUNCTION {init.state.consts}
{ #0 'before.all :=
#1 'mid.sentence :=
#2 'after.sentence :=
#3 'after.block :=
}
STRINGS { s t }
FUNCTION {output.nonnull}
{ 's :=
output.state mid.sentence =
{ ", " * write$ }
{ output.state after.block =
{ add.period$ write$
newline$
"\newblock " write$
}
{ output.state before.all =
'write$
{ add.period$ " " * write$ }
if$
}
if$
mid.sentence 'output.state :=
}
if$
s
}
FUNCTION {output}
{ duplicate$ empty$
'pop$
'output.nonnull
if$
}
FUNCTION {output.check}
{ 't :=
duplicate$ empty$
{ pop$ "empty " t * " in " * cite$ * warning$ }
'output.nonnull
if$
}
FUNCTION {fin.entry}
{ add.period$
write$
newline$
}
FUNCTION {new.block}
{ output.state before.all =
'skip$
{ after.block 'output.state := }
if$
}
FUNCTION {new.sentence}
{ output.state after.block =
'skip$
{ output.state before.all =
'skip$
{ after.sentence 'output.state := }
if$
}
if$
}
FUNCTION {not}
{ { #0 }
{ #1 }
if$
}
FUNCTION {and}
{ 'skip$
{ pop$ #0 }
if$
}
FUNCTION {or}
{ { pop$ #1 }
'skip$
if$
}
FUNCTION {non.stop}
{ duplicate$
"}" * add.period$
#-1 #1 substring$ "." =
}
FUNCTION {new.block.checkb}
{ empty$
swap$ empty$
and
'skip$
'new.block
if$
}
FUNCTION {field.or.null}
{ duplicate$ empty$
{ pop$ "" }
'skip$
if$
}
FUNCTION {emphasize}
{ duplicate$ empty$
{ pop$ "" }
{ "{\em " swap$ * non.stop
{ "\/}" * }
{ "}" * }
if$
}
if$
}
FUNCTION {bolden}
{ duplicate$ empty$
{ pop$ "" }
{ "{\bf " swap$ * "}" * }
if$
}
INTEGERS { nameptr namesleft numnames }
FUNCTION {format.names}
{ 's :=
#1 'nameptr :=
s num.names$ 'numnames :=
numnames 'namesleft :=
{ namesleft #0 > }
{ s nameptr
"{vv~}{ll}{, jj}{, f.}" format.name$ 't :=
nameptr #1 >
{
namesleft #1 >
{ ", " * t * }
{
numnames #2 >
{ "," * }
'skip$
if$
t "others" =
{ " " * "et~al." emphasize * }
{ " and " * t * }
if$
}
if$
}
't
if$
nameptr #1 + 'nameptr :=
namesleft #1 - 'namesleft :=
}
while$
}
FUNCTION {format.names.ed}
{ 's :=
#1 'nameptr :=
s num.names$ 'numnames :=
numnames 'namesleft :=
{ namesleft #0 > }
{ s nameptr
"{f.~}{vv~}{ll}{, jj}"
format.name$ 't :=
nameptr #1 >
{
namesleft #1 >
{ ", " * t * }
{
numnames #2 >
{ "," * }
'skip$
if$
t "others" =
{ " " * "et~al." emphasize * }
{ " and " * t * }
if$
}
if$
}
't
if$
nameptr #1 + 'nameptr :=
namesleft #1 - 'namesleft :=
}
while$
}
FUNCTION {format.key}
{ empty$
{ key field.or.null }
{ "" }
if$
}
FUNCTION {format.authors}
{ author empty$
{ "" }
{ author format.names }
if$
}
FUNCTION {format.editors}
{ editor empty$
{ "" }
{ editor format.names
editor num.names$ #1 >
{ ", editors" * }
{ ", editor" * }
if$
}
if$
}
FUNCTION {format.in.editors}
{ editor empty$
{ "" }
{ editor format.names.ed
editor num.names$ #1 >
{ ", editors" * }
{ ", editor" * }
if$
}
if$
}
FUNCTION {format.title}
{ title empty$
{ "" }
{ title "t" change.case$
}
if$
}
FUNCTION {format.full.names}
{'s :=
#1 'nameptr :=
s num.names$ 'numnames :=
numnames 'namesleft :=
{ namesleft #0 > }
{ s nameptr
"{vv~}{ll}" format.name$ 't :=
nameptr #1 >
{
namesleft #1 >
{ ", " * t * }
{
numnames #2 >
{ "," * }
'skip$
if$
t "others" =
{ " " * "et~al." emphasize * }
{ " and " * t * }
if$
}
if$
}
't
if$
nameptr #1 + 'nameptr :=
namesleft #1 - 'namesleft :=
}
while$
}
FUNCTION {author.editor.key.full}
{ author empty$
{ editor empty$
{ key empty$
{ cite$ #1 #3 substring$ }
'key
if$
}
{ editor format.full.names }
if$
}
{ author format.full.names }
if$
}
FUNCTION {author.key.full}
{ author empty$
{ key empty$
{ cite$ #1 #3 substring$ }
'key
if$
}
{ author format.full.names }
if$
}
FUNCTION {editor.key.full}
{ editor empty$
{ key empty$
{ cite$ #1 #3 substring$ }
'key
if$
}
{ editor format.full.names }
if$
}
FUNCTION {make.full.names}
{ type$ "book" =
type$ "inbook" =
or
'author.editor.key.full
{ type$ "proceedings" =
'editor.key.full
'author.key.full
if$
}
if$
}
FUNCTION {output.bibitem}
{ newline$
"\bibitem[" write$
label write$
")" make.full.names * "]{" * write$
cite$ write$
"}" write$
newline$
""
before.all 'output.state :=
}
FUNCTION {n.dashify}
{ 't :=
""
{ t empty$ not }
{ t #1 #1 substring$ "-" =
{ t #1 #2 substring$ "--" = not
{ "--" *
t #2 global.max$ substring$ 't :=
}
{ { t #1 #1 substring$ "-" = }
{ "-" *
t #2 global.max$ substring$ 't :=
}
while$
}
if$
}
{ t #1 #1 substring$ *
t #2 global.max$ substring$ 't :=
}
if$
}
while$
}
FUNCTION {word.in}
{ "In " }
FUNCTION {format.date}
{ year duplicate$ empty$
{ "empty year in " cite$ * "; set to ????" * warning$
pop$ "????" }
'skip$
if$
before.all 'output.state :=
" (" swap$ * extra.label * ")" *
}
FUNCTION {format.btitle}
{ title emphasize
}
FUNCTION {tie.or.space.connect}
{ duplicate$ text.length$ #3 <
{ "~" }
{ " " }
if$
swap$ * *
}
FUNCTION {either.or.check}
{ empty$
'pop$
{ "can't use both " swap$ * " fields in " * cite$ * warning$ }
if$
}
FUNCTION {format.bvolume}
{ volume empty$
{ "" }
{ "volume" volume tie.or.space.connect
series empty$
'skip$
{ " of " * series emphasize * }
if$
"volume and number" number either.or.check
}
if$
}
FUNCTION {format.number.series}
{ volume empty$
{ number empty$
{ series field.or.null }
{ output.state mid.sentence =
{ "number" }
{ "Number" }
if$
number tie.or.space.connect
series empty$
{ "there's a number but no series in " cite$ * warning$ }
{ " in " * series * }
if$
}
if$
}
{ "" }
if$
}
FUNCTION {format.edition}
{ edition empty$
{ "" }
{ output.state mid.sentence =
{ edition "l" change.case$ " edition" * }
{ edition "t" change.case$ " edition" * }
if$
}
if$
}
INTEGERS { multiresult }
FUNCTION {multi.page.check}
{ 't :=
#0 'multiresult :=
{ multiresult not
t empty$ not
and
}
{ t #1 #1 substring$
duplicate$ "-" =
swap$ duplicate$ "," =
swap$ "+" =
or or
{ #1 'multiresult := }
{ t #2 global.max$ substring$ 't := }
if$
}
while$
multiresult
}
FUNCTION {format.pages}
{ pages empty$
{ "" }
{ pages multi.page.check
{ "pages" pages n.dashify tie.or.space.connect }
{ "page" pages tie.or.space.connect }
if$
}
if$
}
FUNCTION {format.vol.num.pages}
{ volume field.or.null
bolden
number empty$
'skip$
{ "(" number * ")" * *
volume empty$
{ "there's a number but no volume in " cite$ * warning$ }
'skip$
if$
}
if$
pages empty$
'skip$
{ duplicate$ empty$
{ pop$ format.pages }
{ ", " * pages n.dashify * }
if$
}
if$
}
FUNCTION {format.chapter.pages}
{ chapter empty$
'format.pages
{ type empty$
{ "chapter" }
{ type "l" change.case$ }
if$
chapter tie.or.space.connect
pages empty$
'skip$
{ ", " * format.pages * }
if$
}
if$
}
FUNCTION {format.in.ed.booktitle}
{ booktitle empty$
{ "" }
{ editor empty$
{ word.in booktitle emphasize * }
{ word.in format.in.editors * ", " * booktitle emphasize * }
if$
}
if$
}
FUNCTION {format.thesis.type}
{ type empty$
'skip$
{ pop$
type "t" change.case$
}
if$
}
FUNCTION {format.tr.number}
{ type empty$
{ "Technical Report" }
'type
if$
number empty$
{ "t" change.case$ }
{ number tie.or.space.connect }
if$
}
FUNCTION {format.article.crossref}
{
word.in
"\cite{" * crossref * "}" *
}
FUNCTION {format.book.crossref}
{ volume empty$
{ "empty volume in " cite$ * "'s crossref of " * crossref * warning$
word.in
}
{ "Volume" volume tie.or.space.connect
" of " *
}
if$
"\cite{" * crossref * "}" *
}
FUNCTION {format.incoll.inproc.crossref}
{
word.in
"\cite{" * crossref * "}" *
}
FUNCTION {article}
{ output.bibitem
format.authors "author" output.check
author format.key output
format.date "year" output.check
new.block
format.title "title" output.check
new.block
crossref missing$
{ journal emphasize "journal" output.check
format.vol.num.pages output
}
{ format.article.crossref output.nonnull
format.pages output
}
if$
new.block
note output
fin.entry
}
FUNCTION {book}
{ output.bibitem
author empty$
{ format.editors "author and editor" output.check
editor format.key output
}
{ format.authors output.nonnull
crossref missing$
{ "author and editor" editor either.or.check }
'skip$
if$
}
if$
format.date "year" output.check
new.block
format.btitle "title" output.check
crossref missing$
{ format.bvolume output
new.block
format.number.series output
new.sentence
publisher "publisher" output.check
address output
}
{
new.block
format.book.crossref output.nonnull
}
if$
format.edition output
new.block
note output
fin.entry
}
FUNCTION {booklet}
{ output.bibitem
format.authors output
author format.key output
format.date "year" output.check
new.block
format.title "title" output.check
new.block
howpublished output
address output
new.block
note output
fin.entry
}
FUNCTION {inbook}
{ output.bibitem
author empty$
{ format.editors "author and editor" output.check
editor format.key output
}
{ format.authors output.nonnull
crossref missing$
{ "author and editor" editor either.or.check }
'skip$
if$
}
if$
format.date "year" output.check
new.block
format.btitle "title" output.check
crossref missing$
{ format.bvolume output
format.chapter.pages "chapter and pages" output.check
new.block
format.number.series output
new.sentence
publisher "publisher" output.check
address output
}
{ format.chapter.pages "chapter and pages" output.check
new.block
format.book.crossref output.nonnull
}
if$
format.edition output
new.block
note output
fin.entry
}
FUNCTION {incollection}
{ output.bibitem
format.authors "author" output.check
author format.key output
format.date "year" output.check
new.block
format.title "title" output.check
new.block
crossref missing$
{ format.in.ed.booktitle "booktitle" output.check
format.bvolume output
format.number.series output
format.chapter.pages output
new.sentence
publisher "publisher" output.check
address output
format.edition output
}
{ format.incoll.inproc.crossref output.nonnull
format.chapter.pages output
}
if$
new.block
note output
fin.entry
}
FUNCTION {inproceedings}
{ output.bibitem
format.authors "author" output.check
author format.key output
format.date "year" output.check
new.block
format.title "title" output.check
new.block
crossref missing$
{ format.in.ed.booktitle "booktitle" output.check
format.bvolume output
format.number.series output
format.pages output
address output
new.sentence
organization output
publisher output
}
{ format.incoll.inproc.crossref output.nonnull
format.pages output
}
if$
new.block
note output
fin.entry
}
FUNCTION {conference} { inproceedings }
FUNCTION {manual}
{ output.bibitem
format.authors output
author format.key output
format.date "year" output.check
new.block
format.btitle "title" output.check
organization address new.block.checkb
organization output
address output
format.edition output
new.block
note output
fin.entry
}
FUNCTION {mastersthesis}
{ output.bibitem
format.authors "author" output.check
author format.key output
format.date "year" output.check
new.block
format.btitle "title" output.check
new.block
"Master's thesis" format.thesis.type output.nonnull
school "school" output.check
address output
new.block
note output
fin.entry
}
FUNCTION {misc}
{ output.bibitem
format.authors output
author format.key output
format.date "year" output.check
new.block
format.title output
new.block
howpublished output
new.block
note output
fin.entry
}
FUNCTION {phdthesis}
{ output.bibitem
format.authors "author" output.check
author format.key output
format.date "year" output.check
new.block
format.btitle "title" output.check
new.block
"Ph.D. thesis" format.thesis.type output.nonnull
school "school" output.check
address output
new.block
note output
fin.entry
}
FUNCTION {proceedings}
{ output.bibitem
format.editors output
editor format.key output
format.date "year" output.check
new.block
format.btitle "title" output.check
format.bvolume output
format.number.series output
address output
new.sentence
organization output
publisher output
new.block
note output
fin.entry
}
FUNCTION {techreport}
{ output.bibitem
format.authors "author" output.check
author format.key output
format.date "year" output.check
new.block
format.title "title" output.check
new.block
format.tr.number output.nonnull
institution "institution" output.check
address output
new.block
note output
fin.entry
}
FUNCTION {unpublished}
{ output.bibitem
format.authors "author" output.check
author format.key output
format.date "year" output.check
new.block
format.title "title" output.check
new.block
note "note" output.check
fin.entry
}
FUNCTION {default.type} { misc }
MACRO {jan} {"January"}
MACRO {feb} {"February"}
MACRO {mar} {"March"}
MACRO {apr} {"April"}
MACRO {may} {"May"}
MACRO {jun} {"June"}
MACRO {jul} {"July"}
MACRO {aug} {"August"}
MACRO {sep} {"September"}
MACRO {oct} {"October"}
MACRO {nov} {"November"}
MACRO {dec} {"December"}
MACRO {acmcs} {"ACM Computing Surveys"}
MACRO {acta} {"Acta Informatica"}
MACRO {cacm} {"Communications of the ACM"}
MACRO {ibmjrd} {"IBM Journal of Research and Development"}
MACRO {ibmsj} {"IBM Systems Journal"}
MACRO {ieeese} {"IEEE Transactions on Software Engineering"}
MACRO {ieeetc} {"IEEE Transactions on Computers"}
MACRO {ieeetcad}
{"IEEE Transactions on Computer-Aided Design of Integrated Circuits"}
MACRO {ipl} {"Information Processing Letters"}
MACRO {jacm} {"Journal of the ACM"}
MACRO {jcss} {"Journal of Computer and System Sciences"}
MACRO {scp} {"Science of Computer Programming"}
MACRO {sicomp} {"SIAM Journal on Computing"}
MACRO {tocs} {"ACM Transactions on Computer Systems"}
MACRO {tods} {"ACM Transactions on Database Systems"}
MACRO {tog} {"ACM Transactions on Graphics"}
MACRO {toms} {"ACM Transactions on Mathematical Software"}
MACRO {toois} {"ACM Transactions on Office Information Systems"}
MACRO {toplas} {"ACM Transactions on Programming Languages and Systems"}
MACRO {tcs} {"Theoretical Computer Science"}
READ
FUNCTION {sortify}
{ purify$
"l" change.case$
}
INTEGERS { len }
FUNCTION {chop.word}
{ 's :=
'len :=
s #1 len substring$ =
{ s len #1 + global.max$ substring$ }
's
if$
}
FUNCTION {format.lab.names}
{ 's :=
s #1 "{vv~}{ll}" format.name$
s num.names$ duplicate$
#2 >
{ pop$ " " * "et~al." emphasize * }
{ #2 <
'skip$
{ s #2 "{ff }{vv }{ll}{ jj}" format.name$ "others" =
{ " " * "et~al." emphasize * }
{ " and " * s #2 "{vv~}{ll}" format.name$ * }
if$
}
if$
}
if$
}
FUNCTION {author.key.label}
{ author empty$
{ key empty$
{ cite$ #1 #3 substring$ }
'key
if$
}
{ author format.lab.names }
if$
}
FUNCTION {author.editor.key.label}
{ author empty$
{ editor empty$
{ key empty$
{ cite$ #1 #3 substring$ }
'key
if$
}
{ editor format.lab.names }
if$
}
{ author format.lab.names }
if$
}
FUNCTION {editor.key.label}
{ editor empty$
{ key empty$
{ cite$ #1 #3 substring$ }
'key
if$
}
{ editor format.lab.names }
if$
}
FUNCTION {calc.label}
{ type$ "book" =
type$ "inbook" =
or
'author.editor.key.label
{ type$ "proceedings" =
'editor.key.label
'author.key.label
if$
}
if$
"("
*
year duplicate$ empty$
{ pop$ "????" }
{ purify$ #-1 #4 substring$ }
if$
*
'label :=
}
FUNCTION {sort.format.names}
{ 's :=
#1 'nameptr :=
""
s num.names$ 'numnames :=
numnames 'namesleft :=
{ namesleft #0 > }
{ nameptr #1 >
{ " " * }
'skip$
if$
s nameptr
"{vv{ } }{ll{ }}{ f{ }}{ jj{ }}"
format.name$ 't :=
nameptr numnames = t "others" = and
{ "et al" * }
{ numnames #2 > nameptr #2 = and
{ "zzzzzz" * #1 'namesleft := }
{ t sortify * }
if$
}
if$
nameptr #1 + 'nameptr :=
namesleft #1 - 'namesleft :=
}
while$
}
FUNCTION {sort.format.title}
{ 't :=
"A " #2
"An " #3
"The " #4 t chop.word
chop.word
chop.word
sortify
#1 global.max$ substring$
}
FUNCTION {author.sort}
{ author empty$
{ key empty$
{ "to sort, need author or key in " cite$ * warning$
""
}
{ key sortify }
if$
}
{ author sort.format.names }
if$
}
FUNCTION {author.editor.sort}
{ author empty$
{ editor empty$
{ key empty$
{ "to sort, need author, editor, or key in " cite$ * warning$
""
}
{ key sortify }
if$
}
{ editor sort.format.names }
if$
}
{ author sort.format.names }
if$
}
FUNCTION {editor.sort}
{ editor empty$
{ key empty$
{ "to sort, need editor or key in " cite$ * warning$
""
}
{ key sortify }
if$
}
{ editor sort.format.names }
if$
}
FUNCTION {presort}
{ calc.label
label sortify
" "
*
type$ "book" =
type$ "inbook" =
or
'author.editor.sort
{ type$ "proceedings" =
'editor.sort
'author.sort
if$
}
if$
#1 entry.max$ substring$
'sort.label :=
sort.label
*
" "
*
title field.or.null
sort.format.title
*
#1 entry.max$ substring$
'sort.key$ :=
}
ITERATE {presort}
SORT
STRINGS { last.label next.extra }
INTEGERS { last.extra.num }
FUNCTION {initialize.extra.label.stuff}
{ #0 int.to.chr$ 'last.label :=
"" 'next.extra :=
#0 'last.extra.num :=
}
FUNCTION {forward.pass}
{ last.label label =
{ last.extra.num #1 + 'last.extra.num :=
last.extra.num int.to.chr$ 'extra.label :=
}
{ "a" chr.to.int$ 'last.extra.num :=
"" 'extra.label :=
label 'last.label :=
}
if$
}
FUNCTION {reverse.pass}
{ next.extra "b" =
{ "a" 'extra.label := }
'skip$
if$
extra.label 'next.extra :=
label extra.label * 'label :=
}
EXECUTE {initialize.extra.label.stuff}
ITERATE {forward.pass}
REVERSE {reverse.pass}
FUNCTION {bib.sort.order}
{ sort.label
" "
*
year field.or.null sortify
*
" "
*
title field.or.null
sort.format.title
*
#1 entry.max$ substring$
'sort.key$ :=
}
ITERATE {bib.sort.order}
SORT
FUNCTION {begin.bib}
{ preamble$ empty$
'skip$
{ preamble$ write$ newline$ }
if$
"\begin{thebibliography}{}" write$ newline$
}
EXECUTE {begin.bib}
EXECUTE {init.state.consts}
ITERATE {call.type$}
FUNCTION {end.bib}
{ newline$
"\end{thebibliography}" write$ newline$
}
EXECUTE {end.bib}
%% End of customized bst file
================================================
FILE: pdf/.gitignore
================================================
# Ignore everything in this directory
*
# Except this file
!.gitignore
================================================
FILE: png/.gitignore
================================================
# Ignore everything in this directory
*
# Except this file
!.gitignore
================================================
FILE: templates/arithmetic_figure.txt
================================================
\documentclass[class=minimal,border=10pt]{{standalone}}
\usepackage{{tikz}}
\usepackage{{xcolor}}
\definecolor{{blue}}{{RGB}}{{38,139,210}}
\definecolor{{cyan}}{{RGB}}{{42,161,152}}
\definecolor{{base01}}{{RGB}}{{88,110,117}}
\definecolor{{base02}}{{RGB}}{{7,54,66}}
\definecolor{{base03}}{{RGB}}{{0,43,54}}
\usetikzlibrary{{calc,shapes,positioning}}
\begin{{document}}
\begin{{tikzpicture}}[scale=.5,every node/.style={{minimum size=1cm}},on grid]
\begin{{scope}}[node/.append style={{yslant=0.5,xslant=-0.7}},
yslant=0.5,xslant=-0.7]
\draw[step=10mm, base03, dashed, thick] (0,0) grid ({PADDING_TO});
{INPUT_UNITS}
\foreach \x in {{ {INPUT_GRID_FROM_X},\number\numexpr {INPUT_GRID_FROM_X}+{DILATION},...,\number\numexpr {INPUT_GRID_TO_X}-1 }} {{
\foreach \y in {{ {INPUT_GRID_FROM_Y},\number\numexpr {INPUT_GRID_FROM_Y}+{DILATION},...,\number\numexpr {INPUT_GRID_TO_Y}-1 }} {{
\draw[fill=base02, opacity=0.4] (\x,\y) rectangle
(\x+1,\y+1);
}}
}}
\draw[step=10mm, base03, thick] ({INPUT_GRID_FROM_X}, {INPUT_GRID_FROM_Y}) grid
({INPUT_GRID_TO_X}, {INPUT_GRID_TO_Y});
\coordinate (BL) at ({INPUT_GRID_FROM_X},{INPUT_GRID_FROM_Y});
\coordinate (BR) at ({INPUT_GRID_TO_X},{INPUT_GRID_FROM_Y});
\coordinate (TL) at ({INPUT_GRID_FROM_X},{INPUT_GRID_TO_Y});
\coordinate (TR) at ({INPUT_GRID_TO_X},{INPUT_GRID_TO_Y});
\end{{scope}}
\begin{{scope}}[xshift=-5, yshift={OUTPUT_ELEVATION},
every node/.append style={{yslant=0.5,xslant=-0.7}},
yslant=0.5,xslant=-0.7]
\draw (BL) -- ({OUTPUT_BOTTOM_LEFT}) (BR) -- ({OUTPUT_BOTTOM_RIGHT})
(TL) -- ({OUTPUT_TOP_LEFT}) (TR) -- ({OUTPUT_TOP_RIGHT});
\draw[fill=cyan] (0,0) rectangle ({OUTPUT_TO});
\draw[step=10mm, base03, thick] (0,0) grid ({OUTPUT_TO});
\draw[fill=base02, opacity=0.4] ({OUTPUT_GRID_FROM}) rectangle
({OUTPUT_GRID_TO});
\draw[base03, thick] ({OUTPUT_GRID_FROM}) rectangle ({OUTPUT_GRID_TO});
\end{{scope}}
\end{{tikzpicture}}
\end{{document}}
================================================
FILE: templates/numerical_figure.txt
================================================
\documentclass[class=article,border=10pt]{{standalone}}
\usepackage{{tikz}}
\usepackage{{xcolor}}
\definecolor{{blue}}{{RGB}}{{38,139,210}}
\definecolor{{cyan}}{{RGB}}{{42,161,152}}
\definecolor{{base01}}{{RGB}}{{88,110,117}}
\definecolor{{base02}}{{RGB}}{{7,54,66}}
\definecolor{{base03}}{{RGB}}{{0,43,54}}
\usetikzlibrary{{calc,shapes,positioning}}
\begin{{document}}
\begin{{tikzpicture}}[scale=.5,every node/.style={{minimum size=1cm}},on grid]
\begin{{scope}}
\draw[step=10mm, base03, dashed, thick] (0,0) grid ({PADDING_TO});
\draw[fill=blue] ({INPUT_FROM}) rectangle ({INPUT_TO});
\draw[draw=base03, thick] ({INPUT_FROM}) grid ({INPUT_TO});
{INPUT_VALUES}
\draw[fill=base02, opacity=0.4] ({INPUT_GRID_FROM}) rectangle
({INPUT_GRID_TO});
\draw[step=10mm, base03, thick] ({INPUT_GRID_FROM}) grid
({INPUT_GRID_TO});
{KERNEL_VALUES}
\end{{scope}}
\begin{{scope}}[xshift={XSHIFT}, yshift={YSHIFT}]
\draw[fill=cyan] (0,0) rectangle ({OUTPUT_TO});
\draw[step=10mm, base03, thick] (0,0) grid ({OUTPUT_TO});
\draw[fill=base02, opacity=0.4] ({OUTPUT_GRID_FROM}) rectangle
({OUTPUT_GRID_TO});
\draw[base03, thick] ({OUTPUT_GRID_FROM}) rectangle ({OUTPUT_GRID_TO});
{OUTPUT_VALUES}
\end{{scope}}
\end{{tikzpicture}}
\end{{document}}
================================================
FILE: templates/unit.txt
================================================
\draw[draw=base03, fill=blue, thick] ({0},{1}) rectangle ({2},{3});