I thought you wanted to move to PyTorch 0.4?
You’d probably still need a backward for the Function, but the following seems to work reasonably well.
import numpy as np
import torch
x = torch.tensor([[1.,2.], [3.,4.], [5.,6.]], dtype=torch.float, requires_grad=True)
y = torch.var(x)
y.backward(torch.randn(y.size()))     
# it works fine up to here
print(x.grad)       

class Y_fun(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x):
        x_ = x.detach()
        x_.requires_grad=True
        with torch.enable_grad():
            y = torch.var(x_)
            y.backward(torch.randn(y.size()))
        print(x_.grad)      # exact same thing, but in a forward method, failed
        return y

def y_fun(x):
    return Y_fun.apply(x)

y = y_fun(x)