Skip to content

Feature Request: Locally Connected Layer #499

Open

Description

@ronrest

The Lua version of Torch implements a Locally Connected Layer (Convolution without shared weights). It would be good to have an implementation of this available on the python API version as well.

cc @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki @kshitij12345

Activity

  1. 1zb commented on May 17, 2017

    @1zb

    I came up with the same issue and found torch.nn.backends.thnn.backend.SpatialConvolutionLocal.

    For anyone who want to use locally connected layer in PyTorch,

    inputs=Variable(torch.randn(1,3,32,32)) # N x inC x inH x inW
    weight=Variable(torch.randn(30,30,64,3,3,3)) # outH x outW x outC x inC x kH x kW
    bias=Variable(torch.randn(64,30,30)) # outC x outH x outW
    
    ## arguments: kH, kW, strideH, strideW, padH, padW, inH, inW, outH, outW
    local=torch.nn.backends.thnn.backend.SpatialConvolutionLocal(3, 3, 1, 1, 0, 0, 32, 32, 30, 30)
    outputs=local(inputs, weight, bias) # N x outC x outH x outW
  2. apaszke commented on May 17, 2017

    @apaszke
    Contributor

    This should be easy to add once #1048 is implemented

  3. apaszke commented on May 17, 2017

    @apaszke
    Contributor

    Oh, if the auto-generated function works then we can expose it. @1zb can you send a PR that creates a module to do it? You can base the implementation on other Conv* modules, and use the function you found in forward

  4. 1zb commented on May 18, 2017

    @1zb

    Sure, I am happy to do this.

  5. ibulu commented on Apr 10, 2018

    @ibulu

    I would like to request the same for 1D data, Conv1DLocal?

  6. bwesen commented on Apr 16, 2018

    @bwesen

    Beware that the torch.nn.backends.thnn.backend.SpatialConvolutionLocal function mentioned above is very slow, feeding it batches you get no parallelisation (minibatch of 10 is 10x the time of a 1 batch). At least in pyTorch 0.3.1. Other high-level methods using Unfold seem to work better.

  7. added
    proposal accepted
    on Apr 16, 2018
  8. kausic94 commented on Aug 7, 2018

    @kausic94

    @1zb
    I try this, but it say that required arguement bias is missing despite it being present. Do you know what the problem could be?

    ## arguments: kH, kW, strideH, strideW, padH, padW, inH, inW, outH, outW
    local=torch.nn.backends.thnn.backend.SpatialConvolutionLocal(3, 3, 1, 1, 0, 0, 32, 32, 30, 30)
    outputs=local(inputs, weight, bias) # N x outC x outH x outW
    
  9. sorenchiron commented on Oct 11, 2018

    @sorenchiron

    Saddly, neither of torch.nn.backends.thnn.backend.SpatialConvolutionLocal nor torch.nn._functions.thnn.SpatialConvolutionLocal works for pyTorch 0.4.0.

    directly calling local(x,w,b) yields:

    lib\site-packages\torch\nn\_functions\thnn\auto.py in forward(ctx, input, *params)
        173                 args += (None,)
        174             else:
    --> 175                 raise ValueError("missing required argument '%s'" % param.name)
        176
        177         args += tuple(additional_args)
    
    ValueError: missing required argument 'bias'
    

    That's because, as mentioned in This doc, invoking local.forward(ctx,inputs, *params) requires a ctx (SpatialConvolutionLocalBackward object here) , which by the documentation is sth not supposed to be handled by users creating extensions.

    On the other hand, the correct way of invoking forward is explained in Doc: Anomaly detection example, which is by local.apply(x,w,b)

    Saddly again, the outcomes of calling local.apply(x,w,b) is :

    \lib\site-packages\torch\nn\_functions\thnn\auto.py in forward(ctx, input, *params)
        193             del ctx.buffers
        194
    --> 195         getattr(ctx._backend, update_output.name)(ctx._backend.library_state, input, output, *args)
        196         return output
        197
    
    TypeError: FloatSpatialConvolutionLocal_updateOutput received an invalid combination of arguments - got (int, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor), but expected (int state, torch.FloatTensor input, torch.FloatTensor output, torch.FloatTensor weight, torch.FloatTensor bias, torch.FloatTensor finput, torch.FloatTensor fgradInput, int kW, int kH, int dW, int dH, int padW, int padH, int inputWidth, int inputHeight, int outputWidth, int outputHeight)
    

    By hacking around auto.py, I found that it is not the problem of the input (x,w,b) or args kW,dW,dH... which are of the exact required type torch.FloatTensor. The problem lays in some hidden builtin functions that were designed to generate (int, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) params.

    Hope that there will be a more general ConvBase class that provides ways to define cuda accelerated spatial iterations. Providing this ConvBase might satisfy most of the Conv-related feature-requirement issues. Since end users know math well. Rather than asking busy developers to implement well-known LocalConv, maybe users only want simple access to performance, which is what they cannot achieve by themselves except by experting cuda nvcc.

    Most obviously, given ConvBase, I myself can contribute almost all kinds of special Conv layers.
    Perhaps, users may feel good if pyTorch ask them to do the math, providing high-performance friendly API.
    But it's possible that users may feel bad if pyTorch is slow, and they have to wait until the all-known math is implemented by overworked/tired developers using the parallel APIs that the user actually need.

  10. bwesen commented on Oct 12, 2018

    @bwesen

    I was also hit by this breakage, and ended up re-learning CUDA and wrote the kernels I needed myself and added them as pyTorch extensions. This turned out to be far less work than I spent trying to figure out how to mash the other tensor functions together to do the same thing and it was 10-20x faster as well than those functions even while they worked (the im2col-based unfold things). Mainly due to the massive memory usage of the latter (it has to keep an intermediary gigantonourmous array in RAM).

    But for a general case, building up functions to work in a library with multiple frontends and backends, it's much more work than for the very specific fixed kernels I needed. I guess my point being, if you have a specific case that doesn't need flexibility, adding a cuda extension is not as hard as it might seem.

  11. shir994 commented on Oct 16, 2018

    @shir994

    I was playing around with PyTorch unfold operation. If I understand correctly, LocalConv2d could be done, if we first use torch.nn.Unfold, and then apply element-wise multiplication of kernel with different weights to each of the last dimension and then sum over first unfolded dimension. I think, it could be implemented as follows, as very ad-hoc approach:

    class LocallyConnected2d(nn.Module):
        def calculate_spatial_output_shape(self, input_shape, kernel_size, dilation, padding, stride):
            return [np.floor((input_shape[index] + 2 * padding[index] - dilation[index] * (kernel_size[index] - 1) - 1) /
                    stride[index] + 1).astype(int) for index in range(len(input_shape))]
        
        def __init__(self, input_shape, in_channels, out_channels, kernel_size, dilation=(1,1), padding=(0,0), stride=(1,1)):
            super().__init__()
            self.kernel_size = kernel_size
            self.out_channels = out_channels
            self.dilation = dilation
            self.padding = padding
            self.stride = stride
            
            self.output_height, self.output_width = self.calculate_spatial_output_shape(input_shape, kernel_size,
                                                                                   dilation, padding, stride)
            self.weight_tensor_depth = in_channels * kernel_size[0] * kernel_size[1]
            self.spatial_blocks_size = self.output_height * self.output_width
            self.weights = nn.Parameter(torch.empty((1, self.weight_tensor_depth, self.spatial_blocks_size, out_channels),
                                       requires_grad=True, dtype=torch.float))
            self.bias = nn.Parameter(torch.empty((1, out_channels, self.output_height, self.output_width),
                                    requires_grad=True, dtype=torch.float))
            
            torch.nn.init.xavier_uniform_(self.weights)
            torch.nn.init.xavier_uniform_(self.bias)
            
        def forward(self, input):
            input_unf = torch.nn.functional.unfold(input, self.kernel_size, dilation=self.dilation,
                                                   padding=self.padding, stride=self.stride)
            local_conv_unf = (input_unf.view((*input_unf.shape, 1)) * self.weights)
            return local_conv_unf.sum(dim=1).transpose(2, 1).reshape(
                                            (-1, self.out_channels, self.output_height, self.output_width)) + self.bias
    

    Although, I am very suspicious about speed performance of such implementation, since I do no use any of raw PyTorch backend methods.

  12. bwesen commented on Oct 16, 2018

    @bwesen

    My conv2d_local function I used before rewriting it in custom CUDA, if anyone is interested. It's actually from an unmerged PR somewhere else here.

    Note that it's extremely slow and memory-inefficient to use im2col. It's surely easy and flexible, but it requires the GPU to unpack all the overlapping kernel possibilities in the input array to an intermediary storage and then apply the weight matrix in that space. Doing it "in place" in RAM is about 100x faster (yes, I benchmarked it). For small arrays I'm sure there's much less difference though.

    # This is from this unmerged PR:
    # https://github.com/pytorch/pytorch/pull/1583
    
    def conv2d_local(input, weight, bias=None, padding=0, stride=1, dilation=1):
        if input.dim() != 4:
            raise NotImplementedError("Input Error: Only 4D input Tensors supported (got {}D)".format(input.dim()))
        if weight.dim() != 6:
            # outH x outW x outC x inC x kH x kW
            raise NotImplementedError("Input Error: Only 6D weight Tensors supported (got {}D)".format(weight.dim()))
    
        outH, outW, outC, inC, kH, kW = weight.size()
        kernel_size = (kH, kW)
    
        # TODO: this requires a huge amount of temporary RAM, for the unfold and matmul.
        
        # N x [inC * kH * kW] x [outH * outW]
        cols = torch.nn.functional.unfold(input, kernel_size, dilation=dilation, padding=padding, stride=stride)
        cols = cols.view(cols.size(0), cols.size(1), cols.size(2), 1).permute(0, 2, 3, 1)
        
        out = torch.matmul(cols, weight.view(outH * outW, outC, inC * kH * kW).permute(0, 2, 1))
        out = out.view(cols.size(0), outH, outW, outC).permute(0, 3, 1, 2)
        
        if bias is not None:
            out = out + bias.expand_as(out)
        return out
    
  13. 14 remaining items

  14. grau4 commented on Dec 7, 2022

    @grau4

    Any progress in Dec-2022?

  15. yw5aj commented on Jan 29, 2023

    @yw5aj

    Any helping hand would be appreciated... Jan 2023 :(

  16. DanielWicz commented on Jan 30, 2023

    @DanielWicz

    Waiting :-)

  17. bramgrooten commented on Mar 24, 2023

    @bramgrooten

    I would love to see this as well!

  18. YonatanSimson commented on Sep 11, 2023

    @YonatanSimson

    Any news?

  19. dxiaalign commented on Nov 6, 2023

    @dxiaalign

    Any progress in Nov-2023?

  20. whubaichuan commented on Apr 15, 2024

    @whubaichuan

    Any progress in April-2024?

    It seems SpatialConvolutionLocal is not available in PyTorch now. @ronrest @apaszke

  21. RainyEthan commented on Sep 7, 2026

    @RainyEthan

    +1

  22. added a commit that references this issue on Sep 28, 2026
  23. added
    needs research
    and removed
    proposal accepted
    on Sep 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featuremodule: nnneeds researchtriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions