Train the Neural Language Model: One Stochastic Gradient Ascent Step
The 2003 neural language model is trained by stochastic gradient ascent on the log-probability of each observed next word, one word at a time. A step changes the output layer, the hidden layer and the feature vectors of the words in the context window, and nothing else in C. Implement one such step, with the paper's learning-rate schedule and weight decay.
Implement nplm_sga_step(context, target, C, H, d, U, b, W, eps0, r, t, decay).
Model (as in the forward pass): context lists n−1 word indices oldest first; x=(C(wt−1),…,C(wt−n+1)) with the most recent word first; a=tanh(d+Hx); y=b+Wx+Ua (no Wx term when W is None); p=softmax(y). Shapes: C ∣V∣×m, H h×(n−1)m, d length h, U ∣V∣×h, b length ∣V∣, W ∣V∣×(n−1)m or None. h=0 is allowed (empty H, d, U as in the forward pass).
The step, for the observed next word target =wt:
- Learning rate ε=ε0/(1+rt), where t is the number of updates done so far.
- Gradients of logpwt, all taken at the current parameters: ∂L/∂yj=1j=wt−pj, then back through U and W, through the tanh, through H into x. Block k (length m) of ∂L/∂x belongs to the word at position wt−k.
- Update, with λ =
decay:
- W, U, H: θ←θ+ε(g−λθ), where g is the gradient of logpwt.
- b, d: θ←θ+εg (biases are not decayed).
- C: only the rows of words in the window change. For each distinct word j in the window, C(j)←C(j)+ε(gj−λC(j)), where gj is the sum of the blocks of ∂L/∂x at the positions where j occurs.
Output: a dict with "log_p" (lnpwt before the update), "lr" (ε, rounded to 8 decimals) and the updated "C", "H", "d", "U", "b", "W" as nested lists ("W" is None when there are no direct connections). Round everything except "lr" to 4 decimals. Do not modify the inputs.