1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| from numpy import double import torch from torch.autograd import Function
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_tensors 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)
return grad_input, grad_weight, grad_bias
input = torch.tensor([[2.0, 1.5, 2.5], [1.0, 2.0, 3.0]], dtype=torch.double, requires_grad=True) weight = torch.tensor([[3.0, 2.0, 3.5], [1.0, 2.0, 3.0]], dtype=torch.double, requires_grad=True) bias = torch.tensor([0.1, 0.2], dtype=torch.double, requires_grad=True)
output = LinearFunction.apply(input, weight, bias) print(output)
linear = LinearFunction.apply output = linear(input, weight, bias) print(output)
from torch.autograd import gradcheck
test = gradcheck(LinearFunction.apply, (input, weight, bias), eps=1e-6, atol=1e-4) print(test)
|