How to use nn.conv2d to do the same function as nn.conv1d?

Viewed 108

I'm working on deploying python CNNs on FPGAs, and i'm facing an issue.

I have a 1d CNN which uses torch.conv1d layer function, and it's not supported by the software I'm using :vitis-ai 1.3.

I'm figuring out if there is some way to use nn.conv2d instead to do the same job as nn.conv1d ?

for example :

Conv1d(1, 32, 3, bias = True) => Conv2d(... 

Is there a way to do that ? (without loosing too much performance ?)

Thank you.

1 Answers

Given 1d input, a 2d convolution of kernel-size (n,1) is equivalent to a 1d convolution of kernel-size (n,):

nn.Conv1d(in_channels, out_channels, n)

# for 1d input, is equivalent to:
nn.Conv2d(in_channels, out_channels, (n,1))

Note you will have to unsqueeze(-1) the input to get it of the correct shape for a 2d convolution, but you can return the output to the original shape by applying squeeze(-1):

F.conv1d(inputs, filters)

# is equivalent to:
F.conv2d(inputs.unsqueeze(-1), filters.unsqueeze(-1)).squeeze(-1)
Related