Replace "Variable" with torch.Tensor

I am working on someone’s old codebase and I noticed they have used Variable at a lot of places.
I know that Variable has been deprecated.
What changes can I make to the code to replace Variable with Tensor?

for n, p in model.named_parameters():
	# retrieve the consolidated mean and fisher information.
	n = n.replace('.', '__')
	mean = getattr(model, '{}_estimated_mean'.format(n))
	fisher = getattr(model, '{}_estimated_fisher'.format(n))
	
	# wrap mean and fisher in variables.
	# mean = Variable(mean)
	# fisher = Variable(fisher)
	mean = torch.Tensor(mean, requires_grad=True)
	fisher = torch.Tensor(fisher, requires_grad=True)  

Are the changes in last 4 lines correct? I’ve replaced Variable(mean) with torch.Tensor(mean, requires_grad=True) and so on…

Also I would like to know if wrapping a tensor inside Variable used to detach it from the computation graph? If yes, then I would like to do the same here.

Hi,

You can replace calls like Variable(foo) by foo.
And you can replace Variable(bar, requires_grad=True) by bar.requires_grad_().

2 Likes