• Tutorials >
  • Creating Extensions Using numpy and scipy
Shortcuts

Creating Extensions Using numpy and scipy

Author: Adam Paszke

Updated by: Adam Dziedzic [https://github.com/adam-dziedzic](https://github.com/adam-dziedzic)

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 its implementation
  2. Create a neural network layer that has learnable weights

    • This calls into SciPy as part of its implementation
import torch
from torch.autograd import Function

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.detach().numpy()
        result = abs(rfft2(numpy_input))
        return input.new(result)

    def backward(self, grad_output):
        numpy_go = grad_output.numpy()
        result = irfft2(numpy_go)
        return grad_output.new(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 = torch.randn(8, 8, requires_grad=True)
result = incorrect_fft(input)
print(result)
result.backward(torch.randn(result.size()))
print(input)

Out:

tensor([[ 4.8735, 12.1291,  3.7460,  7.7482,  7.9410],
        [ 5.1553,  3.9722, 12.0110,  7.9523,  2.7573],
        [ 9.4271, 11.9712,  8.4059, 10.8257,  5.6409],
        [12.1190,  2.6272,  4.3462,  8.3785, 10.3529],
        [ 4.2619,  2.1719,  6.3972,  4.5252, 12.1059],
        [12.1190,  8.3360,  2.8271,  6.3498, 10.3529],
        [ 9.4271, 18.3240,  7.3633, 15.9720,  5.6409],
        [ 5.1553, 10.8438,  5.7911, 10.0476,  2.7573]],
       grad_fn=<BadFFTFunction>)
tensor([[-0.5130, -0.7820,  0.3714,  0.8337,  0.0923, -0.8044,  0.8153,  0.0826],
        [-0.7871, -1.5088, -0.4812, -0.1054, -0.8669,  1.0083,  0.3710, -1.3813],
        [ 0.6153,  1.3572,  0.6628, -1.6567,  0.3257,  0.0664,  1.5548,  0.2656],
        [ 0.7784,  1.1006, -0.8864, -1.7474, -1.3494,  0.2364,  0.4411,  1.7943],
        [ 3.0318, -2.3043, -0.3941,  0.2281, -1.8222, -1.8517,  0.3198, -1.3328],
        [ 0.3614, -0.1899, -1.0093,  2.5918,  0.1925, -0.7544, -0.5647, -1.4072],
        [-0.6117, -1.1147, -1.0903, -0.1836, -1.1107, -0.3566,  0.4807,  0.2578],
        [ 0.7198,  0.7797,  0.4050, -1.8800,  0.7276,  0.3205,  0.7540,  2.0313]],
       requires_grad=True)

Parametrized example

In deep learning literature, this layer is confusingly referred to as convolution while the actual operation is cross-correlation (the only difference is that filter is flipped for convolution, which is not the case for cross-correlation).

Implementation of a layer with learnable weights, where cross-correlation has a filter (kernel) that represents weights.

The backward pass computes the gradient wrt the input and the gradient wrt the filter.

from numpy import flip
import numpy as np
from scipy.signal import convolve2d, correlate2d
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter


class ScipyConv2dFunction(Function):
    @staticmethod
    def forward(ctx, input, filter, bias):
        # detach so we can cast to NumPy
        input, filter, bias = input.detach(), filter.detach(), bias.detach()
        result = correlate2d(input.numpy(), filter.numpy(), mode='valid')
        result += bias.numpy()
        ctx.save_for_backward(input, filter, bias)
        return torch.as_tensor(result, dtype=input.dtype)

    @staticmethod
    def backward(ctx, grad_output):
        grad_output = grad_output.detach()
        input, filter, bias = ctx.saved_tensors
        grad_output = grad_output.numpy()
        grad_bias = np.sum(grad_output, keepdims=True)
        grad_input = convolve2d(grad_output, filter.numpy(), mode='full')
        # the previous line can be expressed equivalently as:
        # grad_input = correlate2d(grad_output, flip(flip(filter.numpy(), axis=0), axis=1), mode='full')
        grad_filter = correlate2d(input.numpy(), grad_output, mode='valid')
        return torch.from_numpy(grad_input), torch.from_numpy(grad_filter).to(torch.float), torch.from_numpy(grad_bias).to(torch.float)


class ScipyConv2d(Module):
    def __init__(self, filter_width, filter_height):
        super(ScipyConv2d, self).__init__()
        self.filter = Parameter(torch.randn(filter_width, filter_height))
        self.bias = Parameter(torch.randn(1, 1))

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

Example usage:

module = ScipyConv2d(3, 3)
print("Filter and bias: ", list(module.parameters()))
input = torch.randn(10, 10, requires_grad=True)
output = module(input)
print("Output from the convolution: ", output)
output.backward(torch.randn(8, 8))
print("Gradient for the input map: ", input.grad)

Out:

Filter and bias:  [Parameter containing:
tensor([[-0.2758,  1.9346, -1.9694],
        [-1.2474,  0.1557,  0.1355],
        [ 0.3089,  0.7792,  1.7595]], requires_grad=True), Parameter containing:
tensor([[-1.1192]], requires_grad=True)]
Output from the convolution:  tensor([[-7.3545, -1.2918, -5.7828, -6.4215,  2.9662, -2.3252, -5.3455, -2.3127],
        [ 1.1332, -5.1095,  7.7161, -3.5969,  4.2600, -4.8005, -1.7162, -3.9028],
        [ 2.9619, -3.4818, -4.8507, -2.9417, -2.3452,  1.1581,  1.8444, -4.6705],
        [-1.9034, -2.7889, -2.2307,  0.3973, -2.4607,  0.0377, -0.6851, -4.2134],
        [-3.9216, -6.9418,  0.7974, -3.2162, -2.4771, -2.8320,  6.1140, -2.0747],
        [ 0.9941, -1.2850,  2.1417,  0.6502,  0.4682, -3.9046, -3.6512, -1.1124],
        [ 2.0453, -4.3914, -6.2399,  1.4872, -3.5229,  0.1574, -1.1507,  6.1194],
        [-2.9055, -8.4967,  2.7068,  3.1578, -2.7134, -1.5992, -1.8850, -2.6313]],
       grad_fn=<ScipyConv2dFunctionBackward>)
Gradient for the input map:  tensor([[-0.1455,  0.8676,  0.0531, -0.8233, -3.1221,  6.4166, -4.1033, -1.5106,
          2.6236, -0.1999],
        [-0.2326, -3.2061,  0.4094,  5.0855, -0.7828, -0.8459,  1.8058, -2.4523,
         -1.5831,  2.2959],
        [ 1.8455,  4.1280, -4.0440,  4.7818, -8.3334, -1.4167,  6.2530,  1.1928,
         -0.6284, -3.2514],
        [-1.8103,  1.5409, -8.1225,  4.7636,  0.5309,  3.4917,  0.0848,  0.5280,
         -2.7089, -2.5988],
        [-0.8854,  0.7193,  1.0787, -4.4136,  1.2911, -7.5726,  0.8132, -2.4433,
          2.1421,  3.7049],
        [ 0.0246, -2.5310,  4.1275,  2.6974,  5.0401, -2.8416,  3.0113, -0.0360,
          1.9253,  1.3305],
        [ 1.1933, -0.5125,  2.0783,  2.1520,  0.9076, -5.1077,  1.7382, -0.3144,
         -0.4897,  2.3897],
        [ 1.1258, -4.9604,  3.7265, -3.1804,  3.2703,  1.2288, -0.4531,  7.5333,
         -3.8946, -1.0813],
        [ 2.5889, -1.2430, -0.2412,  0.2085,  0.3203,  2.5808, -2.9457, -0.7575,
         -3.5748, -2.7387],
        [-0.6865, -1.6301, -3.9154, -0.0706, -1.3219,  0.1884,  0.7318,  0.0064,
          2.8918,  0.2344]])

Check the gradients:

from torch.autograd.gradcheck import gradcheck

moduleConv = ScipyConv2d(3, 3)

input = [torch.randn(20, 20, dtype=torch.double, requires_grad=True)]
test = gradcheck(moduleConv, input, eps=1e-6, atol=1e-4)
print("Are the gradients correct: ", test)

Out:

Are the gradients correct:  True

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

Gallery generated by Sphinx-Gallery

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources