Algorithm Search⌘K

Algorithmresearch

GRU4Rec

Also called recurrent session-based recommendation.

Feeds the items of a session to a gated recurrent network and trains it with ranking losses to score the next item.

Time
O(E N (H^2 + B H)) worst
Space
O(n H + H^2) extra
Where
B = the number of sessions per mini-batch; E = the number of epochs; H = the number of hidden units; N = the number of events in the training sessions; n = the number of items
Properties
randomizednot exactofflineiterative
Origin
Balázs Hidasi, Alexandros Karatzoglou, Linas Baltrunas, Domonkos Tikk, 2016

GRU4Rec is the session-based recommender of Hidasi, Karatzoglou, Baltrunas and Tikk (2016). It reads the items of a session one at a time with a gated recurrent unit (GRU) network, a kind of recurrent network, and after each item it scores every item as the next one. It trains with ranking losses on the items of the same mini-batch as negatives, and it builds mini-batches from many sessions in parallel, so that sessions of very different lengths can share one batch. It needs no user profile: the hidden state of the network is the state of the session. The paper reported large gains over item-to-item nearest neighbors on two data sets. That is a measurement, and later comparisons measured simple methods doing as well on other data.

In plain words

A user clicks a few items in a row, with no login and no history. The model keeps a short memory, a vector, and updates it after each click. From the memory it gives each item a score for "this comes next".

The memory update has two gates. One decides how much of the old memory to keep, the other how much of it to use when making a new proposal. Training shows the model real sessions and moves the weights so that the true next item scores higher than the other items in the batch.

The problem

The input is a set of sessions, each a sequence s1,s2,…,sℓs_1, s_2, \dots, s_\ell of items from nn items. The task of session-based recommendation is, after each prefix s1,…,sts_1, \dots, s_t, to rank the items so that st+1s_{t+1} is near the top. The quality is measured by recall@20 and MRR@20 on held-out sessions.

The model has input weights Wz,Wr,WhW_z, W_r, W_h (one column per item, since the input is one-hot), recurrent weights Uz,Ur,UhU_z, U_r, U_h of size H×HH \times H, and output vectors O[k]O[k] and biases ckc_k. After step tt the score of item kk is r^t,k=O[k]⊤ht+ck\hat r_{t,k} = O[k]^\top h_t + c_k. With target ii and NSN_S negatives jj, the two losses of Section 3.1.3 are

LBPR=−1NS∑jln⁡σ(r^i−r^j),LTOP1=1NS∑jσ(r^j−r^i)+σ(r^j2).L_{\mathrm{BPR}} = -\frac{1}{N_S} \sum_{j} \ln \sigma(\hat r_i - \hat r_j), \qquad L_{\mathrm{TOP1}} = \frac{1}{N_S} \sum_j \sigma(\hat r_j - \hat r_i) + \sigma(\hat r_j^2).

BPR is the loss of Bayesian personalized ranking averaged over the negatives. TOP1 is a smooth form of the relative rank of the target, plus a term that pushes the scores of negatives toward 0.

The algorithm

  1. GRU4REC-TRAIN(sessions, H, B, E, η)
  2. 1draw all weights at random
  3. 2repeat E times
  4. 3for each session-parallel mini-batch of B lanes do
  5. 4for each lane: h ← 0 if its session starts here, else the state the lane carried
  6. 5read the input item with GRU-STEP; score the target and the other targets of the batch; get the loss gradient by backpropagation
  7. 6add the gradients of all lanes
  8. 7step all weights against the summed gradient with rate η
  9. 8return the weights
  10. GRU-STEP(x, h)
  11. 9z ← σ(W_z[x] + U_z h); r ← σ(W_r[x] + U_r h) ▷ update gate and reset gate
  12. 10ĥ ← tanh(W_h[x] + U_h (r ⊙ h)) ▷ candidate state
  13. 11return (1 - z) ⊙ h + z ⊙ ĥ

Lines L9 to L11 are Equations 2 to 5 of the paper. Session-parallel mini-batches (Section 3.1.1, Figure 2) work as follows. Put the sessions in an order. The first batch holds the first event of each of the first BB sessions, with the second events as targets. The next batch holds the second events, and so on. When a session runs out, the next unused session takes its lane and the hidden state of that lane is reset to 0. The negatives of each event are the targets of the other events in the batch (Section 3.1.2). An item is in a batch about as often as it is clicked, so this is sampling in proportion to popularity, and it costs no separate draws.

The code writes the backpropagation through time by hand. The training loop carries each lane's hidden state into the next batch but treats it as a constant, so the gradient of a batch stops at the step boundary. That cut is a choice of this code; the paper does not say how far its gradient runs back. The paper trains with Adagrad and puts tanh on the output scores (Section 4.2); the code uses plain stochastic gradient steps and linear scores.

Example

Take H=1H = 1 and an item xx with Wz[x]=Wr[x]=0W_z[x] = W_r[x] = 0, Wh[x]=ln⁡3W_h[x] = \ln 3, all recurrent weights 0, and h0=0h_0 = 0.

  • Line L9: z=r=σ(0)=0.5z = r = \sigma(0) = 0.5.
  • Line L10: h^=tanh⁡(ln⁡3)=(9−1)/(9+1)=0.8\hat h = \tanh(\ln 3) = (9 - 1)/(9 + 1) = 0.8.
  • Line L11: h1=0.5⋅0+0.5⋅0.8=0.4h_1 = 0.5 \cdot 0 + 0.5 \cdot 0.8 = 0.4.

Let the target ii have O[i]=1O[i] = 1 and one negative jj have O[j]=−1O[j] = -1, both with bias 0. The scores are r^i=0.4\hat r_i = 0.4 and r^j=−0.4\hat r_j = -0.4.

  • BPR: −ln⁡σ(0.8)=ln⁡(1+e−0.8)≈0.3711-\ln \sigma(0.8) = \ln(1 + e^{-0.8}) \approx 0.3711. Its derivative in r^i\hat r_i is −σ(−0.8)≈−0.3100-\sigma(-0.8) \approx -0.3100, so a step raises the target score.
  • TOP1: σ(−0.8)+σ(0.16)≈0.3100+0.5399=0.8499\sigma(-0.8) + \sigma(0.16) \approx 0.3100 + 0.5399 = 0.8499. The second term is large even though the negative ranks below the target; it pushes r^j\hat r_j toward 0.

For the mini-batches, take sessions (0,1,2,3)(0, 1, 2, 3), (4,5)(4, 5), (6)(6), (7,8,9)(7, 8, 9), (1,3,5,7,9)(1, 3, 5, 7, 9), (2,4)(2, 4) and B=3B = 3. Session (6)(6) has no target and is skipped. The first batch is the events 0→10 \to 1, 4→54 \to 5, 7→87 \to 8. Session (4,5)(4, 5) is then done, so in the second batch its lane starts (1,3,5,7,9)(1, 3, 5, 7, 9) with a reset: 1→21 \to 2, 1→31 \to 3, 8→98 \to 9. The test file checks these values.

Correctness

The proof in proofs/correctness.md shows that the hand-written backward pass is the exact gradient of the summed loss over a sequence: the loss derivatives in the scores, the output layer, and one GRU step backward, then an induction from the last step to the first. It also shows that the session-parallel batches visit each event of each session of length at least 2 exactly once, in order, with a reset at the first event. The tests check every gradient entry against finite differences for both losses. Whether the trained model ranks well is a question of measurement, not of proof.

Proof: The hand-written backward pass of GRU4Rec is the gradient of the ranking loss, and the session-parallel batches visit every event oncefull

The notation is that of the page. A sequence has inputs x1,…,xTx_1, \dots, x_T, targets y1,…,yTy_1, \dots, y_T, negative lists N1,…,NTN_1, \dots, N_T and a fixed start state h0h_0. For t=1,…,Tt = 1, \dots, T,

atz=Wz[xt]+Uzht−1,atr=Wr[xt]+Urht−1,zt=σ(atz),rt=σ(atr),a^z_t = W_z[x_t] + U_z h_{t-1}, \quad a^r_t = W_r[x_t] + U_r h_{t-1}, \quad z_t = \sigma(a^z_t), \quad r_t = \sigma(a^r_t),
ath=Wh[xt]+Uh(rt⊙ht−1),h^t=tanh⁡(ath),ht=(1−zt)⊙ht−1+zt⊙h^t,a^h_t = W_h[x_t] + U_h (r_t \odot h_{t-1}), \quad \hat h_t = \tanh(a^h_t), \quad h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \hat h_t,

the scores are ρt,k=O[k]⊤ht+ck\rho_{t,k} = O[k]^\top h_t + c_k for k∈{yt}∪Ntk \in \{y_t\} \cup N_t, and the loss is L=∑tℓ(ρt)\mathcal L = \sum_t \ell(\rho_t) with ℓ\ell the BPR or the TOP1 loss of the page. Every function in the chain (σ\sigma, tanh⁡\tanh, products, sums, ln⁡σ\ln \sigma) is smooth, so L\mathcal L is a smooth function of all the parameters and the chain rule applies everywhere.

Lemma 1 (the losses). With ii the target, NS=∣Nt∣N_S = |N_t| and σ′=σ(1−σ)\sigma' = \sigma (1 - \sigma):

  • BPR, ℓ=−1NS∑jln⁡σ(ρi−ρj)\ell = -\frac{1}{N_S} \sum_j \ln \sigma(\rho_i - \rho_j): ∂ℓ/∂ρi=−1NS∑jσ(ρj−ρi)\partial \ell / \partial \rho_i = -\frac{1}{N_S} \sum_j \sigma(\rho_j - \rho_i) and ∂ℓ/∂ρj=1NSσ(ρj−ρi)\partial \ell / \partial \rho_j = \frac{1}{N_S} \sigma(\rho_j - \rho_i).
  • TOP1, ℓ=1NS∑jσ(ρj−ρi)+σ(ρj2)\ell = \frac{1}{N_S} \sum_j \sigma(\rho_j - \rho_i) + \sigma(\rho_j^2): ∂ℓ/∂ρi=−1NS∑jσ′(ρj−ρi)\partial \ell / \partial \rho_i = -\frac{1}{N_S} \sum_j \sigma'(\rho_j - \rho_i) and ∂ℓ/∂ρj=1NS(σ′(ρj−ρi)+2ρjσ′(ρj2))\partial \ell / \partial \rho_j = \frac{1}{N_S} \bigl(\sigma'(\rho_j - \rho_i) + 2 \rho_j \sigma'(\rho_j^2)\bigr).

Proof. ddxln⁡σ(x)=1−σ(x)=σ(−x)\frac{d}{dx} \ln \sigma(x) = 1 - \sigma(x) = \sigma(-x), so ∂∂ρi(−ln⁡σ(ρi−ρj))=−σ(ρj−ρi)\frac{\partial}{\partial \rho_i} \bigl(-\ln \sigma(\rho_i - \rho_j)\bigr) = -\sigma(\rho_j - \rho_i) and the derivative in ρj\rho_j is the negative of that. For TOP1, σ(ρj−ρi)\sigma(\rho_j - \rho_i) has derivative −σ′-\sigma' in ρi\rho_i and σ′\sigma' in ρj\rho_j, and σ(ρj2)\sigma(\rho_j^2) has derivative 2ρjσ′(ρj2)2 \rho_j \sigma'(\rho_j^2) in ρj\rho_j. The code computes these. A negative list that contains jj twice is a sum, which the code also handles, since it adds. □\square

Lemma 2 (the output layer). Let δt,k=∂ℓ(ρt)/∂ρt,k\delta_{t,k} = \partial \ell(\rho_t) / \partial \rho_{t,k}. Then ∂ℓ(ρt)/∂O[k]=δt,kht\partial \ell(\rho_t) / \partial O[k] = \delta_{t,k} h_t, ∂ℓ(ρt)/∂ck=δt,k\partial \ell(\rho_t) / \partial c_k = \delta_{t,k}, and ∂ℓ(ρt)/∂ht=∑kδt,kO[k]\partial \ell(\rho_t) / \partial h_t = \sum_k \delta_{t,k} O[k].

Proof. ρt,k\rho_{t,k} is bilinear in O[k]O[k] and hth_t and linear in ckc_k. □\square

Lemma 3 (one GRU step backward). Let gt=∂L/∂htg_t = \partial \mathcal L / \partial h_t, the total derivative through all later steps and the output of step tt. Then, entry by entry,

h^ˉ=gt⊙zt,zˉ=gt⊙(h^t−ht−1),aˉh=h^ˉ⊙(1−h^t2),\bar{\hat h} = g_t \odot z_t, \qquad \bar z = g_t \odot (\hat h_t - h_{t-1}), \qquad \bar a^h = \bar{\hat h} \odot (1 - \hat h_t^2),
uˉ=Uh⊤aˉh,rˉ=uˉ⊙ht−1,aˉz=zˉ⊙zt⊙(1−zt),aˉr=rˉ⊙rt⊙(1−rt),\bar u = U_h^\top \bar a^h, \qquad \bar r = \bar u \odot h_{t-1}, \qquad \bar a^z = \bar z \odot z_t \odot (1 - z_t), \qquad \bar a^r = \bar r \odot r_t \odot (1 - r_t),

the gradient contributions of step tt are aˉh(rt⊙ht−1)⊤\bar a^h (r_t \odot h_{t-1})^\top to UhU_h, aˉzht−1⊤\bar a^z h_{t-1}^\top to UzU_z, aˉrht−1⊤\bar a^r h_{t-1}^\top to UrU_r, and aˉh,aˉz,aˉr\bar a^h, \bar a^z, \bar a^r to the rows Wh[xt],Wz[xt],Wr[xt]W_h[x_t], W_z[x_t], W_r[x_t], and

∂L∂ht−1∣through step t=gt⊙(1−zt)+uˉ⊙rt+Uz⊤aˉz+Ur⊤aˉr.\frac{\partial \mathcal L}{\partial h_{t-1}}\Big|_{\text{through step } t} = g_t \odot (1 - z_t) + \bar u \odot r_t + U_z^\top \bar a^z + U_r^\top \bar a^r.

Proof. hth_t depends on ht−1h_{t-1} directly (through (1−zt)⊙ht−1(1 - z_t) \odot h_{t-1}), and through ztz_t, rtr_t and h^t\hat h_t. The direct path gives gt⊙(1−zt)g_t \odot (1 - z_t). The product rule on ht=(1−zt)⊙ht−1+zt⊙h^th_t = (1 - z_t) \odot h_{t-1} + z_t \odot \hat h_t gives ∂ht/∂zt=diag(h^t−ht−1)\partial h_t / \partial z_t = \mathrm{diag}(\hat h_t - h_{t-1}) and ∂ht/∂h^t=diag(zt)\partial h_t / \partial \hat h_t = \mathrm{diag}(z_t), so zˉ\bar z and h^ˉ\bar{\hat h} are as stated. tanh⁡′=1−tanh⁡2\tanh' = 1 - \tanh^2 and σ′=σ(1−σ)\sigma' = \sigma(1 - \sigma) give aˉh\bar a^h, aˉz\bar a^z, aˉr\bar a^r. The argument u=rt⊙ht−1u = r_t \odot h_{t-1} enters atha^h_t through UhU_h, so ∂L/∂u=Uh⊤aˉh=uˉ\partial \mathcal L / \partial u = U_h^\top \bar a^h = \bar u, and uu passes uˉ⊙ht−1\bar u \odot h_{t-1} to rtr_t and uˉ⊙rt\bar u \odot r_t to ht−1h_{t-1}. The pre-activations atza^z_t and atra^r_t pass Uz⊤aˉzU_z^\top \bar a^z and Ur⊤aˉrU_r^\top \bar a^r to ht−1h_{t-1}. Each pre-activation a=W[xt]+Uva = W[x_t] + U v has ∂ak/∂Ukq=vq\partial a_k / \partial U_{kq} = v_q and ∂ak/∂W[xt]k=1\partial a_k / \partial W[x_t]_k = 1, and no other row of WW appears, because the input is one-hot. □\square

Theorem 4 (the backward pass is the gradient). sequence_loss_and_grad returns L\mathcal L and its exact gradient in every parameter.

Proof. The loop runs t=T,T−1,…,1t = T, T - 1, \dots, 1 and keeps dh_next, which on entry to step tt holds ∂L/∂ht\partial \mathcal L / \partial h_t through the steps after tt (zero for t=Tt = T, since no later step exists). It adds ∑kδt,kO[k]\sum_k \delta_{t,k} O[k] (Lemma 2, with δ\delta from Lemma 1), so dh is gtg_t, the full derivative: hth_t affects L\mathcal L only through ℓ(ρt)\ell(\rho_t) and through step t+1t + 1. It then adds the contributions of Lemma 3 and sets dh_next to ∂L/∂ht−1\partial \mathcal L / \partial h_{t-1} through step tt, which is everything after t−1t - 1 except the output at t−1t - 1; that output is added at the next iteration. By induction from t=Tt = T downward the invariant holds at every step. Each parameter is shared across steps, and its gradient is the sum of the contributions of all steps, which is what the code adds. h0h_0 is a constant and gets no gradient. □\square

The tests compare every entry of this gradient with a central finite difference for both losses on a sequence of four steps with a nonzero h0h_0.

Proposition 5 (session-parallel batches). session_parallel_batches(sessions, X) returns batches in which (a) each session of length ℓ≥2\ell \ge 2 contributes exactly the ℓ−1\ell - 1 events (st,st+1)(s_t, s_{t+1}), t=1,…,ℓ−1t = 1, \dots, \ell - 1, in order, (b) the reset flag is true exactly at t=1t = 1, (c) no batch has more than XX events or two events of one session, and (d) sessions shorter than 2 contribute nothing.

Proof. Each lane holds at most one session and a position in it. A lane at position tt emits (st,st+1)(s_t, s_{t+1}) with the flag t=1t = 1, then moves to t+1t + 1 if st+2s_{t+2} exists, and otherwise takes the next session from the queue at position 1 or goes idle. So a lane emits the events of one session in order, from the first to the last, and then moves on, which gives (a) and (b) for each session it takes. The queue holds each session of length at least 2 once and is read in order, so each such session is taken by exactly one lane, and the loop runs until all lanes are idle, so every taken session is finished. Each batch takes at most one event per lane, which gives (c). Sessions shorter than 2 are not in the queue, which gives (d). □\square

A training step. In train, a lane carries its hidden state from one batch to the next and resets it to 0 at the start of a session, as in Section 3.1.1 of the paper. The gradient of a batch is the exact gradient of the sum of the one-step losses with each carried state treated as a constant (Theorem 4 with T=1T = 1). That is the gradient of the full loss with backpropagation cut at the step boundary, not the full gradient through the session. The page states this choice. This page does not prove that the steps converge, or that the model ranks well; ranking quality is measured. ■\blacksquare

Complexity

  • One step. The GRU step costs O(H2)O(H^2) for the three recurrent products, and the scores and their gradients cost O(H)O(H) per scored item. With in-batch negatives each event scores BB items, so one event costs O(H2+BH)O(H^2 + B H).
  • One epoch. NN events, so O(N(H2+BH))O(N (H^2 + B H)). The batching itself is O(N)O(N).
  • Training. O(EN(H2+BH))O(E N (H^2 + B H)) for EE epochs.
  • Space. O(nH)O(n H) for the input and output weights and O(H2)O(H^2) for the recurrent weights, plus the hidden states of the active lanes.
  • Prediction. Reading a session of length ℓ\ell costs O(ℓH2)O(\ell H^2) and scoring all items costs O(nH)O(n H).

Properties

  • No user model. The state is built from the session alone, so a new or anonymous user can get recommendations after one click.
  • Order aware. The state after s1,…,sts_1, \dots, s_t depends on the order of the items, unlike a sum of item vectors.
  • Smooth loss. Both losses are smooth in all weights, so the gradient exists everywhere.
  • Not convex. The products in the GRU make the loss non-convex, and training finds a local solution.
  • Popularity bias in the negatives. In-batch negatives are popular items more often, which changes what the loss pushes down.

Variants and improvements

  • Loss functions. The paper found pointwise cross-entropy often unstable and used BPR and TOP1 (Section 4.2). Hidasi and Karatzoglou (2018) added the BPR-max and TOP1-max losses and extra sampled negatives, and reported gains of up to 35% in MRR and recall@20 over the earlier RNN.
  • Larger layers. The paper reported better results with 1000 hidden units than with 100 for the pairwise losses (Table 3).
  • Deeper networks. The paper tried more GRU layers and found one layer best on its data.
  • Self-attention. SASRec replaces the recurrent state by causal self-attention over the past items. An attention or transformer page does not yet exist on the site.
  • Other units. The paper reported that a plain recurrent unit and an LSTM did worse than the GRU in its experiments.

When to use it

Hidasi et al. evaluated on RSC15, the RecSys Challenge 2015 clicks (7,966,257 training sessions with 31,637,239 clicks on 37,483 items), and VIDEO, a video service (about 3 million sessions). Their best baseline was session-based item-to-item nearest neighbors. In Table 3, a GRU with 1000 units and the TOP1 loss reached recall@20 of 0.6206 and MRR@20 of 0.2693 on RSC15, which they reported as 22.53% and 31.49% above item-KNN, and the BPR loss reached recall@20 of 0.6322. On VIDEO, TOP1 with 1000 units reported recall@20 of 0.6624 and MRR@20 of 0.3891.

These are measurements on two data sets with one protocol. Ludewig and Jannach (2018) compared session-based methods on more data sets and found that simple nearest neighbor methods often did as well as or better than GRU4Rec. Use GRU4Rec when sessions are anonymous and the order of the items matters, and compare it with a well-tuned session nearest neighbor baseline.

Pitfalls

  • Weak baselines. As with other neural recommenders, a poorly tuned nearest neighbor baseline makes the network look better than it is.
  • Unstable pointwise loss. The paper reports that cross-entropy gave only 10 and 6 numerically stable networks out of 100 random runs on RSC15 and VIDEO.
  • The hidden state at session ends. Forgetting to reset the state when a lane switches sessions leaks one session into the next.
  • Truncated gradients. Stopping the gradient at the batch boundary, as this code does, means the weights never get a signal from more than one step back. It is cheap but it is not the full gradient.
  • Target in the negatives. If two lanes have the same target, that item is a positive for one lane and a negative for the other. The code drops a lane's own target from its negatives.
  • Gradient checks. Check the backward pass with finite differences on a nonzero start state, or the UU gradients of the first step are zero and the check proves less.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

gru4rec.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gru4rec/. The authors are listed in prov/6CBA3Q.jsonl.

"""GRU4Rec (Hidasi, Karatzoglou, Baltrunas and Tikk, ICLR 2016), by hand.

The input of step t is the item x_t as a one-hot vector, so W x_t is the
column of W for item x_t; here the input weights are stored by item, as rows
Wz[x], Wr[x], Wh[x] of length H. The GRU of Equations 2 to 5 of the paper:

    z_t  = sigma(Wz[x_t] + Uz h_(t-1))
    r_t  = sigma(Wr[x_t] + Ur h_(t-1))
    hh_t = tanh(Wh[x_t] + Uh (r_t * h_(t-1)))
    h_t  = (1 - z_t) * h_(t-1) + z_t * hh_t

The score of item j after step t is O[j] . h_t + c[j]. The loss of step t
compares the target item i with a list of negative items j (N_S of them):

    BPR:  -(1/N_S) sum_j ln sigma(r_i - r_j)
    TOP1:  (1/N_S) sum_j sigma(r_j - r_i) + sigma(r_j^2)

`sequence_loss_and_grad` runs the forward pass over a sequence and the
backward pass through time, written by hand. Training uses session-parallel
mini-batches with the targets of the other lanes as negatives, and stops the
gradient at the step boundary (the hidden state is carried, not
differentiated through). That cut is a choice of this module, not of the
paper. The gradient check covers full sequences. The paper also uses tanh on
the output scores and Adagrad; this module uses linear scores and plain SGD.

Parameters are a dict of 2-D lists.
"""

import math
import random

Matrix = list[list[float]]
Params = dict[str, Matrix]


def sigmoid(z: float) -> float:
    if z >= 0:
        return 1.0 / (1.0 + math.exp(-z))
    e = math.exp(z)
    return e / (1.0 + e)


def log_sigmoid(z: float) -> float:
    if z >= 0:
        return -math.log1p(math.exp(-z))
    return z - math.log1p(math.exp(z))


def matvec(a: Matrix, v: list[float]) -> list[float]:
    return [sum(x * y for x, y in zip(row, v)) for row in a]


def tmatvec(a: Matrix, v: list[float]) -> list[float]:
    """a^T v."""
    out = [0.0] * len(a[0])
    for row, s in zip(a, v):
        if s != 0.0:
            for c, x in enumerate(row):
                out[c] += x * s
    return out


def init(n_items: int, hidden: int, seed: int = 1, scale: float = 0.3) -> Params:
    """Gaussian start. Cost O(n_items H + H^2)."""
    rng = random.Random(seed)

    def mat(r: int, c: int) -> Matrix:
        return [[rng.gauss(0.0, scale) for _ in range(c)] for _ in range(r)]

    return {
        "Wz": mat(n_items, hidden), "Wr": mat(n_items, hidden), "Wh": mat(n_items, hidden),
        "Uz": mat(hidden, hidden), "Ur": mat(hidden, hidden), "Uh": mat(hidden, hidden),
        "O": mat(n_items, hidden), "c": [[0.0] * n_items],
    }


def gru_step(p: Params, x: int, h: list[float]) -> dict:
    """One GRU step from state h with input item x. Cost O(H^2)."""
    az = [a + b for a, b in zip(p["Wz"][x], matvec(p["Uz"], h))]
    ar = [a + b for a, b in zip(p["Wr"][x], matvec(p["Ur"], h))]
    z = [sigmoid(v) for v in az]  # @line L9
    r = [sigmoid(v) for v in ar]
    rh = [a * b for a, b in zip(r, h)]
    hh = [math.tanh(a + b) for a, b in zip(p["Wh"][x], matvec(p["Uh"], rh))]  # @line L10
    new = [(1.0 - zz) * hp + zz * hc for zz, hp, hc in zip(z, h, hh)]  # @line L11
    return {"x": x, "h_prev": h, "z": z, "r": r, "rh": rh, "hh": hh, "h": new}


def scores(p: Params, h: list[float], items: list[int]) -> list[float]:
    """O[j] . h + c[j] for the listed items. Cost O(len(items) H)."""
    return [sum(a * b for a, b in zip(p["O"][j], h)) + p["c"][0][j] for j in items]


def step_loss(kind: str, rs: list[float]) -> tuple[float, list[float]]:
    """Loss and its derivative in the scores. rs[0] is the target, rs[1:] the negatives."""
    ri, neg = rs[0], rs[1:]
    ns = len(neg)
    if ns == 0:
        return 0.0, [0.0] * len(rs)
    d = [0.0] * len(rs)
    total = 0.0
    if kind == "bpr":
        for k, rj in enumerate(neg, start=1):
            total -= log_sigmoid(ri - rj) / ns
            g = sigmoid(rj - ri) / ns
            d[0] -= g
            d[k] += g
    elif kind == "top1":
        for k, rj in enumerate(neg, start=1):
            a, b = sigmoid(rj - ri), sigmoid(rj * rj)
            total += (a + b) / ns
            d[0] -= a * (1.0 - a) / ns
            d[k] += (a * (1.0 - a) + b * (1.0 - b) * 2.0 * rj) / ns
    else:
        raise ValueError("kind must be 'bpr' or 'top1'")
    return total, d


def zeros_like(p: Params) -> Params:
    return {name: [[0.0] * len(row) for row in mat] for name, mat in p.items()}


def sequence_loss_and_grad(
    p: Params, xs: list[int], ys: list[int], negs: list[list[int]], h0: list[float], kind: str
) -> tuple[float, Params, list[float]]:
    """Loss summed over the steps, its gradient by backpropagation through time, and the last state.

    Step t reads xs[t] and is scored on target ys[t] against the items negs[t].
    h0 is a constant. Cost O(T (H^2 + N_S H)) for T steps.
    """
    caches, total, dscores = [], 0.0, []
    h = h0
    for x, y, neg in zip(xs, ys, negs):
        c = gru_step(p, x, h)
        items = [y] + neg
        loss, d = step_loss(kind, scores(p, c["h"], items))
        total += loss
        caches.append(c)
        dscores.append((items, d))
        h = c["h"]
    g = zeros_like(p)
    dh_next = [0.0] * len(h0)
    for c, (items, d) in zip(reversed(caches), reversed(dscores)):
        dh = dh_next[:]
        for j, dj in zip(items, d):
            g["c"][0][j] += dj
            for k in range(len(dh)):
                g["O"][j][k] += dj * c["h"][k]
                dh[k] += dj * p["O"][j][k]
        x, hp, z, r, rh, hh = c["x"], c["h_prev"], c["z"], c["r"], c["rh"], c["hh"]
        dhh = [a * b for a, b in zip(dh, z)]
        dz = [a * (b - e) for a, b, e in zip(dh, hh, hp)]
        dhp = [a * (1.0 - b) for a, b in zip(dh, z)]
        dah = [a * (1.0 - b * b) for a, b in zip(dhh, hh)]
        drh = tmatvec(p["Uh"], dah)
        dr = [a * b for a, b in zip(drh, hp)]
        dhp = [a + b * e for a, b, e in zip(dhp, drh, r)]
        daz = [a * b * (1.0 - b) for a, b in zip(dz, z)]
        dar = [a * b * (1.0 - b) for a, b in zip(dr, r)]
        for name, da, inp in (("h", dah, rh), ("z", daz, hp), ("r", dar, hp)):
            gw, gu = g["W" + name][x], g["U" + name]
            for k in range(len(da)):
                gw[k] += da[k]
                for q in range(len(inp)):
                    gu[k][q] += da[k] * inp[q]
        dhp = [a + b + e for a, b, e in zip(dhp, tmatvec(p["Uz"], daz), tmatvec(p["Ur"], dar))]
        dh_next = dhp
    return total, g, h


def session_parallel_batches(sessions: list[list[int]], lanes: int) -> list[list[tuple[int, int, int, bool]]]:
    """The session-parallel mini-batches of Section 3.1.1 of the paper.

    Each batch is a list of (session index, input item, target item, reset),
    one per active lane. A lane works through its session event by event;
    when the session ends, the lane takes the next unused session and the
    hidden state is reset. Sessions shorter than 2 are skipped. Cost
    O(total events).
    """
    queue = [s for s in range(len(sessions)) if len(sessions[s]) >= 2]
    nxt = 0
    state: list[list[int] | None] = []
    for _ in range(lanes):
        if nxt < len(queue):
            state.append([queue[nxt], 0])
            nxt += 1
        else:
            state.append(None)
    batches = []
    while any(st is not None for st in state):
        batch = []
        for b in range(lanes):
            st = state[b]
            if st is None:
                continue
            s, pos = st
            seq = sessions[s]
            batch.append((s, seq[pos], seq[pos + 1], pos == 0))
            if pos + 2 < len(seq):
                state[b] = [s, pos + 1]
            elif nxt < len(queue):
                state[b] = [queue[nxt], 0]
                nxt += 1
            else:
                state[b] = None
        batches.append(batch)
    return batches


def train(
    sessions: list[list[int]], n_items: int, hidden: int, lanes: int, epochs: int, rate: float,
    kind: str = "bpr", seed: int = 1,
) -> Params:
    """SGD over session-parallel mini-batches with in-batch negatives. Cost O(E events (H^2 + lanes H))."""
    p = init(n_items, hidden, seed)  # @line L1
    for _ in range(epochs):  # @line L2
        hs: dict[int, list[float]] = {}
        for batch in session_parallel_batches(sessions, lanes):  # @line L3
            targets = [y for _, _, y, _ in batch]
            g_total = zeros_like(p)
            for s, x, y, reset in batch:
                h = [0.0] * hidden if reset else hs[s]  # @line L4
                neg = sorted({t for t in targets if t != y})
                _, g, h_new = sequence_loss_and_grad(p, [x], [y], [neg], h, kind)  # @line L5
                hs[s] = h_new
                for name, mat in g.items():  # @line L6
                    tot = g_total[name]
                    for r, row in enumerate(mat):
                        for c, v in enumerate(row):
                            tot[r][c] += v
            for name, mat in p.items():  # @line L7
                for r, row in enumerate(mat):
                    gr = g_total[name][r]
                    for c in range(len(row)):
                        row[c] -= rate * gr[c]
    return p  # @line L8


def next_items(p: Params, session: list[int], n_items: int, k: int) -> list[int]:
    """The k items with the highest score after reading the session. Cost O(T H^2 + n H)."""
    h = [0.0] * len(p["Uz"])
    for x in session:
        h = gru_step(p, x, h)["h"]
    s = scores(p, h, list(range(n_items)))
    return sorted(range(n_items), key=lambda j: (-s[j], j))[:k]
test_gru4rec.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gru4rec/. The authors are listed in prov/6CBA3Q.jsonl.

import math
import random

import pytest

import gru4rec as g

FD_STEP = 1e-6
FD_TOL = 1e-6


def cyclic_sessions(seed: int, n: int, count: int) -> list[list[int]]:
    """Sessions in which the item after x is always (x + 1) mod n."""
    rng = random.Random(seed)
    out = []
    for _ in range(count):
        s, length = rng.randrange(n), rng.randint(3, 6)
        out.append([(s + k) % n for k in range(length)])
    return out


@pytest.mark.parametrize("kind", ["bpr", "top1"])
def test_every_gradient_matches_finite_differences(kind):
    p = g.init(5, 3, seed=7, scale=0.6)
    for row in p["c"]:
        for c in range(len(row)):
            row[c] = 0.1 * (c - 2)
    xs, ys = [0, 3, 1, 4], [3, 1, 4, 2]
    negs = [[1, 2], [0, 4], [2], [0, 1, 3]]
    h0 = [0.2, -0.3, 0.1]
    _, grads, _ = g.sequence_loss_and_grad(p, xs, ys, negs, h0, kind)
    for name, mat in p.items():
        for r in range(len(mat)):
            for c in range(len(mat[r])):
                old = mat[r][c]
                mat[r][c] = old + FD_STEP
                up = g.sequence_loss_and_grad(p, xs, ys, negs, h0, kind)[0]
                mat[r][c] = old - FD_STEP
                down = g.sequence_loss_and_grad(p, xs, ys, negs, h0, kind)[0]
                mat[r][c] = old
                fd = (up - down) / (2 * FD_STEP)
                assert abs(fd - grads[name][r][c]) <= FD_TOL * max(1.0, abs(fd)), (name, r, c)


@pytest.mark.parametrize("kind", ["bpr", "top1"])
def test_loss_derivative_in_the_scores(kind):
    rs = [0.3, -0.2, 0.5, 1.1]
    _, d = g.step_loss(kind, rs)
    for k in range(len(rs)):
        up, down = rs[:], rs[:]
        up[k] += FD_STEP
        down[k] -= FD_STEP
        fd = (g.step_loss(kind, up)[0] - g.step_loss(kind, down)[0]) / (2 * FD_STEP)
        assert abs(fd - d[k]) <= FD_TOL


def test_session_parallel_batches_cover_every_event_once():
    sessions = [[0, 1, 2, 3], [4, 5], [6], [7, 8, 9], [1, 3, 5, 7, 9], [2, 4]]
    batches = g.session_parallel_batches(sessions, 3)
    seen = []
    for batch in batches:
        assert len(batch) <= 3
        assert len({s for s, _, _, _ in batch}) == len(batch)
        seen.extend(batch)
    expected = []
    for s, seq in enumerate(sessions):
        expected.extend((s, seq[t], seq[t + 1], t == 0) for t in range(len(seq) - 1))
    assert sorted(seen) == sorted(expected)
    for s, seq in enumerate(sessions):
        order = [(x, y) for b in batches for s2, x, y, _ in b if s2 == s]
        assert order == [(seq[t], seq[t + 1]) for t in range(len(seq) - 1)]
    assert batches[0] == [(0, 0, 1, True), (1, 4, 5, True), (3, 7, 8, True)]
    assert batches[1] == [(0, 1, 2, False), (4, 1, 3, True), (3, 8, 9, False)]


def test_page_example():
    p = {
        "Wz": [[0.0]], "Wr": [[0.0]], "Wh": [[math.log(3.0)]],
        "Uz": [[0.0]], "Ur": [[0.0]], "Uh": [[0.0]],
        "O": [[1.0], [-1.0]], "c": [[0.0, 0.0]],
    }
    c = g.gru_step(p, 0, [0.0])
    assert c["z"] == [0.5] and c["r"] == [0.5]
    assert abs(c["hh"][0] - 0.8) <= 1e-12
    assert abs(c["h"][0] - 0.4) <= 1e-12
    rs = g.scores(p, c["h"], [0, 1])
    bpr, d_bpr = g.step_loss("bpr", rs)
    top1, _ = g.step_loss("top1", rs)
    assert abs(bpr - math.log1p(math.exp(-0.8))) <= 1e-12
    assert abs(bpr - 0.3711006659477777) <= 1e-12
    assert abs(d_bpr[0] + 1 / (1 + math.exp(0.8))) <= 1e-12
    assert abs(top1 - (1 / (1 + math.exp(0.8)) + 1 / (1 + math.exp(-0.16)))) <= 1e-12


@pytest.mark.parametrize("kind", ["bpr", "top1"])
def test_training_learns_a_cyclic_pattern(kind):
    n = 6
    sessions = cyclic_sessions(4, n, 30)
    before = g.init(n, 6, seed=2)
    p = g.train(sessions, n, 6, 5, 10, 0.1, kind, seed=2)
    hits_before = sum(g.next_items(before, [(x - 1) % n, x], n, 1) == [(x + 1) % n] for x in range(n))
    hits = sum(g.next_items(p, [(x - 1) % n, x], n, 1) == [(x + 1) % n] for x in range(n))
    assert hits_before <= 2
    assert hits == n


def test_unknown_loss_is_rejected():
    with pytest.raises(ValueError):
        g.step_loss("hinge", [0.0, 1.0])

History

Hidasi, Karatzoglou, Baltrunas and Tikk presented GRU4Rec at ICLR 2016. It was one of the first applications of a recurrent network to session-based recommendation, and it became a standard baseline. Hidasi and Karatzoglou improved the losses and the sampling at CIKM 2018. Ludewig and Jannach published a comparison in 2018 that found simple nearest neighbor methods competitive. Self-attention models such as SASRec (2018) followed.

References

  1. Balázs Hidasi, Alexandros Karatzoglou, Linas Baltrunas and Domonkos Tikk, Session-based recommendations with recurrent neural networks, ICLR 2016, Section 3 (the GRU, Equations 2 to 5), Section 3.1 (1-of-N input and the network), Section 3.1.1 (session-parallel mini-batches, Figure 2), Section 3.1.2 (in-batch negatives as popularity-based sampling), Section 3.1.3 (the BPR and TOP1 losses), Section 4 (RSC15 and VIDEO, recall@20 and MRR@20, Tables 1 and 3)
  2. Balázs Hidasi and Alexandros Karatzoglou, Recurrent neural networks with top-k gains for session-based recommendations, CIKM 2018, Abstract (new ranking losses and extra negative samples, with reported gains in MRR and recall@20)
  3. Malte Ludewig and Dietmar Jannach, Evaluation of session-based recommendation algorithms, Abstract (simple nearest neighbor methods often did as well as or better than GRU4Rec in their comparison)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example