Search

Search papers and lessons

BERT4Rec: Sequential Recommendation with Bidirectional Encoder Representations

Fei Sun, Jun Liu, Jian Feng Wu et al. · 2019

BERT4Rec predicts a user's next item by hiding some items in their history and filling them in from both sides, which lets each item's representation use context from both directions.

On this page

  • Colour = topic mix
  • Linear algebra
  • Neural network basics
  • Calculus
  • Discrete math
  • Probability
  • Architectures
  • ReadReady to readNot yet

TL;DR

BERT4Rec predicts a user's next item by treating their history the way BERT treats a sentence. It hides some items at random and learns to fill them in from the items on both sides. Earlier sequential recommenders read a history left to right, so each item's representation only used the items before it. Because BERT4Rec sees both sides, it builds richer representations, and at test time a mask is placed at the end of the history to ask for the next item. On four public benchmarks it beat the strongest baselines by 7.24% HR@10 and 11.03% NDCG@10 on average.

Builds on: Sequential Recommendation, Masked Language Modeling, Recommender System · Leads to: later sequence recommenders that train with masked prediction

Why it mattered

Sequential recommendation asks what a user will do next, given what they did before. By 2019 the strongest models for it read the history one step at a time: recurrent networks such as GRU4Rec, convolutional models such as Caser, and the attention-based SASRec, which is a left-to-right Transformer. The paper states that it is the first study to bring a deep bidirectional model and the Cloze objective into recommendation.

The idea mattered for two reasons. First, it showed that the representation a model learns for each item improves when the item can see context from both sides, as words do in BERT. Second, it adapted BERT's training to a setting without a shared pre-training corpus. The paper notes that BERT is pre-trained on large, task-independent text corpora, whereas BERT4Rec is trained from scratch on each recommendation dataset. The paper has been widely cited; OpenAlex records about 4,400 citations.

The problem

Earlier recommenders make two assumptions. The first is that each item's representation can only use the items before it. The paper calls this a unidirectional limit: an item at position five never learns anything from the item at position six, even when that later item is the clearest clue to what the user was doing.

The second assumption is a rigid order. Sequence models were designed for text and time series, where the order is fixed by nature. User behaviour is looser. The paper's example is buying controllers soon after buying a console, which a model can explain only if it sees the console purchase as context.

Making the model bidirectional is not straightforward. Conventional training predicts the next item at every position. If each position's representation can see the items on its right, then the item it is supposed to predict is already in its input, and the model learns to copy it. The paper calls this information leakage, and it makes the prediction trivial. One fix creates a separate sample for each prefix of the history, which the authors find far too slow.

The Cloze task solves the leakage problem. A Cloze test removes some words from a passage and asks the reader to fill them in. The same idea is Masked Language Modeling in BERT. Hidden items cannot leak, so every item can use both sides. The remaining mismatch is that Cloze fills gaps in the middle, while recommendation predicts the future. The paper resolves this at test time by appending a mask to the end of the history.

How it works

A small example traces the whole method. The shop has five items: shoes (A), socks (B), sweater (C), scarf (D) and hat (E). A user's history is shoes, socks, sweater, scarf, in that order.

flowchart LR
  A[History of item IDs in order] --> B[Add learned position vectors]
  B --> C[Replace some items with a mask token]
  C --> D[Stack bidirectional self-attention layers]
  D --> E[Read the output at each mask]
  E --> F[Softmax over all items]
  F --> G[Cross-entropy on the true item]
  1. Start with the history in time order. The list is shoes, socks, sweater, scarf, oldest first. Check: the order is part of the input, so reversing the list would describe a different history.

  2. Add position. Self-attention alone does not know which item came first, so each position gets a learned position vector added to its item embedding. Check: the item at position one and the same item at position three now have different inputs.

  3. Mask some items. For a training example, each item is masked with some proportion ρ. Here the sweater is masked, so the input becomes shoes, socks, [mask], scarf. Check: the sweater's identity is hidden, but its neighbours are not.

  4. Run bidirectional self-attention. Every position attends to every other position, with no mask that blocks the future. At the masked position, the attention can draw on socks on the left and scarf on the right. Check: this is the step that a left-to-right model cannot do.

  5. Score every item at the mask. A small feedforward network with GELU turns the output at the mask into a vector, and its dot products with all item embeddings go through a softmax. Suppose the probabilities are: shoes 0.10, socks 0.15, sweater 0.50, scarf 0.20, hat 0.05. Check: they add up to 1.

  6. Measure the error on the true item. The true item is the sweater, with probability 0.50, so the loss is minus its natural log, about 0.69. Check: if the model had given the sweater 0.90, the loss would be about 0.11. The loss falls as the true item becomes more likely.

  7. Ask for the next item at test time. The test history is shoes, socks, sweater, scarf, followed by a mask at the end. The output at that final mask gives a probability for every item as the next one. Suppose the top item is the hat, at 0.40. Check: the question now asks about the future, which matches the recommendation task. The paper also trains with examples where only the last item is masked, which brings training closer to this test.

The math

Let Su=[v1(u),…,vnu(u)]\mathcal{S}_u = [v^{(u)}_1, \dots, v^{(u)}_{n_u}] be user uu's interactions in time order. The task is to model the probability of the next item:

p(vnu+1(u)=v∣Su).p\left(v^{(u)}_{n_u+1} = v \mid \mathcal{S}_u\right).

Step 2 in symbols: input embeddings

Each item viv_i has an embedding vi\mathbf{v}_i of size dd, and each position ii has a learned positional embedding pi\mathbf{p}_i of the same size. The input to the first layer is their sum:

hi0=vi+pi.\mathbf{h}^0_i = \mathbf{v}_i + \mathbf{p}_i.

Step 4 in symbols: one bidirectional Transformer layer

Let Hl\mathbf{H}^{l} be the matrix of hidden states at layer ll, with one row per position. Each layer does two things in sequence, a multi-head self-attention step and a position-wise feedforward step, each wrapped with a residual connection, dropout and layer normalization:

Al−1=LN⁡(Hl−1+Dropout⁡(MH⁡(Hl−1))),\mathbf{A}^{l-1} = \operatorname{LN}\left(\mathbf{H}^{l-1} + \operatorname{Dropout}\left(\operatorname{MH}(\mathbf{H}^{l-1})\right)\right), Trm⁡(Hl−1)=LN⁡(Al−1+Dropout⁡(PFFN⁡(Al−1))).\operatorname{Trm}(\mathbf{H}^{l-1}) = \operatorname{LN}\left(\mathbf{A}^{l-1} + \operatorname{Dropout}\left(\operatorname{PFFN}(\mathbf{A}^{l-1})\right)\right).

Here LN is layer normalization. Multi-head attention runs hh attentions in parallel on learned projections of the same matrix and joins their outputs:

MH⁡(H)=[head1;… ;headh] WO,headi=Attention⁡(HWiQ,HWiK,HWiV).\operatorname{MH}(\mathbf{H}) = [\text{head}_1; \dots; \text{head}_h]\,\mathbf{W}^{O}, \qquad \text{head}_i = \operatorname{Attention}\left(\mathbf{H}\mathbf{W}^{Q}_i, \mathbf{H}\mathbf{W}^{K}_i, \mathbf{H}\mathbf{W}^{V}_i\right).

Each head uses scaled dot-product attention with no causal mask, which is what makes the model bidirectional:

Attention⁡(Q,K,V)=softmax⁡(QK⊤d/h)V.\operatorname{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V}) = \operatorname{softmax}\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d/h}}\right)\mathbf{V}.

The feedforward step applies the same two-layer network at every position, with a GELU in between:

FFN⁡(x)=GELU⁡(xW(1)+b(1))W(2)+b(2),GELU⁡(x)=x Φ(x),\operatorname{FFN}(\mathbf{x}) = \operatorname{GELU}\left(\mathbf{x}\mathbf{W}^{(1)} + \mathbf{b}^{(1)}\right)\mathbf{W}^{(2)} + \mathbf{b}^{(2)}, \qquad \operatorname{GELU}(x) = x\,\Phi(x),

where Φ\Phi is the cumulative distribution function of the standard normal distribution.

Step 5 in symbols: scoring the items

At a masked position tt with final hidden state htL\mathbf{h}^{L}_t, the paper produces a distribution over all items:

P(v)=softmax⁡(GELU⁡(htLWP+bP)E⊤+bO).P(v) = \operatorname{softmax}\left(\operatorname{GELU}\left(\mathbf{h}^{L}_t \mathbf{W}^{P} + \mathbf{b}^{P}\right)\mathbf{E}^{\top} + \mathbf{b}^{O}\right).

The matrix E\mathbf{E} holds one embedding per item and is shared between the input and the output, which reduces the number of parameters.

Step 6 in symbols: the loss

Let Sum\mathcal{S}^{m}_u be the set of masked items in a masked history Su′\mathcal{S}'_u, and let vm∗v^{*}_m be the true item behind a mask. The loss averages the negative log-probability of the true items:

L=1∣Sum∣∑vm∈Sum−log⁡P(vm=vm∗∣Su′).\mathcal{L} = \frac{1}{|\mathcal{S}^{m}_u|} \sum_{v_m \in \mathcal{S}^{m}_u} -\log P\left(v_m = v^{*}_m \mid \mathcal{S}'_u\right).

This is the Cross-Entropy Loss averaged over masked positions. For the example in Step 6, with P=0.50P = 0.50 on the true item, the loss is −ln⁡(0.50)≈0.69-\ln(0.50) \approx 0.69.

Results

The text reports the following. The per-dataset tables are in the paper, and the numbers here are only those the prose states.

Evaluation. Each user's last item is held out as the test item, and the second-to-last is used for validation. Each test item is ranked against 100 negative items that the user has not interacted with, sampled according to their popularity. So the model ranks 101 candidates, not the whole catalogue. HR@k asks whether the true item is in the top k. NDCG@k is similar but rewards placing it nearer the top. MRR averages the reciprocal of the rank of the true item. The paper reports k = 1, 5 and 10.

Headline gains. Against the strongest baseline on each dataset, BERT4Rec improves HR@10 by 7.24% and NDCG@10 by 11.03% on average, and MRR by 11.46%. The paper says it performs best on all four datasets across the metrics. The four datasets are Amazon Beauty, Steam, MovieLens-1M and MovieLens-20M.

Where the gain comes from. The paper's first question is whether the gain comes from the bidirectional architecture or from the Cloze objective. When the Cloze task masks only one item at a time, BERT4Rec still significantly outperforms SASRec on Beauty and ML-1M at hidden size 256. The bidirectional architecture is therefore the main source of gain, and the Cloze objective adds further improvement on top of it. The attention analysis supports the same reading. In the second layer, attention focuses on recent items, and at the masked position attention reaches items on both sides.

Settings that mattered. The main comparison uses two layers, two heads, hidden size 64, and a maximum history length of 200 for ML-1M and ML-20M and 50 for Beauty and Steam. The mask proportion is 0.6 for Beauty, 0.4 for Steam and 0.2 for the MovieLens datasets. Training is from scratch on one GPU with Adam at learning rate 0.0001. The best mask proportion depends on sequence length: on ML-1M, a proportion of 0.6 would mean predicting about 98 items per history, against 5 on Beauty, which is too hard to train well. On maximum length, Beauty is best at 20 and ML-1M at 200, and the paper says the model does not consistently benefit from a longer window.

Ablations. Removing positional embeddings hurts badly on the long-history datasets, because the output at every mask would then depend only on the item embeddings, and the model could not tell which mask it was filling. On ML-20M with four layers, removing the residual connections lowers NDCG@10 by about 10%. More layers help on the large dataset, and the drop on Beauty at four layers is attributed to overfitting.

Cost. Each layer costs time quadratic in the history length, so the cost grows fast with longer windows. The paper notes that the attention parallelises well on a GPU, which keeps the training time practical at the lengths it tested.

Limits. The model uses only item IDs, not item features such as category or price; the authors name this as future work. Each user's history is treated as one sequence, with no separate sessions. Evaluation ranks each test item against 100 sampled negatives, so its numbers are not directly comparable with full-catalogue ranking. The paper's footnote notes that POP scores very low partly because its negatives are sampled by popularity. The gains are measured on four public datasets.

Reading guide

The paper runs in five parts. The lessons below are what each part needs.

Check yourself

QuestionWhat is the single structural difference between SASRec and BERT4Rec that determines what each item's representation can see?Show answer

SASRec uses a causal attention mask, so each position attends only to positions on its left. BERT4Rec has no such mask, so each position attends to items on both sides. That difference is why SASRec predicts each next item from its prefix, while BERT4Rec predicts masked items from both sides.

QuestionUnder the paper's evaluation, a user's test item is ranked third among the 101 candidates. What are its HR@1, HR@5 and reciprocal rank?Show answer

HR@1 is 0, because the item is not in the top 1. HR@5 is 1, because it is in the top 5. The reciprocal rank is 1 / 3, about 0.33. These are the values for this one test case, and the paper's metrics average them over all users.

QuestionWhy does a bidirectional model need the Cloze objective rather than the usual next-item prediction at every position?Show answer

If each position's representation can see the items on its right, the item to be predicted is already in the input, so the model can copy it. This is the information leakage the paper describes, and it makes the prediction trivial. Masking the target item hides it, so each position can use both sides without seeing the answer.

QuestionA service with histories of about 10 items wants to report NDCG@10 over a catalogue of one million items. Why should it be careful comparing with the paper's numbers?Show answer

The paper ranks each test item against 100 sampled negatives, so the candidate list has 101 items. Ranking against a million items is much harder, and the same model would score lower. The paper's negatives are also sampled by popularity, which affects the results. To compare fairly, the service should evaluate the paper's models and its own under the same protocol.

Sources

Read the full paper

Fei Sun, Jun Liu, Jian Feng Wu et al., 2019. arXiv:1904.06690