Please help me diagnose why I'm getting different values for autograd and grads. Here's…
- User
Please help me diagnose why I'm getting different values for autograd and grads. Here's my code:
import torch
class MLP: def init( self, linear_1_in_features, linear_1_out_features, f_function, linear_2_in_features, linear_2_out_features, g_function ): """ Args: linear_1_in_features: the in features of first linear layer linear_1_out_features: the out features of first linear layer linear_2_in_features: the in features of second linear layer linear_2_out_features: the out features of second linear layer f_function: string for the f function: relu | sigmoid | identity g_function: string for the g function: relu | sigmoid | identity """ self.f_function = f_function self.g_function = g_function
self.parameters = dict( W1 = torch.randn(linear_1_out_features, linear_1_in_features), b1 = torch.randn(linear_1_out_features), W2 = torch.randn(linear_2_out_features, linear_2_in_features), b2 = torch.randn(linear_2_out_features), ) self.grads = dict( dJdW1 = torch.zeros(linear_1_out_features, linear_1_in_features), dJdb1 = torch.zeros(linear_1_out_features), dJdW2 = torch.zeros(linear_2_out_features, linear_2_in_features), dJdb2 = torch.zeros(linear_2_out_features), ) # put all the cache value you need in self.cache self.cache = dict() def forward(self, x): """ Args: x: tensor shape (batch_size, linear_1_in_features) """ # TODO: Implement the forward function self.cache['x'] = x z1 = self.cache['z1'] = x @ self.parameters['W1'].T + self.parameters['b1'] if self.f_function == 'relu': a1 = self.cache['a1'] = torch.relu(z1) elif self.f_function == 'sigmoid': a1 = self.cache['a1'] = torch.sigmoid(z1) else: a1 = self.cache['a1'] = z1 z2 = self.cache['z2'] = a1 @ self.parameters['W2'].T + self.parameters['b2'] if self.g_function == 'relu': a2 = self.cache['a2'] = torch.relu(z2) elif self.g_function == 'sigmoid': a2 = self.cache['a2'] = torch.sigmoid(z2) else: a2 = self.cache['a2'] = z2 return a2 def backward(self, dJdy_hat): """ Args: dJdy_hat: The gradient tensor of shape (batch_size, linear_2_out_features) """ # TODO: Implement the backward function x = self.cache['x'] a1 = self.cache['a1'] z1 = self.cache['z1'] z2 = self.cache['z2'] if self.g_function == 'relu': dJdz2 = dJdy_hat * (z2 > 0).float() elif self.g_function == 'sigmoid': sigmoid_z2 = torch.sigmoid(z2) dJdz2 = dJdy_hat * sigmoid_z2 * (1 - sigmoid_z2) else: dJdz2 = dJdy_hat self.grads['dJdW2'] = dJdz2.T @ a1 self.grads['dJdb2'] = dJdz2.sum(dim=0) dJda1 = dJdz2 @ self.parameters["W2"] if self.f_function == 'relu': dJdz1 = dJda1 * (z1 > 0).float() elif self.f_function == 'sigmoid': sigmoid_z1 = torch.sigmoid(z1) dJdz1 = dJda1 * sigmoid_z1 * (1 - sigmoid_z1) else: dJdz1 = dJda1 self.grads['dJdW1'] = dJdz1.T @ x self.grads['dJdb1'] = dJdz1.sum(dim=0) def clear_grad_and_cache(self): for grad in self.grads: self.grads[grad].zero_() self.cache = dict() - Assistant