Skip to content

Instantly share code, notes, and snippets.

@bdsaglam
Last active January 31, 2025 09:38
Show Gist options
  • Select an option

  • Save bdsaglam/84b1e1ba848381848ac0a308bfe0d84c to your computer and use it in GitHub Desktop.

Select an option

Save bdsaglam/84b1e1ba848381848ac0a308bfe0d84c to your computer and use it in GitHub Desktop.
Separable 2D Convolution PyTorch
class SeparableConv2d(torch.nn.Module):
def __init__(self,
in_channels,
out_channels,
kernel_size=3,
stride=1,
padding=0,
dilation=1,
bias=True,
padding_mode='zeros',
depth_multiplier=1,
):
super().__init__()
intermediate_channels = in_channels * depth_multiplier
self.spatialConv = torch.nn.Conv2d(
in_channels=in_channels,
out_channels=intermediate_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=in_channels,
bias=bias,
padding_mode=padding_mode
)
self.pointConv = torch.nn.Conv2d(
in_channels=intermediate_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0,
dilation=1,
bias=bias,
padding_mode=padding_mode,
)
def forward(self, x):
return self.pointConv(self.spatialConv(x))
@tejan-rgb

Copy link
Copy Markdown

Hi, can you please explain why in

self.spatialConv = torch.nn.Conv2d(
             in_channels=in_channels,
             out_channels=intermediate_channels,
             kernel_size=kernel_size,
             stride=stride,
             padding=padding,
             dilation=dilation,
             groups=in_channels,
             bias=bias,
             padding_mode=padding_mode

groups=in_channels?

@MaloOLIVIER

Copy link
Copy Markdown

Hello @tejan-rgb, the groups = in_channels attribute is necessary to compute the depthwise convolution, you can see how it works on this website, https://animatedai.github.io/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment