Algorithm Search⌘K

Algorithmresearch

SASRec

Also called self-attentive sequential recommendation.

Applies causal self-attention over a user's item sequence to predict the next item, attending to the relevant past items.

Time
O(E U (n^2 d + n d^2 + m d)) worst
Space
O(m d + n d + d^2 + n^2) extra
Where
E = the number of epochs; U = the number of sequences; d = the embedding size; m = the number of items; n = the length of a sequence
Properties
randomizednot exactofflineiterative
Origin
Wang Cheng Kang, Julian McAuley, 2018

SASRec is the sequential recommender of Kang and McAuley (2018). It reads the sequence of items a user has acted on and, at each position, predicts the next item. In place of the recurrent state of GRU4Rec, it uses causal self-attention: the output at position tt is a weighted mix of the items at positions 0,…,t0, \dots, t, with weights computed from the items themselves, so the model can look at the last item on sparse data and at a longer past on dense data. Each block has a self-attention layer and a small feed-forward network, each with layer normalization and a residual connection, and the score of an item is the inner product of the output with the same item embedding used at the input. The paper measured better ranking than its baselines on four data sets. That is a measurement, made with a sampled evaluation protocol, not a proof.

In plain words

To guess what a user will pick next, look back over what they picked before, but not all past items matter equally. SASRec learns how much to look at each past item. Each item asks a question (its query), every earlier item offers an answer key, and the better a key matches the question, the more that earlier item counts.

The model may only look back, never ahead, because at prediction time the future is unknown. A mask removes the links to later positions. A position vector added to each item tells the model where the item is in the sequence.

The problem

The input is a set of user sequences Su=(S1u,…,S∣Su∣u)S^u = (S^u_1, \dots, S^u_{|S^u|}) over mm items, ordered by time. For each prefix the task is to rank the items so that the next one is near the top, the sequential form of session-based recommendation. SASRec keeps the most recent nn actions, and the paper pads shorter sequences on the left with a padding item whose embedding is 0.

With one block and one head, as in the code, the model is

Et=Mst+Pt,X=LN1(E),At=softmaxu≤t((XtWQ)⋅(XuWK)d),E_t = M_{s_t} + P_t, \qquad X = \mathrm{LN}_1(E), \qquad A_t = \mathrm{softmax}_{u \le t}\Bigl(\frac{(X_t W^Q) \cdot (X_u W^K)}{\sqrt d}\Bigr),
St=Et+∑u≤tAt,u XuWV,Ft=St+ReLU(LN2(St)W(1)+b(1))W(2)+b(2),ri,t=Ft⋅Mi.S_t = E_t + \sum_{u \le t} A_{t,u}\, X_u W^V, \qquad F_t = S_t + \mathrm{ReLU}\bigl(\mathrm{LN}_2(S_t) W^{(1)} + b^{(1)}\bigr) W^{(2)} + b^{(2)}, \qquad r_{i,t} = F_t \cdot M_i.

M∈Rm×dM \in \mathbb R^{m \times d} is the item embedding, shared by the input and the prediction (Equation 6), P∈Rn×dP \in \mathbb R^{n \times d} is a learned position embedding, and layer normalization is LN(x)=α⊙(x−μ)/σ2+ϵ+β\mathrm{LN}(x) = \alpha \odot (x - \mu)/\sqrt{\sigma^2 + \epsilon} + \beta. With the target ot=st+1o_t = s_{t+1} and one negative jj per step, drawn from the items not in the user's sequence, the loss of Section III-E is

−∑u∑t[ln⁡σ(rot,t)+ln⁡(1−σ(rj,t))],-\sum_u \sum_t \Bigl[\ln \sigma(r_{o_t, t}) + \ln\bigl(1 - \sigma(r_{j, t})\bigr)\Bigr],

the log loss on one positive and one negative per position.

The algorithm

  1. SASREC-TRAIN(sequences, d, E, η)
  2. 1draw M, P and the block weights at random; gains 1, biases 0
  3. 2repeat E times
  4. 3for each sequence s, in random order do
  5. 4for each position t: target o_t ← s_{t+1}, and a random negative j_t not in s
  6. 5F ← FORWARD(s); loss and gradient of -Σ_t [ln σ(F_t·M[o_t]) + ln σ(-F_t·M[j_t])] by backpropagation
  7. 6for each weight w do
  8. 7w ← w - η · ∂loss/∂w
  9. 8return the weights
  10. FORWARD(s)
  11. 9E_t ← M[s_t] + P_t for each position t
  12. 10X ← LN₁(E); Q, K, V ← X W^Q, X W^K, X W^V
  13. 11A_{t,u} ← softmax over u ≤ t of Q_t·K_u / √d ▷ the causal mask: no u > t
  14. 12S_t ← E_t + Σ_{u ≤ t} A_{t,u} V_u
  15. 13F_t ← S_t + ReLU(LN₂(S_t) W¹ + b¹) W² + b²
  16. 14return F

The backpropagation of line L5 runs through the prediction layer, the feed-forward network, the second layer normalization, the softmax attention, the projections and the first layer normalization; the code writes every part by hand and checks each gradient entry against finite differences. The paper stacks two blocks, applies dropout to the embeddings and to the output of each sublayer, and trains with Adam at learning rate 0.001 and batch size 128. The code uses one block, no dropout, plain gradient steps and no padding.

Example

Take d=2d = 2, items M0=(2,0)M_0 = (2, 0), M1=(0,3)M_1 = (0, 3), M2=(1,1)M_2 = (1, 1), positions P0=(0,0)P_0 = (0, 0), P1=(0,1)P_1 = (0, 1), layer normalizations with gain 1 and bias 0, WQ=WK=0W^Q = W^K = 0, WV=IW^V = I, and a feed-forward network with zero weights. The sequence is (0,1)(0, 1).

  • Line L9: E0=(2,0)E_0 = (2, 0) and E1=(0,4)E_1 = (0, 4).
  • Line L10: each row is normalized to mean 0 and variance 1: X0=(1,−1)X_0 = (1, -1) and X1=(−1,1)X_1 = (-1, 1), up to the tiny ϵ\epsilon. So V=XV = X.
  • Line L11: with zero queries and keys all scores are 0. Position 0 may look only at itself, A0=(1)A_0 = (1). Position 1 looks at both, with equal weight, A1=(1/2,1/2)A_1 = (1/2, 1/2).
  • Line L12: S0=(2,0)+(1,−1)=(3,−1)S_0 = (2, 0) + (1, -1) = (3, -1) and S1=(0,4)+12(1,−1)+12(−1,1)=(0,4)S_1 = (0, 4) + \tfrac12 (1, -1) + \tfrac12 (-1, 1) = (0, 4).
  • Line L13: the feed-forward network adds 0, so F=SF = S.

The score of item 2 as the next item after the whole sequence is F1⋅M2=0+4=4F_1 \cdot M_2 = 0 + 4 = 4. F0=(3,−1)F_0 = (3, -1) does not depend on item 1; whatever item is put at position 1, the first row stays the same. The test file checks these values, and it checks the second claim in general by changing each later item and comparing the earlier outputs as floats.

Correctness

The proof in proofs/correctness.md shows two things. First, causality: FtF_t depends only on s0,…,sts_0, \dots, s_t, because the attention sums run over u≤tu \le t and all other operations act on one position at a time; in the code this holds exactly in floating point. Second, the backward pass is the exact gradient of the loss, by lemmas for the output, for layer normalization and for softmax attention, put together in reverse order of the forward graph. Whether the trained model ranks well is measured, not proved.

Proof: The causal mask keeps each SASRec output a function of the past, and the hand-written backward pass is the gradient of the lossfull

The notation is that of the page, with one block and one head. For a sequence s0,…,sT−1s_0, \dots, s_{T-1} and row vectors of length dd,

Et=M[st]+Pt,Xt=LN1(Et),Qt=XtWQ,  Kt=XtWK,  Vt=XtWV,E_t = M[s_t] + P_t, \quad X_t = \mathrm{LN}_1(E_t), \quad Q_t = X_t W_Q, \; K_t = X_t W_K, \; V_t = X_t W_V,
zt,u=Qt⋅Ku/d,At,u=ezt,u∑w≤tezt,w  (u≤t),St=Et+∑u≤tAt,uVu,z_{t,u} = Q_t \cdot K_u / \sqrt d, \quad A_{t,u} = \frac{e^{z_{t,u}}}{\sum_{w \le t} e^{z_{t,w}}} \; (u \le t), \quad S_t = E_t + \sum_{u \le t} A_{t,u} V_u,
Yt=LN2(St),Ht=ReLU(YtW1+c1),Ft=St+HtW2+c2,Y_t = \mathrm{LN}_2(S_t), \quad H_t = \mathrm{ReLU}(Y_t W_1 + c_1), \quad F_t = S_t + H_t W_2 + c_2,

where LN(x)=γ⊙x^+β\mathrm{LN}(x) = \gamma \odot \hat x + \beta with x^=(x−μ) ρ\hat x = (x - \mu)\, \rho, μ\mu the mean of the entries of xx, vv their variance and ρ=(v+ϵ)−1/2\rho = (v + \epsilon)^{-1/2}. The loss with positives iti_t and negatives jtj_t is

L=∑t−ln⁡σ(Ft⋅M[it])−ln⁡(1−σ(Ft⋅M[jt])).\mathcal L = \sum_t -\ln \sigma(F_t \cdot M[i_t]) - \ln\bigl(1 - \sigma(F_t \cdot M[j_t])\bigr).

Proposition 1 (causality). For every tt, FtF_t depends only on s0,…,sts_0, \dots, s_t and the parameters. In floating point the same holds exactly: changing st′s_{t'} for some t′>tt' > t leaves the computed FtF_t bit for bit the same.

Proof. EuE_u, XuX_u, QuQ_u, KuK_u, VuV_u depend only on sus_u and position uu. StS_t uses EtE_t and Ku,VuK_u, V_u for u≤tu \le t only, because the sums run over u≤tu \le t; that is the mask, which the code implements by never forming zt,uz_{t,u} for u>tu > t, rather than by adding −∞-\infty. YtY_t, HtH_t and FtF_t are computed from StS_t alone, position by position. So the expression for FtF_t contains only values from positions 0,…,t0, \dots, t. The code evaluates exactly this expression, with the same operations in the same order whatever the later items are, so the floating-point result is the same. □\square

The test changes the item at each position t′t' to every other item and checks that FuF_u for u<t′u < t' is equal as floats.

For the gradient, every function in the chain is differentiable except ReLU at 0; the claims are at points where no entry of YtW1+c1Y_t W_1 + c_1 is 0, and at 0 the code uses the derivative 0. Write aˉ\bar a for ∂L/∂a\partial \mathcal L / \partial a.

Lemma 2 (the output). With ℓ+=Ft⋅M[it]\ell^+ = F_t \cdot M[i_t] and ℓ−=Ft⋅M[jt]\ell^- = F_t \cdot M[j_t], ∂L/∂ℓ+=σ(ℓ+)−1\partial \mathcal L / \partial \ell^+ = \sigma(\ell^+) - 1 and ∂L/∂ℓ−=σ(ℓ−)\partial \mathcal L / \partial \ell^- = \sigma(\ell^-). So Fˉt=(σ(ℓ+)−1)M[it]+σ(ℓ−)M[jt]\bar F_t = (\sigma(\ell^+) - 1) M[i_t] + \sigma(\ell^-) M[j_t], and the prediction layer adds (σ(ℓ+)−1)Ft(\sigma(\ell^+) - 1) F_t to the gradient of row M[it]M[i_t] and σ(ℓ−)Ft\sigma(\ell^-) F_t to row M[jt]M[j_t].

Proof. −ln⁡σ(x)=ln⁡(1+e−x)-\ln \sigma(x) = \ln(1 + e^{-x}) has derivative −σ(−x)=σ(x)−1-\sigma(-x) = \sigma(x) - 1, and −ln⁡(1−σ(x))=ln⁡(1+ex)-\ln(1 - \sigma(x)) = \ln(1 + e^x) has derivative σ(x)\sigma(x). The dot products are bilinear. □\square

Lemma 3 (layer normalization). If y=γ⊙x^+βy = \gamma \odot \hat x + \beta and g=yˉg = \bar y, then γˉ=g⊙x^\bar \gamma = g \odot \hat x, βˉ=g\bar \beta = g, and with h=g⊙γh = g \odot \gamma,

xˉ=ρ(h−mean(h)−x^ mean(h⊙x^)).\bar x = \rho \bigl(h - \mathrm{mean}(h) - \hat x\, \mathrm{mean}(h \odot \hat x)\bigr).

Proof. The gain and bias formulas follow from yc=γcx^c+βcy_c = \gamma_c \hat x_c + \beta_c. For xˉ\bar x, ∂μ/∂xa=1/d\partial \mu / \partial x_a = 1/d and ∂v/∂xa=2(xa−μ)/d\partial v / \partial x_a = 2 (x_a - \mu)/d (the term from μ\mu sums to 0, since ∑c(xc−μ)=0\sum_c (x_c - \mu) = 0), so ∂ρ/∂xa=−12ρ3⋅2(xa−μ)/d=−ρ2x^a/d\partial \rho / \partial x_a = -\tfrac12 \rho^3 \cdot 2 (x_a - \mu)/d = -\rho^2 \hat x_a / d. Then

∂x^c∂xa=ρ([a=c]−1d)+(xc−μ)∂ρ∂xa=ρ([a=c]−1d−x^cx^ad),\frac{\partial \hat x_c}{\partial x_a} = \rho\Bigl([a = c] - \frac1d\Bigr) + (x_c - \mu) \frac{\partial \rho}{\partial x_a} = \rho\Bigl([a = c] - \frac1d - \frac{\hat x_c \hat x_a}{d}\Bigr),

and xˉa=∑chc ∂x^c/∂xa=ρ(ha−mean(h)−x^a mean(h⊙x^))\bar x_a = \sum_c h_c\, \partial \hat x_c / \partial x_a = \rho\bigl(h_a - \mathrm{mean}(h) - \hat x_a\, \mathrm{mean}(h \odot \hat x)\bigr). □\square

Lemma 4 (softmax attention). Fix tt and let ot=∑u≤tAt,uVuo_t = \sum_{u \le t} A_{t,u} V_u with oˉt\bar o_t known. Then Vˉu+=At,uoˉt\bar V_u \mathrel{+}= A_{t,u} \bar o_t, and with αu=oˉt⋅Vu\alpha_u = \bar o_t \cdot V_u,

zˉt,u=At,u(αu−∑w≤tAt,wαw),Qˉt+=∑u≤tzˉt,uKu/d,Kˉu+=zˉt,uQt/d.\bar z_{t,u} = A_{t,u} \Bigl(\alpha_u - \sum_{w \le t} A_{t,w} \alpha_w\Bigr), \qquad \bar Q_t \mathrel{+}= \sum_{u \le t} \bar z_{t,u} K_u / \sqrt d, \qquad \bar K_u \mathrel{+}= \bar z_{t,u} Q_t / \sqrt d.

Proof. oto_t is linear in each VuV_u with coefficient At,uA_{t,u} and in each At,uA_{t,u} with coefficient VuV_u, so Aˉt,u=αu\bar A_{t,u} = \alpha_u. The softmax has ∂At,w/∂zt,u=At,w([w=u]−At,u)\partial A_{t,w} / \partial z_{t,u} = A_{t,w}([w = u] - A_{t,u}), so zˉt,u=∑wαwAt,w([w=u]−At,u)\bar z_{t,u} = \sum_w \alpha_w A_{t,w} ([w = u] - A_{t,u}), which is the stated form. zt,uz_{t,u} is bilinear in QtQ_t and KuK_u with the factor 1/d1/\sqrt d. □\square

Theorem 5 (the backward pass is the gradient). loss_and_grad returns L\mathcal L and ∂L/∂θ\partial \mathcal L / \partial \theta for every parameter θ\theta.

Proof. The code goes through the forward graph in reverse.

  1. Lemma 2 gives Fˉt\bar F_t and the prediction-layer part of Mˉ\bar M.
  2. Ft=St+HtW2+c2F_t = S_t + H_t W_2 + c_2 gives cˉ2+=Fˉt\bar c_2 \mathrel{+}= \bar F_t, Wˉ2+=Ht⊤Fˉt\bar W_2 \mathrel{+}= H_t^\top \bar F_t, and Hˉt=FˉtW2⊤\bar H_t = \bar F_t W_2^\top. The ReLU passes Hˉt\bar H_t where the pre-activation is positive, which gives cˉ1\bar c_1, Wˉ1+=Yt⊤Pˉt\bar W_1 \mathrel{+}= Y_t^\top \bar P_t for that masked gradient Pˉt\bar P_t, and Yˉt=PˉtW1⊤\bar Y_t = \bar P_t W_1^\top. Lemma 3 turns Yˉt\bar Y_t into the gain and bias gradients of LN2\mathrm{LN}_2 and a gradient in StS_t.
  3. StS_t reaches the loss through FtF_t directly (the residual) and through LN2\mathrm{LN}_2, and through nothing else, so Sˉt\bar S_t is the sum of Fˉt\bar F_t and the result of step 2. It is complete at this point.
  4. St=Et+otS_t = E_t + o_t, so oˉt=Sˉt\bar o_t = \bar S_t and Eˉt\bar E_t gets Sˉt\bar S_t from the residual. Lemma 4 for each tt adds the contributions to Qˉt\bar Q_t, Kˉu\bar K_u and Vˉu\bar V_u for all u≤tu \le t. After all tt these sums are complete, since KuK_u and VuV_u reach the loss only through the oto_t with t≥ut \ge u.
  5. Qt=XtWQQ_t = X_t W_Q and the same for KK and VV give WˉQ+=Xt⊤Qˉt\bar W_Q \mathrel{+}= X_t^\top \bar Q_t and the like, and Xˉt=QˉtWQ⊤+KˉtWK⊤+VˉtWV⊤\bar X_t = \bar Q_t W_Q^\top + \bar K_t W_K^\top + \bar V_t W_V^\top. Lemma 3 turns Xˉt\bar X_t into the LN1\mathrm{LN}_1 gradients and a gradient in EtE_t, which is added to the residual part of step 4.
  6. Et=M[st]+PtE_t = M[s_t] + P_t adds Eˉt\bar E_t to the gradient of row M[st]M[s_t] and of row PtP_t.

Each step is the chain rule for one node of the graph, applied after all the nodes that use its output, so every adjoint is complete when it is used. Each parameter that appears in several places (MM as input and output embedding, the shared weights at every position) gets the sum of its contributions, which is the derivative of a sum. □\square

The tests compare every entry of this gradient with a central finite difference at two random points with gains and biases away from 1 and 0.

A training step. One step of train takes the exact gradient of the loss of one sequence, with one negative drawn per step from the items not in the sequence, and moves all parameters against it. The page uses plain gradient steps where the paper uses Adam. This page does not prove that the steps converge, or that the model ranks well; that is measured. ■\blacksquare

Complexity

  • One sequence. The attention scores and the weighted sums cost O(n2d)O(n^2 d), and the projections and the feed-forward network cost O(nd2)O(n d^2), so the forward and backward passes cost O(n2d+nd2)O(n^2 d + n d^2), as in Section III-F. The paper notes that the n2dn^2 d term usually dominates.
  • Training. O(EU(n2d+nd2))O(E U (n^2 d + n d^2)) for EE epochs over UU sequences. The code also updates the whole item table at each step, which adds O(md)O(m d) per step; an update of the used rows only would remove it.
  • Space. O(md+nd+d2)O(m d + n d + d^2) parameters, which do not grow with the number of users, plus O(n2+nd)O(n^2 + n d) for the attention weights and the cache of one sequence.
  • Prediction. After the forward pass, scoring an item costs O(d)O(d), as for matrix factorization.
  • Parallel time. The positions of one layer can be computed at the same time, unlike a recurrent network, which must finish step t−1t - 1 before step tt. The paper reported SASRec over ten times faster than the RNN and CNN baselines on a GPU.

Properties

  • Causal. The output at position tt uses only positions 0,…,t0, \dots, t, so training on all positions at once does not leak the targets.
  • Adaptive range. The attention weights decide how far back to look. The paper reported that the model attended mostly to recent items on sparse data and further back on dense data.
  • Order through positions only. Without PP, the attention weights do not depend on the order of the past items. The paper's ablation found removing PP better on its sparsest data set and worse on the others.
  • Shared embedding. One matrix MM serves the input and the prediction. The paper reported that this improved the results; the nonlinear block still allows asymmetric transitions.
  • Not convex. The loss is not convex in the weights.

Variants and improvements

  • More blocks and heads. The paper's default stacks two blocks with one head. In its ablation (Table IV, NDCG@10), one block did reasonably well, two blocks did better mainly on the dense data sets, three blocks were about the same as two, and two heads were slightly worse than one.
  • User embedding. Adding a user vector to FtF_t is possible; the paper found it did not help.
  • Long sequences. The quadratic cost limits nn. The paper suggests attention restricted to recent actions, or splitting long sequences.
  • Bidirectional models. Later models train with masked items in both directions in place of next-item prediction. There is no page for these yet.
  • Recurrent models. GRU4Rec keeps a recurrent state in place of attention. Recurrent network, attention and transformer pages do not yet exist on the site.

When to use it

Kang and McAuley evaluated on Amazon Beauty, Amazon Games, Steam and MovieLens-1M, with the last action of each user held out for testing and the one before it for validation. They ranked the held-out item against 100 sampled negative items and measured Hit@10 and NDCG@10. In Table III SASRec was best on all four data sets, and they reported average gains of 6.9% in Hit Rate and 9.6% in NDCG over the strongest baseline. They also observed that non-neural methods did better among the baselines on the sparse data sets and neural ones on the dense data sets.

These are measurements with one protocol, and ranking among 100 sampled items is a different measure from ranking among all items. Use SASRec when users have long ordered histories and the order matters, and compare it on full rankings with simple sequential baselines, such as a first-order Markov chain over items, and with tuned non-sequential ones.

Pitfalls

  • A leaky mask. If position tt can see position t+1t + 1, the model learns to copy the target and the training loss falls while real accuracy does not. Test it by changing a later item and checking that earlier outputs do not change.
  • Padding. With left padding, the loss terms whose target is the padding item must be dropped, and the padding embedding must stay 0.
  • Negatives from the history. The paper draws negatives from items not in the user's sequence, so items already seen are never pushed down. Recommend among unseen items, as the code does, or the model may suggest an item the user just took.
  • Sampled metrics. Results with 100 sampled negatives are not comparable with results over the full catalog.
  • Layer normalization at a constant row. If all entries of a row are equal, the variance is 0 and only ϵ\epsilon keeps the division finite; gradients there are large.
  • Softmax overflow. Subtract the largest score before taking exponentials, as the code does.

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.

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

"""SASRec (Kang and McAuley, ICDM 2018) with one block, by hand.

For a sequence s_0, ..., s_(T-1) of items (row vectors of length d):

    E_t = M[s_t] + P[t]                                   (Equation 1)
    X   = LN1(E),  Q = X WQ,  K = X WK,  V = X WV
    A_t = softmax over u <= t of Q_t . K_u / sqrt(d)      (causal, Equations 2 and 3)
    S_t = E_t + sum_(u <= t) A_(t,u) V_u                  (residual)
    F_t = S_t + ReLU(LN2(S_t) W1 + c1) W2 + c2            (Equation 4, residual)
    r_(i,t) = F_t . M[i]                                  (Equation 6, shared M)

LN is layer normalization with gain and bias. The loss of Section III-E is the
binary cross entropy with the next item as positive and one negative item per
step. The backward pass, including layer normalization and the softmax, is
written by hand and checked against finite differences in the tests.

Differences from the paper, kept to stay short: one block and one head, no
dropout, plain SGD in place of Adam, and no left padding (a sequence of
length T uses positions 0 to T - 1).
"""

import math
import random

Matrix = list[list[float]]
Params = dict[str, Matrix]
EPS = 1e-8


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 softplus(z: float) -> float:
    """ln(1 + e^z) without overflow."""
    return z + math.log1p(math.exp(-z)) if z > 0 else math.log1p(math.exp(z))


def dot(a: list[float], b: list[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


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


def matvec(w: Matrix, v: list[float]) -> list[float]:
    """W v, which is v W^T as a row."""
    return [dot(row, v) for row in w]


def outer_add(g: Matrix, a: list[float], b: list[float]) -> None:
    """g += a^T b."""
    for r, x in enumerate(a):
        if x != 0.0:
            row = g[r]
            for c, y in enumerate(b):
                row[c] += x * y


def init(n_items: int, d: int, n_pos: int, seed: int = 1, scale: float = 0.3) -> Params:
    """Gaussian start, unit gains, zero biases. Cost O(n_items d + n_pos d + d^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 {
        "M": mat(n_items, d), "P": mat(n_pos, d),
        "g1": [[1.0] * d], "b1": [[0.0] * d],
        "WQ": mat(d, d), "WK": mat(d, d), "WV": mat(d, d),
        "g2": [[1.0] * d], "b2": [[0.0] * d],
        "W1": mat(d, d), "c1": [[0.0] * d], "W2": mat(d, d), "c2": [[0.0] * d],
    }


def layer_norm(x: list[float], g: list[float], b: list[float]) -> tuple[list[float], list[float], float]:
    """g * (x - mean) / sqrt(var + EPS) + b, with the normalized x and 1/sqrt(var + EPS)."""
    d = len(x)
    mu = sum(x) / d
    var = sum((v - mu) ** 2 for v in x) / d
    rstd = 1.0 / math.sqrt(var + EPS)
    xhat = [(v - mu) * rstd for v in x]
    return [a * h + c for a, h, c in zip(g, xhat, b)], xhat, rstd


def layer_norm_back(dy: list[float], xhat: list[float], rstd: float, g: list[float], dg: list[float], db: list[float]) -> list[float]:
    """Adds the gain and bias gradients; returns the gradient in x."""
    d = len(dy)
    dxhat = [a * b for a, b in zip(dy, g)]
    for c in range(d):
        dg[c] += dy[c] * xhat[c]
        db[c] += dy[c]
    m1 = sum(dxhat) / d
    m2 = sum(a * b for a, b in zip(dxhat, xhat)) / d
    return [rstd * (a - m1 - h * m2) for a, h in zip(dxhat, xhat)]


def forward(p: Params, seq: list[int]) -> tuple[Matrix, dict]:
    """The outputs F_t for every position, and a cache. Cost O(T^2 d + T d^2)."""
    d = len(p["M"][0])
    scale = 1.0 / math.sqrt(d)
    e = [[a + b for a, b in zip(p["M"][s], p["P"][t])] for t, s in enumerate(seq)]  # @line L9
    ln1 = [layer_norm(row, p["g1"][0], p["b1"][0]) for row in e]  # @line L10
    x = [r[0] for r in ln1]
    q = [vecmat(row, p["WQ"]) for row in x]
    k = [vecmat(row, p["WK"]) for row in x]
    v = [vecmat(row, p["WV"]) for row in x]
    att, s = [], []
    for t in range(len(seq)):
        z = [dot(q[t], k[u]) * scale for u in range(t + 1)]  # @line L11
        top = max(z)
        w = [math.exp(a - top) for a in z]
        tot = sum(w)
        a = [x_ / tot for x_ in w]
        att.append(a)
        o = [sum(a[u] * v[u][c] for u in range(t + 1)) for c in range(d)]
        s.append([x_ + y for x_, y in zip(e[t], o)])  # @line L12
    ln2 = [layer_norm(row, p["g2"][0], p["b2"][0]) for row in s]
    y = [r[0] for r in ln2]
    pre = [[a + b for a, b in zip(vecmat(row, p["W1"]), p["c1"][0])] for row in y]
    hid = [[max(0.0, a) for a in row] for row in pre]
    f = [[a + b + c for a, b, c in zip(srow, vecmat(hrow, p["W2"]), p["c2"][0])] for srow, hrow in zip(s, hid)]  # @line L13
    cache = {"seq": seq, "e": e, "ln1": ln1, "x": x, "q": q, "k": k, "v": v, "att": att,
             "s": s, "ln2": ln2, "y": y, "pre": pre, "hid": hid}
    return f, cache  # @line L14


def loss(p: Params, seq: list[int], pos: list[int], neg: list[int]) -> float:
    """Sum over t of -ln sigma(F_t . M[pos_t]) - ln(1 - sigma(F_t . M[neg_t]))."""
    f, _ = forward(p, seq)
    return sum(softplus(-dot(ft, p["M"][i])) + softplus(dot(ft, p["M"][j])) for ft, i, j in zip(f, pos, neg))


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


def loss_and_grad(p: Params, seq: list[int], pos: list[int], neg: list[int]) -> tuple[float, Params]:
    """The loss and its exact gradient in every parameter. Cost O(T^2 d + T d^2)."""
    d = len(p["M"][0])
    scale = 1.0 / math.sqrt(d)
    T = len(seq)
    f, c = forward(p, seq)
    g = zeros_like(p)
    total = 0.0
    df = []
    for t in range(T):
        mi, mj = p["M"][pos[t]], p["M"][neg[t]]
        lp, ln_ = dot(f[t], mi), dot(f[t], mj)
        total += softplus(-lp) + softplus(ln_)
        dp, dn = sigmoid(lp) - 1.0, sigmoid(ln_)
        df.append([dp * a + dn * b for a, b in zip(mi, mj)])
        for col in range(d):
            g["M"][pos[t]][col] += dp * f[t][col]
            g["M"][neg[t]][col] += dn * f[t][col]
    ds = []
    for t in range(T):
        dft = df[t]
        g["c2"][0] = [a + b for a, b in zip(g["c2"][0], dft)]
        outer_add(g["W2"], c["hid"][t], dft)
        dhid = matvec(p["W2"], dft)
        dpre = [a if b > 0 else 0.0 for a, b in zip(dhid, c["pre"][t])]
        g["c1"][0] = [a + b for a, b in zip(g["c1"][0], dpre)]
        outer_add(g["W1"], c["y"][t], dpre)
        dy = matvec(p["W1"], dpre)
        _, xhat, rstd = c["ln2"][t]
        dst = layer_norm_back(dy, xhat, rstd, p["g2"][0], g["g2"][0], g["b2"][0])
        ds.append([a + b for a, b in zip(dft, dst)])
    de = [row[:] for row in ds]
    dq = [[0.0] * d for _ in range(T)]
    dk = [[0.0] * d for _ in range(T)]
    dv = [[0.0] * d for _ in range(T)]
    for t in range(T):
        a, do = c["att"][t], ds[t]
        da = [dot(do, c["v"][u]) for u in range(t + 1)]
        for u in range(t + 1):
            for col in range(d):
                dv[u][col] += a[u] * do[col]
        mean = sum(x * y for x, y in zip(a, da))
        dz = [a[u] * (da[u] - mean) * scale for u in range(t + 1)]
        for u in range(t + 1):
            for col in range(d):
                dq[t][col] += dz[u] * c["k"][u][col]
                dk[u][col] += dz[u] * c["q"][t][col]
    for t in range(T):
        xt = c["x"][t]
        outer_add(g["WQ"], xt, dq[t])
        outer_add(g["WK"], xt, dk[t])
        outer_add(g["WV"], xt, dv[t])
        dx = [a + b + e for a, b, e in zip(matvec(p["WQ"], dq[t]), matvec(p["WK"], dk[t]), matvec(p["WV"], dv[t]))]
        _, xhat, rstd = c["ln1"][t]
        det = layer_norm_back(dx, xhat, rstd, p["g1"][0], g["g1"][0], g["b1"][0])
        de[t] = [a + b for a, b in zip(de[t], det)]
        for col in range(d):
            g["M"][seq[t]][col] += de[t][col]
            g["P"][t][col] += de[t][col]
    return total, g


def train(
    sequences: list[list[int]], n_items: int, d: int, epochs: int, rate: float, seed: int = 1
) -> Params:
    """SGD on the loss of Section III-E, one sequence at a time.

    Precondition: every sequence has at least 2 items and does not use every
    item. The model gets one position per input step of the longest sequence.
    Cost O(epochs sum_u (T_u^2 d + T_u d^2)), plus O(n_items d) per update.
    """
    rng = random.Random(seed)
    n_pos = max(len(s) for s in sequences) - 1
    if any(len(s) < 2 for s in sequences):
        raise ValueError("a sequence needs at least 2 items")
    free = [[j for j in range(n_items) if j not in set(s)] for s in sequences]
    if any(not f for f in free):
        raise ValueError("a sequence uses every item")
    p = init(n_items, d, n_pos, seed)  # @line L1
    for _ in range(epochs):  # @line L2
        order = list(range(len(sequences)))
        rng.shuffle(order)
        for u in order:  # @line L3
            s = sequences[u]
            inp, pos = s[:-1], s[1:]
            neg = [rng.choice(free[u]) for _ in inp]  # @line L4
            _, g = loss_and_grad(p, inp, pos, neg)  # @line L5
            for name, mat in p.items():  # @line L6
                for r, row in enumerate(mat):
                    gr = g[name][r]
                    for col in range(len(row)):
                        row[col] -= rate * gr[col]  # @line L7
    return p  # @line L8


def next_items(p: Params, seq: list[int], k: int, exclude_seen: bool = True) -> list[int]:
    """The k items with the highest r_(i,T) after the sequence.

    With exclude_seen, items of the sequence are left out, as the negatives of
    training never include them. Cost O(T^2 d + T d^2 + n d).
    """
    f, _ = forward(p, seq)
    last = f[-1]
    seen = set(seq) if exclude_seen else set()
    scores = [dot(last, m) for m in p["M"]]
    items = [i for i in range(len(scores)) if i not in seen]
    return sorted(items, key=lambda i: (-scores[i], i))[:k]
test_sasrec.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sasrec/. The authors are listed in prov/QW5Y7Z.jsonl.

import random

import pytest

import sasrec as m

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


def random_params(seed: int) -> m.Params:
    """Random weights with gains and biases away from 1 and 0, so that every term is tested."""
    p = m.init(5, 4, 4, seed=seed, scale=0.6)
    rng = random.Random(seed + 100)
    for name in ("g1", "g2"):
        p[name] = [[rng.uniform(0.5, 1.5) for _ in range(4)]]
    for name in ("b1", "b2", "c1", "c2"):
        p[name] = [[rng.uniform(-0.3, 0.3) for _ in range(4)]]
    return p


def cyclic(seed: int, n: int, count: int) -> list[list[int]]:
    rng = random.Random(seed)
    out = []
    for _ in range(count):
        s, length = rng.randrange(n), rng.randint(3, 5)
        out.append([(s + k) % n for k in range(length)])
    return out


@pytest.mark.parametrize("seed", [3, 8])
def test_every_gradient_matches_finite_differences(seed):
    p = random_params(seed)
    seq, pos, neg = [0, 3, 1, 4], [3, 1, 4, 2], [2, 0, 0, 1]
    _, grads = m.loss_and_grad(p, seq, pos, neg)
    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 = m.loss(p, seq, pos, neg)
                mat[r][c] = old - FD_STEP
                down = m.loss(p, seq, pos, neg)
                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)


def test_causal_mask_later_items_do_not_change_earlier_outputs():
    p = random_params(5)
    base = [0, 3, 1, 4]
    f, _ = m.forward(p, base)
    for t in range(1, len(base)):
        for other in range(5):
            changed = base[:t] + [other] + base[t + 1:]
            g, _ = m.forward(p, changed)
            for u in range(t):
                assert g[u] == f[u]
    g, _ = m.forward(p, [0, 3, 2, 2])
    assert g[3] != f[3]


def test_attention_rows_are_causal_distributions():
    p = random_params(6)
    _, cache = m.forward(p, [1, 2, 0, 3])
    for t, row in enumerate(cache["att"]):
        assert len(row) == t + 1
        assert abs(sum(row) - 1.0) <= 1e-12
        assert all(a > 0 for a in row)


def test_page_example():
    zero = [[0.0, 0.0], [0.0, 0.0]]
    p = {
        "M": [[2.0, 0.0], [0.0, 3.0], [1.0, 1.0]], "P": [[0.0, 0.0], [0.0, 1.0]],
        "g1": [[1.0, 1.0]], "b1": [[0.0, 0.0]],
        "WQ": zero, "WK": zero, "WV": [[1.0, 0.0], [0.0, 1.0]],
        "g2": [[1.0, 1.0]], "b2": [[0.0, 0.0]],
        "W1": zero, "c1": [[0.0, 0.0]], "W2": zero, "c2": [[0.0, 0.0]],
    }
    f, cache = m.forward(p, [0, 1])
    assert cache["e"] == [[2.0, 0.0], [0.0, 4.0]]
    for got, want in zip(cache["x"], ([1.0, -1.0], [-1.0, 1.0])):
        assert all(abs(a - b) <= 1e-6 for a, b in zip(got, want))
    assert cache["att"] == [[1.0], [0.5, 0.5]]
    for got, want in zip(f, ([3.0, -1.0], [0.0, 4.0])):
        assert all(abs(a - b) <= 1e-6 for a, b in zip(got, want))
    assert abs(m.dot(f[1], p["M"][2]) - 4.0) <= 1e-6
    assert m.next_items(p, [0, 1], 1) == [2]


def test_training_learns_a_cyclic_pattern():
    n = 6
    sequences = cyclic(4, n, 40)
    p = m.train(sequences, n + 2, 8, 20, 0.05, seed=2)
    before = m.init(n + 2, 8, 4, seed=2)

    def hits(q):
        total = 0
        for length in (1, 2, 3, 4):
            for x in range(n):
                prefix = [(x - length + 1 + k) % n for k in range(length)]
                total += m.next_items(q, prefix, 1) == [(x + 1) % n]
        return total

    assert hits(before) <= 12
    assert hits(p) == 24


def test_preconditions():
    with pytest.raises(ValueError):
        m.train([[0]], 3, 2, 1, 0.1)
    with pytest.raises(ValueError):
        m.train([[0, 1, 2]], 3, 2, 1, 0.1)

History

Kang and McAuley presented SASRec at ICDM 2018. It brought the self-attention design of the transformer, from machine translation, to next-item recommendation, and compared it with Markov chain models, GRU4Rec and the convolutional model Caser. It became a standard baseline for sequential recommendation, and later models built on it with more layers, bidirectional training and other objectives.

References

  1. Wang-Cheng Kang and Julian McAuley, Self-attentive sequential recommendation, IEEE International Conference on Data Mining (ICDM 2018), Section III-A (item and position embeddings, Equation 1), Section III-B (scaled dot-product attention, Equations 2 and 3, causality, the feed-forward network of Equation 4), Section III-C (stacking, residual connections, layer normalization, dropout), Section III-D (the shared item embedding, Equation 6), Section III-E (the binary cross entropy loss with one negative per step, Adam), Section III-F (complexity O(n^2 d + n d^2)), Section IV (four data sets, Hit@10 and NDCG@10 over 100 sampled negatives, Table III, the ablation in Table IV)

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
  • at least three sources
  • a scene preset for the example