nn.Upsample to nn.functional.interpolate


(Michelangelo) #1

Hi everyone,

I am quite new in pyTorch and I noticed that in version 0.4.1 of Pytorch the nn.Upsample is being replaced by nn.functional.interpolate

I’m trying to change the code which I am working on it but I got an error. any help to replace Upsampling to interpolate will be appreciated.

This is part of my model which I need to replace Upsampling to Interpolate:

class GeneratorUNet(nn.Module):
    def __init__(self, in_channels=3, out_channels=3, dropout = 0.0):
        super(GeneratorUNet, self).__init__()

        self.down1 = UNetDown(in_channels, 64, normalize=False)
        self.down2 = UNetDown(64, 128)
        self.down3 = UNetDown(128, 256)
        self.down4 = UNetDown(256, 512, dropout=dropout)
        self.down5 = UNetDown(512, 512, dropout=dropout)
        self.down6 = UNetDown(512, 512, dropout=dropout)
        self.down7 = UNetDown(512, 512, dropout=dropout)
        self.down8 = UNetDown(512, 512, normalize=False, dropout=dropout)

        self.up1 = UNetUp(512, 512, dropout=dropout)
        self.up2 = UNetUp(1024, 512, dropout=dropout)
        self.up3 = UNetUp(1024, 512, dropout=dropout)
        self.up4 = UNetUp(1024, 512, dropout=dropout)
        self.up5 = UNetUp(1024, 256)
        self.up6 = UNetUp(512, 128)
        self.up7 = UNetUp(256, 64)


        self.final = nn.Sequential(
            nn.Upsample(scale_factor=2), # Here is the Upsampling needs to replace with interpolate
            nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv2d(128, out_channels, 4, padding=1),
            nn.Tanh()
        )


    def forward(self, x):
        d1 = self.down1(x)
        d2 = self.down2(d1)
        d3 = self.down3(d2)
        d4 = self.down4(d3)
        d5 = self.down5(d4)
        d6 = self.down6(d5)
        d7 = self.down7(d6)
        d8 = self.down8(d7)
        u1 = self.up1(d8, d7)
        u2 = self.up2(u1, d6)
        u3 = self.up3(u2, d5)
        u4 = self.up4(u3, d4)
        u5 = self.up5(u4, d3)
        u6 = self.up6(u5, d2)
        u7 = self.up7(u6, d1)

        return self.final(u7)


(Anuvabh) #2

I think a simple way to define a module to use the interpolate function. Then you can use it in your sequential container same as you are using nn.Upsample currently.
Something along these lines:

class Upsample(nn.Module):
    def __init__(self,  scale_factor):
        super(Upsample, self).__init__()
        self.scale_factor = scale_factor
    def forward(self, x):
        return F.interpolate(x, scale_factor=self.scale_factor)

(Michelangelo) #3

Thank you so much. It works perfectly.

ps: you just need to swap the line of super and init


(Anuvabh) #4

Oops, yes. I’ll edit and fix that