Creating extensions using numpy and scipy

Author: Adam Paszke

In this tutorial, we shall go through two tasks:

  1. Create a neural network layer with no parameters.

    • This calls into numpy as part of it’s implementation
  2. Create a neural network layer that has learnable weights

    • This calls into SciPy as part of it’s implementation
import torch
from torch.autograd import Function
from torch.autograd import Variable

Parameter-less example

This layer doesn’t particularly do anything useful or mathematically correct.

It is aptly named BadFFTFunction

Layer Implementation

from numpy.fft import rfft2, irfft2


class BadFFTFunction(Function):

    def forward(self, input):
        numpy_input = input.numpy()
        result = abs(rfft2(numpy_input))
        return torch.FloatTensor(result)

    def backward(self, grad_output):
        numpy_go = grad_output.numpy()
        result = irfft2(numpy_go)
        return torch.FloatTensor(result)

# since this layer does not have any parameters, we can
# simply declare this as a function, rather than as an nn.Module class


def incorrect_fft(input):
    return BadFFTFunction()(input)

Example usage of the created layer:

input = Variable(torch.randn(8, 8), requires_grad=True)
result = incorrect_fft(input)
print(result.data)
result.backward(torch.randn(result.size()))
print(input.grad)

Out:

20.1997   5.1008   1.4327   7.4462   9.6989
  4.0786   7.5101   5.1218   2.9514  10.2165
 11.4993   9.0001   6.8640   4.9923   5.9637
  2.1148   1.1874   8.0125   5.0989   4.0037
  7.2239  16.1796   9.1793   2.5649   5.4271
  2.1148   6.9877   4.9656   5.7910   4.0037
 11.4993   2.2513  17.7885  12.2230   5.9637
  4.0786   4.1140  13.0560   4.3760  10.2165
[torch.FloatTensor of size 8x5]

Variable containing:
-0.2249  0.0523 -0.1097 -0.0235  0.4490 -0.0235 -0.1097  0.0523
 0.0569 -0.0214 -0.0195 -0.1150  0.1565  0.0548  0.1332  0.0863
-0.2216 -0.2317 -0.1265  0.1342 -0.0734  0.1571 -0.0169 -0.0149
 0.0095  0.0788  0.2745 -0.0279 -0.0373 -0.0253  0.0942  0.1071
 0.0983 -0.0232 -0.0070  0.2548 -0.2377  0.2548 -0.0070 -0.0232
 0.0095  0.1071  0.0942 -0.0253 -0.0373 -0.0279  0.2745  0.0788
-0.2216 -0.0149 -0.0169  0.1571 -0.0734  0.1342 -0.1265 -0.2317
 0.0569  0.0863  0.1332  0.0548  0.1565 -0.1150 -0.0195 -0.0214
[torch.FloatTensor of size 8x8]

Parametrized example

This implements a layer with learnable weights.

It implements the Cross-correlation with a learnable kernel.

In deep learning literature, it’s confusingly referred to as Convolution.

The backward computes the gradients wrt the input and gradients wrt the filter.

Implementation:

Please Note that the implementation serves as an illustration, and we did not verify it’s correctness

from scipy.signal import convolve2d, correlate2d
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter


class ScipyConv2dFunction(Function):

    def forward(self, input, filter):
        result = correlate2d(input.numpy(), filter.numpy(), mode='valid')
        self.save_for_backward(input, filter)
        return torch.FloatTensor(result)

    def backward(self, grad_output):
        input, filter = self.saved_tensors
        grad_input = convolve2d(grad_output.numpy(), filter.t().numpy(), mode='full')
        grad_filter = convolve2d(input.numpy(), grad_output.numpy(), mode='valid')
        return torch.FloatTensor(grad_input), torch.FloatTensor(grad_filter)


class ScipyConv2d(Module):

    def __init__(self, kh, kw):
        super(ScipyConv2d, self).__init__()
        self.filter = Parameter(torch.randn(kh, kw))

    def forward(self, input):
        return ScipyConv2dFunction()(input, self.filter)

Example usage:

module = ScipyConv2d(3, 3)
print(list(module.parameters()))
input = Variable(torch.randn(10, 10), requires_grad=True)
output = module(input)
print(output)
output.backward(torch.randn(8, 8))
print(input.grad)

Out:

[Parameter containing:
 1.9289  0.3935 -0.5973
-0.7732 -0.6008  0.7107
-1.0488 -0.9177 -1.5095
[torch.FloatTensor of size 3x3]
]
Variable containing:
-1.7179 -1.9352 -3.8154 -0.3988 -0.7005 -2.7746  0.0806  3.5019
 5.0286  3.6790 -0.9014 -3.8993 -4.5629  2.0165 -0.3009 -2.5673
 3.4704  2.7994  0.0172  0.6726  1.0561 -1.7217  0.2245  1.6227
-2.9827 -4.5966 -5.1890  1.0816  3.2722  2.0411  0.8476 -5.1022
-0.1915  3.3556  1.3115  4.5768 -0.9872 -4.3034 -0.4047  1.4850
-3.6360 -5.4964  5.9710  0.4596 -1.3029 -3.9416 -1.2930  1.1693
 5.2405  0.3854 -4.3478  0.8101  4.5782  2.5700  2.0663  2.1214
-3.7382  1.8291 -0.9240 -3.3267 -0.2852  6.8937  2.0471  4.2930
[torch.FloatTensor of size 8x8]

Variable containing:
 0.0701  3.7943 -5.3995  0.1075 -0.8927  4.3481 -1.7648 -1.1580  0.9385 -0.0484
 0.6156 -0.8809  1.8861 -0.2474  0.8478  0.8405 -1.3164 -1.9256  0.6255  0.0080
-2.4246 -2.9191  9.0698 -3.2110  0.6424 -5.5314  5.6483 -5.1848 -0.2290  0.1302
 0.1499 -2.6571  1.1759  4.9767 -5.3916 -0.2154 -2.0760 -0.5326 -1.8853 -0.4672
 5.6177 -2.3086 -5.2561  7.1254 -3.2097 -2.7601 -0.6180  4.3432 -3.3999 -1.4951
 0.1272 -3.0202 -2.2108  4.6327 -0.0119 -3.3254 -0.7807  1.4626  2.4542 -1.7276
-1.6061  1.3392 -1.3962 -2.7647  0.6007  0.3763  4.3952  2.2063  1.4883 -1.6710
-1.3541 -0.0262 -0.3653  5.0409 -5.5391  7.0570  1.3683 -4.5092  4.3295  1.8065
-0.2947  0.0471  1.3559  1.2816 -0.3027  1.4178  2.7249 -1.2063  0.8268  1.1194
 0.4700 -0.0884  0.7969  0.5650  2.3180 -3.8346  5.5531 -2.7143  0.6782  2.4351
[torch.FloatTensor of size 10x10]

Total running time of the script: ( 0 minutes 2.893 seconds)

Generated by Sphinx-Gallery