小编Per*_*via的帖子

python中'ctx'和'self'之间的区别?

在使用深度学习库PyTorch时,我遇到了这样的定义.是否ctx有相同的行为self

class LinearFunction(Function):

    @staticmethod
    def forward(ctx, input, weight, bias=None):
        ctx.save_for_backward(input, weight, bias)
        output = input.mm(weight.t())
        if bias is not None:
            output += bias.unsqueeze(0).expand_as(output)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        input, weight, bias = ctx.saved_variables
        grad_input = grad_weight = grad_bias = None
        if ctx.needs_input_grad[0]:
            grad_input = grad_output.mm(weight)
        if ctx.needs_input_grad[1]:
            grad_weight = grad_output.t().mm(input)
        if bias is not None and ctx.needs_input_grad[2]:
            grad_bias = grad_output.sum(0).squeeze(0)

        return grad_input, grad_weight, grad_bias
Run Code Online (Sandbox Code Playgroud)

python pytorch

5
推荐指数
1
解决办法
3782
查看次数

标签 统计

python ×1

pytorch ×1