Legacy autograd function with non-static forward method is deprecated and will be removed in 1.3

JhonPool4: <p>Hi,</p>
<p>Do you know why a have this warning, and what I need to modify so that it doesn’t appear:</p>
<pre><code class="lang-auto">/pytorch/torch/csrc/autograd/python_function.cpp:622: UserWarning: Legacy autograd function with non-static forward method is deprecated and will be removed in 1.3. Please use new-style autograd function with static forward method. (Example: https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function)
</code></pre>
<p>The code is</p>
<pre><code class="lang-auto">class BinActive(torch.autograd.Function):
    '''
    Binarize the input activations and calculate the mean across channel dimension.
    '''
    #@staticmethod
    def forward(self, input):
        self.save_for_backward(input)
        size = input.size()
        mean = torch.mean(input.abs(), 1, keepdim=True)
        input = input.sign()
        return input, mean
    #@staticmethod
    def backward(self, grad_output, grad_output_mean):
        input, = self.saved_tensors
        grad_input = grad_output.clone()
        #grad_input[input.ge(1)] = 0
        #grad_input[input.le(-1)] = 0
        return grad_input
</code></pre>
<p>Thanks for your help,</p>

ptrblck: <p>Remove the comments before <code>@staticmethod</code> (<code>#</code>) and the warning should not be raised anymore.</p>

JhonPool4: <p>Thanks for your reply, I have removed the comments before <em><span class="mention">@staticmethod</span> (#)</em> :</p>
<pre><code class="lang-auto">class BinActive(torch.autograd.Function):
    '''
    Binarize the input activations and calculate the mean across channel dimension.
    '''   
    @staticmethod
    def forward(self, input):
        self.save_for_backward(input)
        size = input.size()
        mean = torch.mean(input.abs(), 1, keepdim=True)
        input = input.sign()
        return input, mean
    @staticmethod
    def backward(self, grad_output, grad_output_mean):
        input, = self.saved_tensors
        grad_input = grad_output.clone()
        #grad_input[input.ge(1)] = 0
        #grad_input[input.le(-1)] = 0
        return grad_input
</code></pre>
<p>however, when I try to train the network I have this problem:</p>
<pre><code class="lang-auto">---&gt; 21         x, mean = BinActive()(x)
     22 
     23         x = self.conv(x)

TypeError: forward() missing 1 required positional argument: 'input'
</code></pre>

ptrblck: <p>Try to use:</p>
<pre><code class="lang-python">x, mean = BinActive.apply(x)
</code></pre>

JhonPool4: <p>Thanks, It worked <img src="https://discuss.pytorch.org/images/emoji/apple/smiley.png?v=9" title=":smiley:" class="emoji" alt=":smiley:"></p>

Muhammad_Hasan: <p>hey i am getting error:   Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method. (Example: <a href="https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function" rel="nofollow noopener">https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function</a>)<br>
how to solve it?</p>
<p>import torch</p>
<p>from torch.autograd import Variable</p>
<p>import cv2</p>
<p>from data import BaseTransform, VOC_CLASSES as labelmap</p>
<p>from ssd import build_ssd</p>
<p>import imageio</p>
<h1>Defining a function that will do the detections</h1>
<p>def detect(frame, net, transform): # We define a detect function that will take as inputs, a frame, a ssd neural network, and a transformation to be applied on the images, and that will return the frame with the detector rectangle.</p>
<pre><code>height, width = frame.shape[:2] # We get the height and the width of the frame.

frame_t = transform(frame)[0] # We apply the transformation to our frame.

x = torch.from_numpy(frame_t).permute(2, 0, 1) # We convert the frame into a torch tensor.

x = Variable(x.unsqueeze(0)) # We add a fake dimension corresponding to the batch.

y = net(x) # We feed the neural network ssd with the image and we get the output y.

detections = y.data # We create the detections tensor contained in the output y.

scale = torch.Tensor([width, height, width, height]) # We create a tensor object of dimensions [width, height, width, height].

for i in range(detections.size(1)): # For every class:

    j = 0 # We initialize the loop variable j that will correspond to the occurrences of the class.

    while detections[0, i, j, 0] &gt;= 0.6: # We take into account all the occurrences j of the class i that have a matching score larger than 0.6.

        pt = (detections[0, i, j, 1:] * scale).numpy() # We get the coordinates of the points at the upper left and the lower right of the detector rectangle.

        cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), (255, 0, 0), 2) # We draw a rectangle around the detected object.

        cv2.putText(frame, labelmap[i - 1], (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA) # We put the label of the class right above the rectangle.

        j += 1 # We increment j to get to the next occurrence.

return frame # We return the original frame with the detector rectangle and the label around the detected object.
</code></pre>
<h1>Creating the SSD neural network</h1>
<p>net = build_ssd(‘test’) # We create an object that is our neural network ssd.</p>
<p>net.load_state_dict(torch.load(‘ssd300_mAP_77.43_v2.pth’, map_location = lambda storage, loc: storage)) # We get the weights of the neural network from another one that is pretrained (ssd300_mAP_77.43_v2.pth).</p>
<h1>Creating the transformation</h1>
<p>transform = BaseTransform(net.size, (104/256.0, 117/256.0, 123/256.0)) # We create an object of the BaseTransform class, a class that will do the required transformations so that the image can be the input of the neural network.</p>
<h1>Doing some Object Detection on a video</h1>
<p>reader = imageio.get_reader(‘funny_dog.mp4’) # We open the video.</p>
<p>fps = reader.get_meta_data()[‘fps’] # We get the fps frequence (frames per second).</p>
<p>writer = imageio.get_writer(‘output.mp4’, fps = fps) # We create an output video with this same fps frequence.</p>
<p>for i, frame in enumerate(reader): # We iterate on the frames of the output video:</p>
<pre><code>frame = detect(frame, net.eval(), transform) # We call our detect function (defined above) to detect the object on the frame.

writer.append_data(frame) # We add the next frame in the output video.

print(i) # We print the number of the processed frame.
</code></pre>
<p>writer.close() # We close the process that handles the creation of the output video.</p>
<p>getting this error:    Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method. (Example: <a href="https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function" rel="nofollow noopener">https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function</a>)</p>

ptrblck: <p>Somewhere in your code you are defining a <code>torch.autograd.Function</code> in the deprecated format and you would have to use the new-style autograd function with the static methods. The link in the error message gives you an example.</p>

Monash_u: <p>Hi Sir,</p>
<p>Same Problem i am also facing as Muhammad_Hasan. here is the below code. I include <span class="mention">@Staticmethod</span> in above of forward funtion but still i am getting forward() missing 1 required positional argument: ‘x’.</p>
<p>CODE:</p>
<p>import torch<br>
import torch.nn as nn<br>
import torch.nn.functional as F<br>
from torch.autograd import Variable<br>
from layers import *<br>
from data import v2<br>
import os</p>
<p>class SSD(nn.Module,x):<br>
“”"Single Shot Multibox Architecture<br>
The network is composed of a base VGG network followed by the<br>
added multibox conv layers.  Each multibox layer branches into<br>
1) conv2d for class conf scores<br>
2) conv2d for localization predictions<br>
3) associated priorbox layer to produce default bounding<br>
boxes specific to the layer’s feature map size.<br>
See: <a href="https://arxiv.org/pdf/1512.02325.pdf" rel="nofollow noopener">https://arxiv.org/pdf/1512.02325.pdf</a> for more details.</p>
<pre><code>Args:
    phase: (string) Can be "test" or "train"
    base: VGG16 layers for input, size of either 300 or 500
    extras: extra layers that feed to multibox loc and conf layers
    head: "multibox head" consists of loc and conf conv layers
"""

def __init__(self, phase, base, extras, head, num_classes):
    super(SSD, self).__init__()
    self.phase = phase
    self.num_classes = num_classes
    # TODO: implement __call__ in PriorBox
    self.priorbox = PriorBox(v2)
    self.priors = Variable(self.priorbox.forward(), volatile=True)
    self.size = 300

    # SSD network
    self.vgg = nn.ModuleList(base)
    # Layer learns to scale the l2 normalized features from conv4_3
    self.L2Norm = L2Norm(512, 20)
    self.extras = nn.ModuleList(extras)

    self.loc = nn.ModuleList(head[0])
    self.conf = nn.ModuleList(head[1])
   

    if phase == 'test':
        self.softmax = nn.Softmax()
        self.detect = Detect(num_classes, 0, 200, 0.01, 0.45)
    
    
@staticmethod    
def forward(self, x):
    """Applies network layers and ops on input image(s) x.

    Args:
        x: input image or batch of images. Shape: [batch,3*batch,300,300].

    Return:
        Depending on phase:
        test:
            Variable(tensor) of output class label predictions,
            confidence score, and corresponding location predictions for
            each object detected. Shape: [batch,topk,7]

        train:
            list of concat outputs from:
                1: confidence layers, Shape: [batch*num_priors,num_classes]
                2: localization layers, Shape: [batch,num_priors*4]
                3: priorbox layers, Shape: [2,num_priors*4]
    """
    sources = list()
    loc = list()
    conf = list()

    # apply vgg up to conv4_3 relu
    for k in range(23):
        x = self.vgg[k](x)

    s = self.L2Norm(x)
    sources.append(s)

    # apply vgg up to fc7
    for k in range(23, len(self.vgg)):
        x = self.vgg[k](x)
    sources.append(x)

    # apply extra layers and cache source layer outputs
    for k, v in enumerate(self.extras):
        x = F.relu(v(x), inplace=True)
        if k % 2 == 1:
            sources.append(x)

    # apply multibox head to source layers
    for (x, l, c) in zip(sources, self.loc, self.conf):
        loc.append(l(x).permute(0, 2, 3, 1).contiguous())
        conf.append(c(x).permute(0, 2, 3, 1).contiguous())

    loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)
    conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)
    if self.phase == "test":
        output = self.detect(
            loc.view(loc.size(0), -1, 4),                   # loc preds
            self.softmax(conf.view(-1, self.num_classes)),  # conf preds
            self.priors.type(type(x.data))                  # default boxes
        )
  
    else:
        output = (
            loc.view(loc.size(0), -1, 4),
            conf.view(conf.size(0), -1, self.num_classes),
            self.priors
        )
        
    
    return output


def load_weights(self, base_file):
    other, ext = os.path.splitext(base_file)
    if ext == '.pkl' or '.pth':
        print('Loading weights into state dict...')
        self.load_state_dict(torch.load(base_file, map_location=lambda storage, loc: storage))
        print('Finished!')
    else:
        print('Sorry only .pth and .pkl files supported.')
</code></pre>
<h1>This function is derived from torchvision VGG make_layers()</h1>
<h1><a href="https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py" rel="nofollow noopener">https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py</a></h1>
<p>def vgg(cfg, i, batch_norm=False):<br>
layers = []<br>
in_channels = i<br>
for v in cfg:<br>
if v == ‘M’:<br>
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]<br>
elif v == ‘C’:<br>
layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]<br>
else:<br>
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)<br>
if batch_norm:<br>
layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]<br>
else:<br>
layers += [conv2d, nn.ReLU(inplace=True)]<br>
in_channels = v<br>
pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)<br>
conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)<br>
conv7 = nn.Conv2d(1024, 1024, kernel_size=1)<br>
layers += [pool5, conv6,<br>
nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]<br>
return layers</p>
<p>def add_extras(cfg, i, batch_norm=False):<br>
# Extra layers added to VGG for feature scaling<br>
layers = []<br>
in_channels = i<br>
flag = False<br>
for k, v in enumerate(cfg):<br>
if in_channels != ‘S’:<br>
if v == ‘S’:<br>
layers += [nn.Conv2d(in_channels, cfg[k + 1],<br>
kernel_size=(1, 3)[flag], stride=2, padding=1)]<br>
else:<br>
layers += [nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag])]<br>
flag = not flag<br>
in_channels = v<br>
return layers</p>
<p>def multibox(vgg, extra_layers, cfg, num_classes):<br>
loc_layers = []<br>
conf_layers = []<br>
vgg_source = [24, -2]<br>
for k, v in enumerate(vgg_source):<br>
loc_layers += [nn.Conv2d(vgg[v].out_channels,<br>
cfg[k] * 4, kernel_size=3, padding=1)]<br>
conf_layers += [nn.Conv2d(vgg[v].out_channels,<br>
cfg[k] * num_classes, kernel_size=3, padding=1)]<br>
for k, v in enumerate(extra_layers[1::2], 2):<br>
loc_layers += [nn.Conv2d(v.out_channels, cfg[k]<br>
* 4, kernel_size=3, padding=1)]<br>
conf_layers += [nn.Conv2d(v.out_channels, cfg[k]<br>
* num_classes, kernel_size=3, padding=1)]<br>
return vgg, extra_layers, (loc_layers, conf_layers)</p>
<p>base = {<br>
‘300’: [64, 64, ‘M’, 128, 128, ‘M’, 256, 256, 256, ‘C’, 512, 512, 512, ‘M’,<br>
512, 512, 512],<br>
‘512’: [],<br>
}<br>
extras = {<br>
‘300’: [256, ‘S’, 512, 128, ‘S’, 256, 128, 256, 128, 256],<br>
‘512’: [],<br>
}<br>
mbox = {<br>
‘300’: [4, 6, 6, 6, 4, 4],  # number of boxes per feature map location<br>
‘512’: [],<br>
}</p>
<p>def build_ssd(phase, size=300, num_classes=21):<br>
if phase != “test” and phase != “train”:<br>
print(“Error: Phase not recognized”)<br>
return<br>
if size != 300:<br>
print(“Error: Sorry only SSD300 is supported currently!”)<br>
return</p>
<pre><code>return SSD(phase, *multibox(vgg(base[str(size)], 3),
                            add_extras(extras[str(size)], 1024),
                            mbox[str(size)], num_classes), num_classes)</code></pre>

ptrblck: <p>It seems you are writing a module, not a custom <code>autograd.Function</code>, so you won’t need the <code>@staticmethod</code> decorator.</p>

Monash_u: <p>thanks for your reply, if i not use <span class="mention">@staticmethod</span> decorator, then its showing runtime error:</p>
<p>Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method. (Example: <a href="https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function" rel="nofollow noopener">https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function </a>).</p>
<p>so that i followed your suggestion which you have given to jhonpool4 to include <span class="mention">@staticmethor</span> before the forward function, but i am getting another new issue : forward() missing 1 required positional argument, “x”.</p>

ptrblck: <p>If you are writing a custom <code>autograd.Function</code>, then you would need the decorator.<br>
However, base on your code it seems you might be able to just write an <code>nn.Module</code> and let Autograd figure out the backward pass. In this approach you wouldn’t need the <code>@staticmethod</code> decorator.</p>

Monash_u: <aside class="quote no-group" data-username="ptrblck" data-post="11" data-topic="69869">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>In</p>
</blockquote>
</aside>
<p>thanks, i removed <span class="mention">@staticmethod</span> in my code then i am facing below error</p>
<p>Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method. (Example: <a href="https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function" rel="noopener nofollow ugc">https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function </a>).</p>

ptrblck: <p>Could you post your model, which yields this error by wrapping it into three backticks ``` please?</p>

Monash_u: <pre><code class="lang-python">import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from layers import *
from data import v2
import os


class SSD(nn.Module):
    """Single Shot Multibox Architecture
    The network is composed of a base VGG network followed by the
    added multibox conv layers.  Each multibox layer branches into
        1) conv2d for class conf scores
        2) conv2d for localization predictions
        3) associated priorbox layer to produce default bounding
           boxes specific to the layer's feature map size.
    See: https://arxiv.org/pdf/1512.02325.pdf for more details.

    Args:
        phase: (string) Can be "test" or "train"
        base: VGG16 layers for input, size of either 300 or 500
        extras: extra layers that feed to multibox loc and conf layers
        head: "multibox head" consists of loc and conf conv layers
    """

    def __init__(self, phase, base, extras, head, num_classes):
        super(SSD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        # TODO: implement __call__ in PriorBox
        self.priorbox = PriorBox(v2)
        self.priors = Variable(self.priorbox.forward(), volatile=True)
        self.size = 300

        # SSD network
        self.vgg = nn.ModuleList(base)
        # Layer learns to scale the l2 normalized features from conv4_3
        self.L2Norm = L2Norm(512, 20)
        self.extras = nn.ModuleList(extras)

        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])
       

        if phase == 'test':
            self.softmax = nn.Softmax()
            self.detect = Detect(num_classes, 0, 200, 0.01, 0.45)
        
        
    @staticmethod    
    def forward(self, x):
        """Applies network layers and ops on input image(s) x.

        Args:
            x: input image or batch of images. Shape: [batch,3*batch,300,300].

        Return:
            Depending on phase:
            test:
                Variable(tensor) of output class label predictions,
                confidence score, and corresponding location predictions for
                each object detected. Shape: [batch,topk,7]

            train:
                list of concat outputs from:
                    1: confidence layers, Shape: [batch*num_priors,num_classes]
                    2: localization layers, Shape: [batch,num_priors*4]
                    3: priorbox layers, Shape: [2,num_priors*4]
        """
        sources = list()
        loc = list()
        conf = list()

        # apply vgg up to conv4_3 relu
        for k in range(23):
            x = self.vgg[k](x)

        s = self.L2Norm(x)
        sources.append(s)

        # apply vgg up to fc7
        for k in range(23, len(self.vgg)):
            x = self.vgg[k](x)
        sources.append(x)

        # apply extra layers and cache source layer outputs
        for k, v in enumerate(self.extras):
            x = F.relu(v(x), inplace=True)
            if k % 2 == 1:
                sources.append(x)

        # apply multibox head to source layers
        for (x, l, c) in zip(sources, self.loc, self.conf):
            loc.append(l(x).permute(0, 2, 3, 1).contiguous())
            conf.append(c(x).permute(0, 2, 3, 1).contiguous())

        loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)
        conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)
        if self.phase == "test":
            output = self.detect(
                loc.view(loc.size(0), -1, 4),                   # loc preds
                self.softmax(conf.view(-1, self.num_classes)),  # conf preds
                self.priors.type(type(x.data))                  # default boxes
            )
      
        else:
            output = (
                loc.view(loc.size(0), -1, 4),
                conf.view(conf.size(0), -1, self.num_classes),
                self.priors
            )
            
        
        return output
    

    def load_weights(self, base_file):
        other, ext = os.path.splitext(base_file)
        if ext == '.pkl' or '.pth':
            print('Loading weights into state dict...')
            self.load_state_dict(torch.load(base_file, map_location=lambda storage, loc: storage))
            print('Finished!')
        else:
            print('Sorry only .pth and .pkl files supported.')


# This function is derived from torchvision VGG make_layers()
# https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py
def vgg(cfg, i, batch_norm=False):
    layers = []
    in_channels = i
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        elif v == 'C':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
    conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)
    conv7 = nn.Conv2d(1024, 1024, kernel_size=1)
    layers += [pool5, conv6,
               nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]
    return layers


def add_extras(cfg, i, batch_norm=False):
    # Extra layers added to VGG for feature scaling
    layers = []
    in_channels = i
    flag = False
    for k, v in enumerate(cfg):
        if in_channels != 'S':
            if v == 'S':
                layers += [nn.Conv2d(in_channels, cfg[k + 1],
                           kernel_size=(1, 3)[flag], stride=2, padding=1)]
            else:
                layers += [nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag])]
            flag = not flag
        in_channels = v
    return layers


def multibox(vgg, extra_layers, cfg, num_classes):
    loc_layers = []
    conf_layers = []
    vgg_source = [24, -2]
    for k, v in enumerate(vgg_source):
        loc_layers += [nn.Conv2d(vgg[v].out_channels,
                                 cfg[k] * 4, kernel_size=3, padding=1)]
        conf_layers += [nn.Conv2d(vgg[v].out_channels,
                        cfg[k] * num_classes, kernel_size=3, padding=1)]
    for k, v in enumerate(extra_layers[1::2], 2):
        loc_layers += [nn.Conv2d(v.out_channels, cfg[k]
                                 * 4, kernel_size=3, padding=1)]
        conf_layers += [nn.Conv2d(v.out_channels, cfg[k]
                                  * num_classes, kernel_size=3, padding=1)]
    return vgg, extra_layers, (loc_layers, conf_layers)


base = {
    '300': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M',
            512, 512, 512],
    '512': [],
}
extras = {
    '300': [256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256],
    '512': [],
}
mbox = {
    '300': [4, 6, 6, 6, 4, 4],  # number of boxes per feature map location
    '512': [],
}


def build_ssd(phase, size=300, num_classes=21):
    if phase != "test" and phase != "train":
        print("Error: Phase not recognized")
        return
    if size != 300:
        print("Error: Sorry only SSD300 is supported currently!")
        return

    return SSD(phase, *multibox(vgg(base[str(size)], 3),
                                add_extras(extras[str(size)], 1024),
                                mbox[str(size)], num_classes), num_classes)
</code></pre>

ptrblck: <p>The posted code still has the <code>@staticmethod</code> defined and is an <code>nn.Module</code>.<br>
I cannot find any usage of <code>torch.autograd.Function</code>, so the posted code should not raise the “legacy function error”.</p>

Takuya_Mouri: <p>Hi, version of colab is PyTorch1.5.0, I modified detection.py and ssd.py<br>
so that it works without warning and error.</p>
<p>Since detection.py have torch.autograd.Function, I delete def  <strong>init</strong> () and add <a href="https://github.com/staticmethod" rel="nofollow noopener">@staticmethod</a>.<br>
I also add output = self.detect.apply() in ssd.py.</p>
<p>I share my code and you can find in ‘# PyTorch1.5.0 support new-style autograd function’ in source.<br>
<aside class="onebox githubblob">
  <header class="source">
      <a href="https://github.com/miyamotok0105/pytorch_handbook/blob/master/chapter7/layers/functions/detection.py" target="_blank" rel="nofollow noopener">github.com</a>
  </header>
  <article class="onebox-body">
    <h4><a href="https://github.com/miyamotok0105/pytorch_handbook/blob/master/chapter7/layers/functions/detection.py" target="_blank" rel="nofollow noopener">miyamotok0105/pytorch_handbook/blob/master/chapter7/layers/functions/detection.py</a></h4>
<pre><code class="lang-py">"""
Copyright (c) 2017 Max deGroot, Ellis Brown
Released under the MIT license
https://github.com/amdegroot/ssd.pytorch
Updated by: Takuya Mouri
"""
import torch
from torch.autograd import Function
from ..box_utils import decode, nms
from data import voc as cfg


class Detect(Function):
    """At test time, Detect is the final layer of SSD.  Decode location preds,
    apply non-maximum suppression to location predictions based on conf
    scores and threshold to a top_k number of output predictions for both
    confidence score and locations.
    """
    # PyTorch1.5.0 support new-style autograd function
    #def __init__(self, num_classes, bkg_label, top_k, conf_thresh, nms_thresh):
</code></pre>

  This file has been truncated. <a href="https://github.com/miyamotok0105/pytorch_handbook/blob/master/chapter7/layers/functions/detection.py" target="_blank" rel="nofollow noopener">show original</a>

  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>
</p>

S.S.LINGESHKUMAR: <p>i am getting diferent error<br>
TypeError: super(type, obj): obj must be an instance or subtype of type<br>
what should i do to solve that issue</p>

S.S.LINGESHKUMAR: <p>earlier i got the legacy autogard… but now i am getting this new error just after visiting the function.py for legacy but i didn’t done any changes<br>
File “C:\Users\hp\Anaconda3\lib\site-packages\torch\autograd\function.py”, line 101, in <strong>init</strong><br>
return super(FunctionMeta, cls).<strong>init</strong>(name, bases, attrs)</p>
<p>TypeError: super(type, obj): obj must be an instance or subtype of type</p>

sayak99: <p><strong>Hey guys Check out my GITHUB for the updated SSD Code for Latest Version of PyTorch</strong></p>
<p><strong>SSD and detection Python Codes updated to make it compatible with the latest version of PyTorch</strong></p>
<aside class="onebox whitelistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicons/favicon.svg" class="site-icon" width="16" height="16">
      <a href="https://github.com/sayakbanerjee1999/Single-Shot-Object-Detection-Updated" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars2.githubusercontent.com/u/43917478?s=400&amp;v=4" class="thumbnail onebox-avatar" width="60" height="60">

<h3><a href="https://github.com/sayakbanerjee1999/Single-Shot-Object-Detection-Updated" target="_blank" rel="nofollow noopener">sayakbanerjee1999/Single-Shot-Object-Detection-Updated</a></h3>

<p>This code includes the updated SSD Class for the Latest PyTorch Support - sayakbanerjee1999/Single-Shot-Object-Detection-Updated</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>


sayak99: <p><strong>Hey guys Check out my GITHUB for the updated SSD Code for Latest Version of PyTorch</strong></p>
<p><strong>SSD.py and detection Python Codes updated to make it compatible with the latest version of PyTorch</strong></p>
<aside class="onebox whitelistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicons/favicon.svg" class="site-icon" width="16" height="16">
      <a href="https://github.com/sayakbanerjee1999/Single-Shot-Object-Detection-Updated" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars2.githubusercontent.com/u/43917478?s=400&amp;v=4" class="thumbnail onebox-avatar" width="60" height="60">

<h3><a href="https://github.com/sayakbanerjee1999/Single-Shot-Object-Detection-Updated" target="_blank" rel="nofollow noopener">sayakbanerjee1999/Single-Shot-Object-Detection-Updated</a></h3>

<p>This code includes the updated SSD Class for the Latest PyTorch Support - sayakbanerjee1999/Single-Shot-Object-Detection-Updated</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>