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
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 is a weighted mix of the items at positions , 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 over 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 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
is the item embedding, shared by the input and the prediction (Equation 6), is a learned position embedding, and layer normalization is . With the target and one negative per step, drawn from the items not in the user's sequence, the loss of Section III-E is
the log loss on one positive and one negative per position.
The algorithm
SASREC-TRAIN(sequences, d, E, η)- 1
draw M, P and the block weights at random; gains 1, biases 0 - 2
repeat E times - 3
for each sequence s, in random order do - 4
for each position t: target o_t ← s_{t+1}, and a random negative j_t not in s - 5
F ← FORWARD(s); loss and gradient of -Σ_t [ln σ(F_t·M[o_t]) + ln σ(-F_t·M[j_t])] by backpropagation - 6
for each weight w do - 7
w ← w - η · ∂loss/∂w - 8
return the weights FORWARD(s)- 9
E_t ← M[s_t] + P_t for each position t - 10
X ← LN₁(E); Q, K, V ← X W^Q, X W^K, X W^V - 11
A_{t,u} ← softmax over u ≤ t of Q_t·K_u / √d ▷ the causal mask: no u > t - 12
S_t ← E_t + Σ_{u ≤ t} A_{t,u} V_u - 13
F_t ← S_t + ReLU(LN₂(S_t) W¹ + b¹) W² + b² - 14
return 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 , items , , , positions , , layer normalizations with gain 1 and bias 0, , , and a feed-forward network with zero weights. The sequence is .
- Line L9: and .
- Line L10: each row is normalized to mean 0 and variance 1: and , up to the tiny . So .
- Line L11: with zero queries and keys all scores are 0. Position 0 may look only at itself, . Position 1 looks at both, with equal weight, .
- Line L12: and .
- Line L13: the feed-forward network adds 0, so .
The score of item 2 as the next item after the whole sequence is . 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: depends only on , because the attention sums run over 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 and row vectors of length ,
where with , the mean of the entries of , their variance and . The loss with positives and negatives is
Proposition 1 (causality). For every , depends only on and the parameters. In floating point the same holds exactly: changing for some leaves the computed bit for bit the same.
Proof. , , , , depend only on and position . uses and for only, because the sums run over ; that is the mask, which the code implements by never forming for , rather than by adding . , and are computed from alone, position by position. So the expression for contains only values from positions . 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.
The test changes the item at each position to every other item and checks that for 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 is 0, and at 0 the code uses the derivative 0. Write for .
Lemma 2 (the output). With and , and . So , and the prediction layer adds to the gradient of row and to row .
Proof. has derivative , and has derivative . The dot products are bilinear.
Lemma 3 (layer normalization). If and , then , , and with ,
Proof. The gain and bias formulas follow from . For , and (the term from sums to 0, since ), so . Then
and .
Lemma 4 (softmax attention). Fix and let with known. Then , and with ,
Proof. is linear in each with coefficient and in each with coefficient , so . The softmax has , so , which is the stated form. is bilinear in and with the factor .
Theorem 5 (the backward pass is the gradient). loss_and_grad returns and for every parameter .
Proof. The code goes through the forward graph in reverse.
- Lemma 2 gives and the prediction-layer part of .
- gives , , and . The ReLU passes where the pre-activation is positive, which gives , for that masked gradient , and . Lemma 3 turns into the gain and bias gradients of and a gradient in .
- reaches the loss through directly (the residual) and through , and through nothing else, so is the sum of and the result of step 2. It is complete at this point.
- , so and gets from the residual. Lemma 4 for each adds the contributions to , and for all . After all these sums are complete, since and reach the loss only through the with .
- and the same for and give and the like, and . Lemma 3 turns into the gradients and a gradient in , which is added to the residual part of step 4.
- adds to the gradient of row and of row .
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 ( as input and output embedding, the shared weights at every position) gets the sum of its contributions, which is the derivative of a sum.
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.
Complexity
- One sequence. The attention scores and the weighted sums cost , and the projections and the feed-forward network cost , so the forward and backward passes cost , as in Section III-F. The paper notes that the term usually dominates.
- Training. for epochs over sequences. The code also updates the whole item table at each step, which adds per step; an update of the used rows only would remove it.
- Space. parameters, which do not grow with the number of users, plus for the attention weights and the cache of one sequence.
- Prediction. After the forward pass, scoring an item costs , 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 before step . The paper reported SASRec over ten times faster than the RNN and CNN baselines on a GPU.
Properties
- Causal. The output at position uses only positions , 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 , the attention weights do not depend on the order of the past items. The paper's ablation found removing better on its sparsest data set and worse on the others.
- Shared embedding. One matrix 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 is possible; the paper found it did not help.
- Long sequences. The quadratic cost limits . 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 can see position , 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 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.
# 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QW5Y7Z Edit this page History Report an error Markdown