Here is the instruction I was given Inside the forward() method: for t in range(l):…
- User
Here is the instruction I was given Inside the forward() method:
for t in range(l): # TODO: Implement forward pass for a single RNN timestamp pass Here you’ll implement the recurrence equation for the RNN. Each timestep receives:
the current input embedding x_t the previous hidden state h_{t-1} and outputs:
the new hidden state h_t Your task:
Implement the RNN recurrence step Append the computed hidden to the output list Update h_t_minus_1 to be the computed hidden for subsequent timesteps After the loop, compute: final_hidden = create a clone() (deep copy) of your final hidden state to return logits = result of projecting the full hidden sequence to the output space And here is the code class CharRNN(nn.Module): def init(self, input_size, hidden_size, output_size, embedding_dim=30): super().init() self.hidden_size = hidden_size self.embedding = nn.Embedding(output_size, embedding_dim) # TODO: Initialize your model parameters as needed e.g. W_e, W_h, etc.
codeself.W_e = nn.Parameter(torch.randn(embedding_dim, hidden_size) * 0.01) # Embedding-to-hidden weights self.W_h = nn.Parameter(torch.randn(hidden_size, hidden_size) * 0.01) # Hidden-to-hidden weights self.b_h = nn.Parameter(torch.zeros(hidden_size)) # Hidden biases # self.W_out = nn.Parameter(torch.randn(hidden_size, output_size) * 0.01) # Hidden-to-output weights self.b_out = nn.Parameter(torch.zeros(output_size)) def forward(self, x, hidden): """ x in [b, l] # b is batch_size and l is sequence length """ x_embed = self.embedding(x) # [b=batch_size, l=sequence_length, e=embedding_dim] b, l, _ = x_embed.size() x_embed = x_embed.transpose(0, 1) # [l, b, e] if hidden is None: h_t_minus_1 = self.init_hidden(b) else: h_t_minus_1 = hidden output = [h_t_minus_1] for t in range(l): # TODO: Implement forward pass for a single RNN timestamp, append the hidden to the output h_t = (self.W_h*h_t_minus_1 + self.W_e*output.[]) output.append(h_t) pass output = torch.stack(output) # [l, b, e] output = output.transpose(0, 1) # [b, l, e] # TODO set these values after completing the loop above final_hidden = None # [b, h] logits = None # [b, l, vocab_size=v] return logits, final_hidden def init_hidden(self, batch_size): return torch.zeros(batch_size, self.hidden_size).to(device) - Assistant