You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
featureA request for a proper, new feature.module: nnRelated to torch.nnneeds researchWe need to decide whether or not this merits inclusion, based on research worldtriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module
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.
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 inWweight=Variable(torch.randn(30,30,64,3,3,3)) # outH x outW x outC x inC x kH x kWbias=Variable(torch.randn(64,30,30)) # outC x outH x outW## arguments: kH, kW, strideH, strideW, padH, padW, inH, inW, outH, outWlocal=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
Reacted by Alex Rogozhnikov, Michael Carlon, BW, wranai, Magicyu-2015, Gavin Wang and Yonatan Simson
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
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.
Saddly, neither of torch.nn.backends.thnn.backend.SpatialConvolutionLocal nor torch.nn._functions.thnn.SpatialConvolutionLocal works for pyTorch 0.4.0.
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.
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.
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:
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
featureA request for a proper, new feature.module: nnRelated to torch.nnneeds researchWe need to decide whether or not this merits inclusion, based on research worldtriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module
Activity
1zb commentedon May 17, 2017
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,
apaszke commentedon May 17, 2017
This should be easy to add once #1048 is implemented
apaszke commentedon May 17, 2017
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 inforward1zb commentedon May 18, 2017
Sure, I am happy to do this.
ibulu commentedon Apr 10, 2018
I would like to request the same for 1D data, Conv1DLocal?
bwesen commentedon Apr 16, 2018
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.
kausic94 commentedon Aug 7, 2018
@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?
sorenchiron commentedon Oct 11, 2018
Saddly, neither of
torch.nn.backends.thnn.backend.SpatialConvolutionLocalnortorch.nn._functions.thnn.SpatialConvolutionLocalworks for pyTorch 0.4.0.directly calling
local(x,w,b)yields: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 :By hacking around
auto.py, I found that it is not the problem of the input(x,w,b)or argskW,dW,dH...which are of the exact required typetorch.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
ConvBaseclass that provides ways to define cuda accelerated spatial iterations. Providing thisConvBasemight satisfy most of the Conv-related feature-requirement issues. Since end users know math well. Rather than asking busy developers to implement well-knownLocalConv, 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.
bwesen commentedon Oct 12, 2018
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.
shir994 commentedon Oct 16, 2018
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:
Although, I am very suspicious about speed performance of such implementation, since I do no use any of raw PyTorch backend methods.
bwesen commentedon Oct 16, 2018
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.
14 remaining items
grau4 commentedon Dec 7, 2022
Any progress in Dec-2022?
yw5aj commentedon Jan 29, 2023
Any helping hand would be appreciated... Jan 2023 :(
DanielWicz commentedon Jan 30, 2023
Waiting :-)
bramgrooten commentedon Mar 24, 2023
I would love to see this as well!
YonatanSimson commentedon Sep 11, 2023
Any news?
dxiaalign commentedon Nov 6, 2023
Any progress in Nov-2023?
whubaichuan commentedon Apr 15, 2024
Any progress in April-2024?
It seems SpatialConvolutionLocal is not available in PyTorch now. @ronrest @apaszke
RainyEthan commentedon Sep 7, 2026
+1
Add _conv2d_local native function