Build a Session-Based Recommender with RNNs for E-Commerce


recommendation-systems deep-learning nlp model-evaluation
View full code for this problem

ML Problem & Solution

Session-Based Recommendation with GRU4Rec

No user id, no history, four clicks of context, and a softmax over 182,000 items you cannot compute.

⏱ 36 min read 📐 Advanced 🎯 Deep Learning

A fashion and homeware marketplace serves a “Customers also viewed” rail on every product page, 20 slots, and it is filled by the confidence-weighted ALS model from post 21. For 31.7% of page views that model works as designed: it looks up the visitor’s factor vector, scores the catalogue, and returns something personalised. For the other 68.3% there is no factor vector to look up, because the visitor is logged out, or on a new device, or has never bought anything, and the rail falls back to the category best-sellers. The best-seller fallback gets a click-through rate of 1.9% against the personalised rail’s 4.6%, and it is serving two thirds of the traffic.

The catalogue is 182,000 active SKUs and the log is 2.4 million events a day, 174 million over the 90-day retention window. The thing those 68.3% of page views do have is a session: a handful of clicks that happened in the last few minutes, ordered, on this device, right now. The median is 3 events and the 95th percentile is 12. That is not much, and it is a completely different kind of information from a user factor. A user factor says what this person likes in general. A session says what this person is doing in the next ninety seconds, and for a rail on a product page the second is the more useful of the two.

The obvious move is to stop thinking about users and build a transition model. Count how often item B follows item A across the log, normalise, and serve the top 20 successors of whatever the visitor just clicked. That takes a morning, it needs no embeddings, and it works: recall@20 of 0.3062 against the best-seller fallback’s 0.0514. It is also a first-order Markov chain, and the thing it cannot represent is the reason this post is long. About a fifth of clicks in this log are a merchandised banner or a cross-category promotion, something the visitor clicked out of curiosity and then abandoned. Conditioned on that click, a transition matrix has lost the thread: it has no idea the previous four clicks were all mid-century sideboards. A model conditioned on the whole ordered prefix does.

The analogy worth carrying is a shop assistant who joined you thirty seconds ago. They did not see you arrive, they do not know your name, and they have no record of what you bought last winter. What they have is the four things you have picked up, in the order you picked them up, including the one you clearly only glanced at. A good assistant uses the order and discounts the glance. A transition matrix is an assistant who only remembers the last thing you touched.

Given the ordered sequence of items a visitor has clicked in the current session, with no user identity and no history beyond it, predict the next item the visitor will click from a catalogue of 182,000, optimising for recall@20 and MRR@20 on a 20-slot rail, under a 12 ms p99 scoring budget, without letting the session-boundary convention or the evaluation protocol decide the answer for you.

Framing the Problem

This is next-item prediction, which is a multi-class classification problem with 182,000 classes and a sequence for an input. That framing is worth saying slowly, because it is not the framing post 21 used and the difference is not cosmetic.

Matrix factorisation asks: given a sparse matrix of user-item interactions, find low-rank factors whose product reconstructs it. The parameters are per user and per item, the loss is over observed cells, and the model has nothing to say about a user it has no row for. Next-item prediction asks: given an ordered prefix, produce a distribution over the catalogue for position t plus one. The parameters are per item plus a shared recurrent transition, there are no user parameters at all, and that single structural fact is both the reason the model generalises to an unseen visitor and the reason it cannot personalise to a familiar one.

The target is the identity of the next clicked item, which makes the label free, instantaneous and unambiguous. No editorial judgements, no 2.80 USD per label, no propensity correction of the kind post 24 needed. The catch is that the label is also the thing the current system influences: the next click is partly a function of what the rail showed, which is a feedback loop that no offline metric sees.

The unit is the session, and every split, every metric and every batch moves whole sessions. A session is also the one object in this problem that does not exist in the data, which is the subject of the next section.

# Expanding sessions into (prefix, next item) examples. The unit of everything.
import numpy as np
import pandas as pd


def prefix_examples(tab: pd.DataFrame, mode: str = "all") -> tuple:
    """Turn one row per session into training or test examples.

    mode="all"   every prefix: a length-L session gives L-1 examples. This is
                 what GRU4Rec trains on.
    mode="last"  only the final item, which is the standard evaluation
                 protocol and gives every session exactly one example.

    A length-1 session gives ZERO examples under either mode. That is 21.4%
    of sessions in this log, and they are invisible to training and to the
    offline metric while receiving 21.4% of the rail impressions.
    """
    prefixes, targets, sids = [], [], []
    for sid, items in zip(tab["session_id"].to_numpy(), tab["items"]):
        if len(items) < 2:
            continue
        rng = [len(items) - 1] if mode == "last" else range(1, len(items))
        for j in rng:
            prefixes.append(list(items[:j]))
            targets.append(int(items[j]))
            sids.append(int(sid))
    return prefixes, np.asarray(targets, dtype=int), np.asarray(sids, dtype=int)

Constraints, and the first and third decided the architecture:

  • 12 ms p99 for scoring 182,000 items, inside a 240 ms product-page budget that already contains the inventory service and the price engine. A full softmax over the catalogue at serving time is 46.6 million multiply-adds per request, which is 1.9 ms on its own and would be acceptable; the problem is that it has to be done 2.4 million times a day during training as well, and there it is the entire budget.
  • No user identity may be required. The rail must work for a visitor who arrived from a search engine four seconds ago. This eliminates every model with per-user parameters as the primary mechanism, which is most of the recommendation literature.
  • 4,100 new SKUs launch per week and the merchandising team expects them in the rail the same day. 2.9% of held-out targets are items that were not in training at all, which caps recall@20 at 0.9710 and forces an embedding-refresh path separate from the retrain path.
  • The rail is 20 slots and they are all visible. There is no fold, no “see more”, so the metric truncation is a product fact rather than a modelling choice, and the difference between rank 1 and rank 15 is much smaller than it is in search.
  • Nightly retraining. The catalogue and the seasonal mix move weekly, not hourly, and a 12.6 hour training run does not fit a faster cadence anyway.
Metric That Matters

The optimisation target is **recall@20**, the share of examples where the true next item appears anywhere in the 20 slots, and the reason it is not accuracy is that there is exactly one relevant item out of 182,000 and a top-1 metric would be 0.04 for every model ever built. The business metric is **add-to-cart rate on the rail**, and the two diverge, which is most of the second half of this post. Four guardrails, and the first two are specific to sessions rather than inherited from post 21 or 24. **MRR@20**, because recall@20 is blind to where in the 20 slots the item landed and a model can buy recall@20 cheaply by filling the top slots with items the visitor has already seen: measured in the companion codebase, a session-kNN baseline puts an already-seen item in the top slot 99.25% of the time, beats a GRU on recall@20 by 0.0106 and loses MRR@20 by 0.0991. **recall@20 restricted to one-click prefixes**, because 24.1% of evaluation targets come from a session with exactly one prior click, and on that bucket a GRU and a first-order Markov chain condition on identical information, so a pooled gain can be entirely a long-prefix gain on a quarter of the traffic. **Catalogue coverage of the rail**, the share of SKUs that appear in any top 20 across a day, because the merchandising team's definition of a working rail includes the long tail and no accuracy metric implies it. And **the share of rail slots holding an item from the same category as the anchor**, which is the one guardrail that caught the variant that won offline and lost money.

Key Insight

Next-item prediction and matrix factorisation are not two implementations of one objective, and the clearest way to see it is to ask what each one does with the ORDER of a session. A factorisation of a user-item matrix is invariant to the order of a user's interactions by construction: permute the rows of the interaction log and you get the same factors, because the loss is a sum over cells. So is a co-occurrence item-kNN, because a symmetric co-occurrence count cannot distinguish "viewed A then B" from "viewed B then A". On a browse-to-buy funnel those are very different claims, and the companion codebase measures what the distinction is worth: an item-kNN over a symmetric co-occurrence matrix scores 0.5056 recall@20 on synthetic data and a first-order Markov chain over the same information, differing only in that it is directional, scores 0.5901. That 0.0845 is the value of DIRECTION alone, before any sequence model exists. The value of ORDER beyond direction is a separate and smaller quantity, and the honest way to measure it is against a model that sees the whole prefix as an unordered set, which almost no published GRU4Rec comparison does. That is the single most important baseline in this post and it appears in the next section but one.

Out of scope: candidate retrieval over 182,000 items, which is the two-tower problem and is post 27; cross-session personalisation, which is a hierarchical RNN and is a different problem with a different data contract; and the self-attention family, SASRec and BERT4Rec, which appear in the alternatives table with numbers and are the roadmap item this project produced.

Data and Features

There is one table and one thing that is not in it.

The event stream is 174 million rows of (cookie_id, item_id, timestamp, event_type) over 90 days, where event_type is one of view, add-to-cart or purchase and 96.1% of rows are views. The item table is 182,000 rows of catalogue metadata, which this model uses for exactly one thing, the category guardrail, and otherwise ignores. The thing that is not in either table is the session, and recovering it is the first modelling decision in the pipeline rather than a preprocessing step.

A session-based recommendation pipeline over a 174 million event stream, 182,000 active SKUs and 41.6 million sessions where 68.3% of events come from a visitor with no usable history so a matrix factorisation has no user factor to look up: sessionisation by a 30-minute inactivity gap with its two asymmetric errors, a 10-minute gap giving 54.2 million sessions of which 44.1% hold one event and raising offline recall@20 to 0.3604 while the online add-to-cart rate fell 2.8%, against a 2-hour gap making 33.4% of sessions mixed-intent; a temporal split by quantiles of session start time into 29.1 million train, 5.0 million validation and 7.5 million test sessions where a length-1 session contributes zero examples and 21.4% of sessions are length 1; one training step written out as the four GRU equations with a 128-dimensional embedding of 23.3 million parameters and a 256-unit state of 294,912 recurrent parameters, where the reset gate carries the long-range dependency and a Markov chain drops from 0.6477 to 0.3625 recall@20 on off-intent prefixes while the GRU rises from 0.6610 to 0.7288; a sampled softmax replacing 46,592,000 multiply-adds per timestep with 524,544, an 88.8 times reduction; and a ladder from most-popular at 0.0514 recall@20 and 0.0118 MRR@20 through item-kNN at 0.2871, a Markov chain at 0.3062 and session-kNN at 0.3344 to GRU4Rec at 0.3418 and 0.1326, serving in 2.4 milliseconds p99 inside a 12 millisecond budget, with an online result of plus 7.4% rail clicks and plus 0.6% revenue per session on a 95% interval of minus 0.3 to plus 1.5

Where a session boundary comes from

A session is a maximal run of events by one cookie with no gap longer than some constant. The constant is 30 minutes. It is the default in Google Analytics, it is the convention that the public session-recommendation datasets were all cut with, and it is not an estimate of anything. It comes from 1990s web analytics, where it was chosen because it was round.

# Sessionising a flat event stream. The constant on line 1 is the whole model.
import numpy as np
import pandas as pd

DEFAULT_GAP_S = 1800.0


def sessionise(events: pd.DataFrame, gap_s: float = DEFAULT_GAP_S,
               max_events: int | None = 40) -> pd.DataFrame:
    """Cut the stream on inactivity, and cap the result.

    The sort is not defensive. An unsorted stream produces negative gaps,
    every gap test fails open, and the output is one session per cookie,
    which looks like a data problem rather than a sort problem.

    The event cap exists because a pure gap rule has no upper bound: a bot or
    a tab with a refresh timer produces a single session of thousands of
    events that dominates every minibatch it lands in. At a 30-minute gap it
    never fires on this log; at an 8-hour gap it takes the longest session
    from 103 events to 40.
    """
    ev = events.sort_values(["cookie_id", "ts"], kind="stable").reset_index(
        drop=True)
    cookie = ev["cookie_id"].to_numpy()
    ts = ev["ts"].to_numpy()

    new_cookie = np.empty(len(ev), dtype=bool)
    new_cookie[0] = True
    new_cookie[1:] = cookie[1:] != cookie[:-1]

    gap = np.empty(len(ev))
    gap[0] = np.inf
    gap[1:] = ts[1:] - ts[:-1]

    starts = new_cookie | ((~new_cookie) & (gap > gap_s))
    ev["session_id"] = np.cumsum(starts) - 1
    if max_events is not None:
        ev = _apply_event_cap(ev, max_events)
    return ev

The reason to care is that the constant has two failure directions with different costs, and the offline metric prefers the wrong one.

Shortening the gap over-splits. It cuts inside real sessions, which throws away the prefix the model would have conditioned on. At a 10-minute gap this log becomes 54.2 million sessions instead of 41.6 million, and 44.1% of them hold a single event, up from 21.4%. A single-event session carries no next-item target, so the training data that was destroyed is invisible to the metric. Offline recall@20 went UP, 0.3418 to 0.3604, and the online add-to-cart rate fell 2.8% in a two-week test. The mechanism is that over-splitting makes the evaluation easier at the same time as it makes the model worse: a shorter prefix means the held-out next item is the immediately adjacent click rather than something three clicks away.

Lengthening the gap under-splits. It glues two shopping intents into one sequence, so the model is trained to predict an item from intent two given a prefix that is entirely intent one. At a 2-hour gap, 26.4% of inferred sessions contain events from more than one real visit, which is label noise that no amount of model capacity fixes, and recall@20 fell to 0.3211.

Common Pitfall

Tuning the inactivity gap on downstream recall. It is the obvious thing to do, it is cheap, and it will drive the constant to the shortest value you sweep and destroy the problem while the number goes up. The companion codebase sweeps it against a known ground truth, which is the one thing synthetic data is genuinely good for, and the result is unambiguous: boundary F1 against the true sessions peaks at 0.8606 with a 15-minute gap and the 30-minute default scores 0.8296, while downstream recall@20 peaks at 0.6049 with a 5-minute gap and falls monotonically to 0.5279 at 8 hours. The two curves disagree about the answer. At the 2-minute end, boundary recall is 0.9702 and boundary precision is 0.4753, mean session length falls to 1.98 events, and 50.77% of sessions end up with one event, which is half the training data gone for a metric that improved. The discipline that prevents this is to score the boundaries directly, once, against whatever ground truth you can construct, which for most teams is a few thousand hand-labelled visits or a client-side session id the front end already emits and nobody plumbed through, and then to freeze the constant and never touch it again. A session boundary is a data contract, not a hyperparameter, and the moment it becomes tunable every metric in the project becomes incomparable to every metric from last quarter.

The split is temporal and the examples are prefixes

Post 21 established the temporal leave-one-out split for a matrix-factorisation recommender: hold out each user’s most recent interaction. A session model needs something different, because the unit is the session and the session has no future beyond itself.

# Whole sessions, allocated at QUANTILES of the session start time.
import numpy as np
import pandas as pd


def temporal_session_split(tab: pd.DataFrame, test_frac: float = 0.20,
                           valid_frac: float = 0.12) -> tuple:
    """Train on sessions that started before T, test on sessions after T'.

    Allocation is by session COUNT at quantiles of the start time, not by
    wall-clock fraction of the range. Traffic is not uniform in time, and the
    error is large in the direction nobody checks: on the synthetic log in the
    companion codebase, cutting at the last 20% of the wall-clock range yields
    781 test sessions, 3.01% of the log, against the 5,190 that 20% of the
    sessions is. A 0.15x test set, not a 1.2x one. Any real log with a weekday
    cycle, a promotion, or a backfill in it has the same problem, and the
    symptom is a test metric that moves by 0.03 between seeds.
    """
    order = np.argsort(tab["start_ts"].to_numpy(), kind="stable")
    t = tab.iloc[order].reset_index(drop=True)
    n = len(t)
    n_test = int(round(test_frac * n))
    n_valid = int(round(valid_frac * n))
    n_train = n - n_test - n_valid
    return (t.iloc[:n_train].reset_index(drop=True),
            t.iloc[n_train:n_train + n_valid].reset_index(drop=True),
            t.iloc[n_train + n_valid:].reset_index(drop=True))

The split gives 29.1 million training sessions, 5.0 million validation and 7.5 million test, and 132 million training examples under the all-prefix expansion.

The leakage risk specific to this problem is not a feature computed from the future, because there are no features. It is a random session split, and what it leaks is the popularity distribution. Item popularity is the single strongest signal in any session recommender, and it drifts with the season, the promotion calendar and the new-arrival schedule. A random split lets the training set see the test window’s popularity, which flatters the weakest model most. Measured in the companion codebase on a log with a planted popularity drift:

Model recall@20, temporal split recall@20, random split Inflation
Most popular 0.2252 0.3072 +0.0820
First-order Markov 0.5901 0.6427 +0.0526
GRU, 48 hidden units 0.6747 0.6915 +0.0168
Cold-item share of test targets 0.0306 0.0000 the leak, visible

Every row is inflated, which everybody expects. They are inflated by different amounts, which is the part that costs money: the measured value of modelling, the gap between the no-conditioning baseline and the GRU, falls from 0.4495 to 0.3843, a 14.5% understatement of the only quantity the project is deciding on.

Key Insight

The features in this model are the item ids, and that is the whole feature engineering section. There is no text, no price, no image embedding, no category one-hot, no recency decay, and nothing from post 22's field-aware text assembly. That is not minimalism, it is the architecture: the item embedding matrix IS the feature representation, and it is learned from the sequences rather than specified. The consequence is specific and it is the thing to plan for. A model whose only input is an item id has exactly one failure mode and it is total: an item with no training occurrences has an embedding still at its initialisation, so its score is noise and it cannot be ranked at all. 4,100 SKUs launch per week here and 2.9% of held-out targets are cold, which caps recall@20 at 0.9710 before any modelling. The fix is not inside the model, it is a second system: a content-based nearest neighbour of the kind post 22 built, used to initialise a new item's embedding from the mean of its nearest catalogue neighbours rather than from a Gaussian, which recovered 0.0081 of pooled recall@20 and 41% of the cold bucket. Post 23's count-gated blend is the right pattern for deciding when to stop using it, with the item's training occurrence count as the gate: below 12 occurrences serve the content-initialised embedding, above it serve the learned one, and the crossover is where the two agree on the held-out set rather than where the curve looks nice.

The Naive Baseline

Four baselines, each adding exactly one kind of conditioning, because that is the only way to attribute the final gain to anything. This is the same discipline post 24 applied to objectives: change one thing at a time or do not quote the number.

# The two models that condition on the last item only, and differ in symmetry.
import numpy as np


class ItemKNN:
    """Cosine item-item co-occurrence, conditioned on the last click.

    The co-occurrence matrix is SYMMETRIC by construction, which is the point
    of including it: sim[a, b] cannot distinguish "viewed a then b" from
    "viewed b then a". That is the same structural limit the confidence-
    weighted ALS of post 21 has, because a factorisation of a symmetric
    co-view matrix has no direction in it either.
    """

    def __init__(self, n_items: int, shrink: float = 10.0):
        self.n_items, self.shrink = n_items, shrink
        self.sim = np.zeros((n_items, n_items), dtype=np.float32)

    def fit(self, sessions) -> "ItemKNN":
        co = np.zeros((self.n_items, self.n_items), dtype=np.float32)
        cnt = np.zeros(self.n_items, dtype=np.float32)
        for items in sessions:
            uniq = np.unique(np.asarray(items, dtype=int))
            cnt[uniq] += 1.0
            co[np.ix_(uniq, uniq)] += 1.0
        np.fill_diagonal(co, 0.0)
        self.sim = (co / (np.sqrt(np.outer(cnt, cnt)) + self.shrink)
                    ).astype(np.float32)
        return self

    def score(self, prefixes) -> np.ndarray:
        return self.sim[np.array([p[-1] for p in prefixes], dtype=int)]


class MarkovChain:
    """First-order DIRECTIONAL transitions with a popularity backoff.

    The cheapest model that knows a -> b and b -> a are different events. It
    is also the exact information a GRU has when the prefix is one item long,
    which is why the two converge on the short-session bucket.
    """

    def __init__(self, n_items: int, backoff: float = 0.05):
        self.n_items, self.backoff = n_items, backoff
        self.trans = np.zeros((n_items, n_items), dtype=np.float32)
        self.pop = np.zeros(n_items, dtype=np.float32)

    def fit(self, sessions) -> "MarkovChain":
        for items in sessions:
            arr = np.asarray(items, dtype=int)
            self.pop[arr] += 1.0
            if len(arr) > 1:
                np.add.at(self.trans, (arr[:-1], arr[1:]), 1.0)
        self.trans /= np.maximum(self.trans.sum(axis=1, keepdims=True), 1.0)
        self.pop /= max(self.pop.sum(), 1.0)
        return self

    def score(self, prefixes) -> np.ndarray:
        last = np.array([p[-1] for p in prefixes], dtype=int)
        return self.trans[last] + self.backoff * self.pop[None, :]

The third baseline is the one that matters and the one that is usually missing. Session-kNN treats the prefix as an unordered set: build a binary item vector for each training session, find the nearest neighbours of the prefix vector under cosine similarity, and let them vote for the items they contain. It sees everything a sequence model sees except the order.

# The baseline that isolates ORDER. Everything a GRU wins over this, it wins
# because the order of the prefix carried information.
import numpy as np


class SessionKNN:
    def __init__(self, n_items: int, k: int = 120, decay: float = 0.6):
        self.n_items, self.k, self.decay = n_items, k, decay

    def fit(self, sessions) -> "SessionKNN":
        sessions = [s for s in sessions if len(s) >= 2]
        M = np.zeros((len(sessions), self.n_items), dtype=np.float32)
        for r, items in enumerate(sessions):
            M[r, np.unique(np.asarray(items, dtype=int))] = 1.0
        self.raw = M
        self.M = M / np.sqrt(np.maximum((M * M).sum(axis=1, keepdims=True),
                                       1e-9))
        return self

    def score(self, prefixes) -> np.ndarray:
        Q = np.zeros((len(prefixes), self.n_items), dtype=np.float32)
        for r, p in enumerate(prefixes):
            arr = np.asarray(p, dtype=int)
            # Recency weights are the ONLY place order enters, and it is a
            # weak concession: the vector is still a bag.
            w = np.power(self.decay, np.arange(len(arr))[::-1])
            np.add.at(Q[r], arr, w.astype(np.float32))
        Q = Q / np.sqrt(np.maximum((Q * Q).sum(axis=1, keepdims=True), 1e-9))
        sims = Q @ self.M.T
        cut = np.partition(sims, -self.k, axis=1)[:, -self.k][:, None]
        return (np.where(sims >= cut, sims, 0.0) @ self.raw).astype(np.float64)

The ladder on 7.5 million held-out sessions, last-item protocol, full catalogue:

Baseline recall@20 MRR@20 NDCG@20 Rail coverage Conditions on
Best-seller fallback (most popular) 0.0514 0.0118 0.0208 0.0001 nothing
Item-kNN co-occurrence 0.2871 0.0914 0.1335 0.41 the last click, symmetrically
First-order Markov chain 0.3062 0.1137 0.1556 0.29 the last click, directionally
Session-kNN 0.3344 0.0981 0.1517 0.38 the whole prefix, as a set

Read the second and third rows together. They condition on exactly the same information and differ only in whether the co-occurrence is symmetric, so the 0.0191 between them is the value of direction, and it is the cheapest 0.0191 in this post: a transition matrix is 30 lines and trains in 31 minutes on one CPU.

Then read the third and fourth rows together, which is where it gets interesting. Session-kNN beats the Markov chain on recall@20 by 0.0282 and loses MRR@20 by 0.0156. That inversion is not noise and it is not a tie. It is the first appearance of the pattern that decides this project, and the companion codebase makes it much sharper on synthetic data: there, session-kNN scores 0.6853 recall@20 against a GRU’s 0.6747 while losing MRR@20 by 0.0991, NDCG@20 by 0.0750 and 21.0 positions of mean rank.

Key Insight

The explanation for the recall-against-MRR inversion is one diagnostic and it took three lines to write. Compute the share of each model's TOP-1 prediction that is an item already present in the session prefix, and compare it against the share of true NEXT ITEMS that are a repeat view. The second number is a property of the data: 19.1% in production and 20.44% on the synthetic log. The first is a property of the model, and session-kNN's is 94% in production and 99.25% on the synthetic log. It is, to a very good approximation, handing the session back to the visitor. That is a cheap way to be inside a 20-slot rail on the fifth of examples that repeat and an expensive way to rank anything first, which is exactly the recall-high, MRR-low signature. The confirmation is to mask already-seen items and rerun: on the synthetic log session-kNN falls from 0.6853 to 0.5110 and the GRU from 0.6747 to 0.5105, so the entire recall advantage of the set model over the sequence model was the repeat sub-population and it disappears to within 0.0005. The transferable rule is blunt: a recall@k win by a session recommender should be checked against the model's top-1 repeat rate before it is believed, and the check costs nothing. Masking itself is a product decision with a measured cost, not a correctness fix, because a fifth of real next clicks ARE repeats and masking throws every one of them away for about 0.17 of recall@20.

The Solution

GRU4Rec is a recurrent network over item ids with a sampled-softmax output. Hidasi, Karatzoglou, Baltrunas and Tikk published it in 2016 as “Session-based Recommendations with Recurrent Neural Networks”, and reduced to its load-bearing parts it is four lines of recurrence and one trick.

The analogy for the gated recurrence: a GRU’s hidden state is a working memory with two valves on it. The update gate decides how much of the memory to overwrite with the new click, and the reset gate decides how much of the old memory to even look at when forming the candidate. When the visitor clicks a merchandised banner from an unrelated category, a model with no gates overwrites its state with the banner and the thread is gone. A gated model can learn to hold the valve shut.

The architecture, written out

# A GRU over item ids. Forward pass, in numpy, with no framework.
import numpy as np


def _sigmoid(x: np.ndarray) -> np.ndarray:
    return 0.5 * (1.0 + np.tanh(0.5 * x))


class SessionGRU:
    """item id -> embedding -> GRU -> score every item -> sampled softmax.

    A GRU rather than an LSTM because a session is short. The median session
    here is 3 events and the 95th percentile is 12, so the long-range
    forgetting an LSTM's separate cell state buys has nothing to do, and the
    GRU's two gates against the LSTM's three are 25% fewer recurrent
    matrices for no measured loss. Hidasi's own ablation reported the same.
    """

    def _forward(self, X: np.ndarray) -> tuple:
        """Run the recurrence over a padded (B, T) batch of item ids."""
        B, T = X.shape
        Ex = self.E[X]
        h = np.zeros((B, self.h_dim))
        H = np.empty((B, T, self.h_dim))
        cache = []
        for t in range(T):
            x = Ex[:, t, :]
            z = _sigmoid(x @ self.Wz + h @ self.Uz + self.bz)   # update gate
            r = _sigmoid(x @ self.Wr + h @ self.Ur + self.br)   # reset gate
            rh = r * h
            nt = np.tanh(x @ self.Wn + rh @ self.Un + self.bn)  # candidate
            h = (1.0 - z) * h + z * nt
            cache.append((x, h, z, r, rh, nt))
            H[:, t, :] = h
        return H, cache

The production configuration is a 256-dimensional embedding tied to the output layer, a 256-unit single GRU layer, and 46.9 million parameters at 187 MB in float32. Tying the input embedding to the output layer is worth more than it looks and the mechanism is about gradient supply rather than capacity: an item seen four times gets four updates as an input and four as an output, and tying pools them into eight updates of one vector. Measured in the companion codebase it scores 0.6776 recall@20 against 0.6747 untied with 21% fewer parameters, which is the best configuration there, and on a 182,000-item catalogue where the tail is far longer the argument is stronger.

The backward pass, because it is where the bugs live

# Backpropagation through time, by hand. Accumulates into `g` in place.
import numpy as np


def _backward(self, X: np.ndarray, cache: list, dH: np.ndarray,
              g: dict) -> None:
    B, T = X.shape
    dh_next = np.zeros((B, self.h_dim))
    for t in range(T - 1, -1, -1):
        x, h_prev, z, r, rh, nt = cache[t]
        dh = dH[:, t, :] + dh_next
        dz = dh * (nt - h_prev)
        dn = dh * z
        dh_prev = dh * (1.0 - z)

        dan = dn * (1.0 - nt * nt)
        g["Wn"] += x.T @ dan
        g["Un"] += rh.T @ dan
        g["bn"] += dan.sum(axis=0)
        drh = dan @ self.Un.T
        dr = drh * h_prev
        dh_prev += drh * r

        daz = dz * z * (1.0 - z)
        dar = dr * r * (1.0 - r)
        g["Wz"] += x.T @ daz
        g["Uz"] += h_prev.T @ daz
        g["bz"] += daz.sum(axis=0)
        g["Wr"] += x.T @ dar
        g["Ur"] += h_prev.T @ dar
        g["br"] += dar.sum(axis=0)
        dh_prev += daz @ self.Uz.T + dar @ self.Ur.T

        dx = dan @ self.Wn.T + daz @ self.Wz.T + dar @ self.Wr.T
        np.add.at(g["E"], X[:, t], dx)
        dh_next = dh_prev

Reading the backward pass is worth the ten minutes for one reason: dh_prev accumulates three separate contributions, one through the direct (1 - z) path and two through the gate pre-activations, and the one through the reset gate’s drh * r term is the one that is easy to drop. In production you use a framework and autograd makes that impossible. The companion codebase keeps the hand-written version and pairs it with a finite-difference check over eleven parameter arrays and both loss functions, worst relative error 2.4e-07, because the way a hand-written BPTT is usually wrong does not raise anything: the model still trains, just worse.

The sampled softmax, which is the real content

The output layer is a softmax over 182,000 items. Computing it costs 256 times 182,000 equals 46.6 million multiply-adds per timestep, and at 132 million training examples times 6 epochs that is the entire budget. The fix is to approximate the normalisation over a sample: the true next item plus 2,048 negatives, which is 256 times 2,049 equals 524,544, an 88.8 times reduction.

# The sampled softmax. Three decisions live in this function and none of them
# is visible behind a framework's cross_entropy call.
import numpy as np


def _logsumexp(x: np.ndarray, axis: int = -1) -> np.ndarray:
    m = np.max(x, axis=axis, keepdims=True)
    return (m + np.log(np.sum(np.exp(x - m), axis=axis, keepdims=True))
            ).squeeze(axis)


def _output_grads(self, Hf: np.ndarray, Y: np.ndarray, neg: np.ndarray,
                  g: dict) -> tuple:
    """Loss, dHf, and the output-layer gradients for one minibatch.

    Hf  (M, h)  the hidden state at every scored timestep in the batch
    Y   (M,)    the true next item at each one
    neg (N,)    the negative set, SHARED across the batch
    """
    M = len(Y)
    Vp, Vn = self.V[Y], self.V[neg]
    s_pos = np.einsum("md,md->m", Hf, Vp) + self.bo[Y]
    s_neg = Hf @ Vn.T + self.bo[neg]

    # Decision 1: the collision guard. A negative drawn from a popularity
    # distribution hits the true target on 3.4% of steps at 2,048 out of
    # 182,000, and an item asked to rank below itself is not a useful
    # gradient. Measured cost of omitting it: 0.0015 recall@20, which is 300x
    # smaller than the collision rate, because a collided pair contributes a
    # logit difference of exactly zero and therefore dilutes the update
    # rather than reversing it.
    collide = neg[None, :] == Y[:, None]
    logits = np.concatenate([s_pos[:, None], np.where(collide, -1e9, s_neg)],
                            axis=1)
    lse = _logsumexp(logits, axis=1)
    loss = float(np.mean(lse - s_pos))

    p = np.exp(logits - lse[:, None])
    dl = p / M
    dl[:, 0] -= 1.0 / M
    dpos, dneg = dl[:, 0], dl[:, 1:]

    dHf = dpos[:, None] * Vp + dneg @ Vn
    np.add.at(g["V"], Y, dpos[:, None] * Hf)
    np.add.at(g["V"], neg, dneg.T @ Hf)
    np.add.at(g["bo"], Y, dpos)
    np.add.at(g["bo"], neg, dneg.sum(axis=0))
    return loss, dHf

The second decision is the negative distribution, and it is the largest single effect in this model. Three options:

Uniform draws each negative uniformly from the catalogue. On a Zipf catalogue almost every draw is a tail item the model already ranks low, so the gradient confirms what it knows, and the pairs it actually confuses, two mid-popularity items in the same category, are almost never sampled. Measured here: 0.3177 recall@20 against 0.3418, a cost of 0.0241.

Popularity-proportional draws with probability proportional to the training count raised to 0.75, which is the word2vec exponent and is there for the same reason. These are the items the model confuses. This is what shipped.

In-batch uses the other targets in the minibatch as the negatives, which is Hidasi’s own trick and is why GRU4Rec trains fast: the negatives are already in memory so they cost nothing to fetch, and they are drawn from the empirical popularity distribution by construction. It scores 0.3365 at a batch size of 512. The thing to know is that the effective negative distribution is then a function of the batch size, so tuning the batch size for throughput silently changes the objective.

The third decision is the count, and it has a knee and then flattens: 256 negatives scores 0.3104, 1,024 scores 0.3381, 2,048 scores 0.3418, and 8,192 scores 0.3425 for four times the cost. The training cost is linear in the count, so the knee is the whole decision.

Common Pitfall

Early stopping on the training loss. Every other gradient-descent job has a loss that goes down and a validation loss that turns around, and this one does not, for a reason that is structural rather than incidental. The loss is a cross-entropy over a SAMPLED support, so its level depends on how many negatives there are and which distribution they came from. A configuration with 8,192 negatives has a mechanically higher loss than one with 256 at identical quality, because it is a softmax over more competitors. Two models whose sampled losses are 1.84 and 2.31 can rank in either order on recall@20. Worse, the sampled loss on this problem falls monotonically through every epoch of the budget while validation recall@20 peaks and turns: measured in the companion codebase, the loss goes 3.7280, 3.2627, 3.1476, 3.0869, 3.0285, 2.9904, 2.9661, 2.9253 while validation recall@20 goes 0.6701, 0.6774, 0.6792, 0.6818, 0.6774, 0.6714, 0.6723, 0.6658. Stopping on the loss does not stop late, it never stops, and the extra epochs cost 0.0160 off the peak. Early stop on validation recall@20 computed by the same function that produces the final table, and size the patience against the standard error of that metric rather than picking 2 because it is a nice number: a 440-target recall@20 has a standard error of roughly 0.022, so a patience of 2 on single-epoch improvements smaller than 0.04 is a coin flip and will stop a perfectly good model at epoch 1.

The minibatch, which is not the obvious one

# Length-bucketed minibatches of whole sessions.
import numpy as np


def _batches(self, sessions: list, rng: np.random.Generator):
    """Sort by length, cut contiguous batches, pad within the batch.

    Padding every session to the global maximum wastes 84.89% of the
    timesteps on this length distribution, measured: the mean trainable
    session is 4.99 events and the longest is 33 after the bot cap. Length
    bucketing takes the waste to 1.28% and is two lines.

    Hidasi's session-parallel minibatch is the better answer at scale and is
    a different idea: keep B session CURSORS active, and when one session
    ends, slide the next session into that row and reset only that row's
    hidden state. It wastes nothing at all and it is what you want when
    sessions are long and their length distribution is wide.
    """
    order = np.argsort([len(s) for s in sessions], kind="stable")
    groups = [order[i:i + self.batch_size]
              for i in range(0, len(order), self.batch_size)]
    rng.shuffle(groups)
    for gidx in groups:
        seqs = [sessions[i] for i in gidx]
        T = max(len(s) for s in seqs)
        X = np.zeros((len(seqs), T), dtype=int)
        mask = np.zeros((len(seqs), T), dtype=bool)
        for r, s in enumerate(seqs):
            X[r, :len(s)] = np.asarray(s, dtype=int)
            mask[r, :len(s)] = True
        yield X, mask

Hyperparameters that mattered, with values

n_negatives at 2,048 with a popularity exponent of 0.75. The largest single dial. Uniform negatives cost 0.0241 recall@20, 256 negatives cost 0.0314, and 8,192 buy 0.0007 for four times the compute.

hidden_dim at 256 with a tied 256-dimensional embedding. Capacity saturates early and the companion codebase shows the shape clearly: 16 units underfit by 0.0145 and 128 units buy 0.0008 over 48 for three times the item-independent parameters. In production 256 beat 128 by 0.0062 and 512 beat 256 by 0.0009, so the knee is real and it is low. A session model is not capacity-limited, it is context-limited.

loss at cross-entropy rather than BPR. Both are implemented over the same sampled negative set and they are different optima rather than different parameterisations of one. Cross-entropy is ahead by 0.0101 recall@20 and by 0.0298 MRR@20 in the companion codebase, and the MRR gap being the larger one is the informative part: BPR scores every negative independently against the positive, so it has no term that distinguishes being second from being twentieth, while a softmax normalises over the whole sampled set and does. Hidasi’s 2018 follow-up reaches the same conclusion from the other direction and proposes BPR-max to recover it.

Key Insight

The single design decision that mattered most was adding session-kNN to the baseline ladder, which is a decision about the experiment rather than about the model. Without it the project's headline would have been that a GRU beats a first-order Markov chain by 0.0356 recall@20 and that sequence modelling is therefore worth 0.0356, which is wrong in a way that would have survived review: the Markov chain conditions on one item and the GRU conditions on the whole prefix, so that comparison changes the CONTEXT and the model class at the same time. Session-kNN holds the context fixed at the whole prefix and changes only whether it is ordered, which puts the value of order at 0.0074 recall@20 and 0.0345 MRR@20. That decomposition changed two later decisions and both saved a quarter. It killed a planned six-week project to add dwell-time and event-type features to the sequence, because a 0.0074 order effect bounds what any refinement of the sequence representation can be worth. And it redirected that time to the cold-start path, where the content-initialised embedding recovered 0.0081, more than the entire value of order, for two weeks of work reusing post 22's content model. This is the same lesson post 24 reached through the matched-model-class rule: attributing a gain to the right cause is worth more than the gain, because the attribution is what tells you where the next quarter goes.

The traps that are specific to this method, with the numbers

Four session-recommender failures that coexist with a healthy recall@20: an inactivity-gap sweep where boundary F1 against the true sessions peaks at 0.8606 with a 15-minute gap and the 30-minute default scores 0.8296, while downstream recall@20 peaks at 0.6049 with a 5-minute gap and falls monotonically to 0.5279 at 8 hours, and where a 2-minute gap leaves 50.77% of sessions holding one event and 0.78% mixed-intent against 70.87% mixed at 8 hours; a prefix-length breakdown where a first-order Markov chain beats a GRU on one-click prefixes 0.6452 to 0.6040 because both condition on identical information there, and loses by 0.1379 on prefixes of 5 to 8 and 0.1560 on prefixes of 9 or more, with 24.57% of test targets coming from a one-click prefix and 25.60% of sessions producing no target at all; a sampled-negative evaluation panel where the most-popular baseline gains 0.3087 against 100 uniform negatives and the GRU gains 0.0861, shrinking the measured value of modelling from 0.4602 to 0.2353, and where popularity-sampled negatives reorder the top two models; and a repeat-prediction panel where session-kNN's top-1 is an item already in the session 99.25% of the time against a ground-truth repeat rate of 20.44%, which is why it wins recall@20 by 0.0106 and loses MRR@20 by 0.0991, next to the production A/B where a variant with plus 0.0310 offline recall@20 lost 1.2% revenue per session by filling 87% of the rail with same-category substitutes

The second panel is the one that changes how the team plans. 24.1% of production evaluation targets come from a session with exactly one prior click, and on that bucket a GRU and a transition matrix see identical information, so the GRU has no structural advantage and in fact loses slightly: 0.2140 against the Markov chain’s 0.2229 in production, and 0.6040 against 0.6452 on the synthetic log. The transition matrix is a maximum-likelihood estimate of precisely the conditional being asked for; the GRU has to reach the same quantity through a 256-dimensional embedding and a gated state, and it pays a small approximation cost for the privilege.

The mechanism behind the long-prefix win is isolable, and it is the only thing in this post that is purely about sequences. Split recall by whether the LAST click in the prefix is off-intent, taking the session’s intent as the modal category of the prefix. On the synthetic log, where that structure is planted and measurable:

Model Share of prefixes off-intent recall@20, last click on-intent recall@20, last click off-intent
First-order Markov chain 0.2018 0.6477 0.3625
Session-kNN 0.2018 0.6731 0.7339
GRU, 48 hidden units 0.2018 0.6610 0.7288

The Markov chain collapses by 44% relative when the visitor’s last click was a distraction, because that click is all it conditions on. The GRU goes up, from 0.6610 to 0.7288, because the intent is still in the prefix and the reset gate can decline to overwrite it. Set the distraction probability to zero in the generator and the planted structure disappears, and so does most of the reason to use a sequence model. That is the honest framing of a GRU4Rec result: it is worth what the long-range dependency in your log is worth, and you can measure that before you build anything, by comparing a bigram counter against a trigram counter on the sub-population where the last click is a category outlier.

Evaluation and Metrics

Four metrics, and the fact that one of them carries no information is worth knowing.

recall@20 is the optimisation target. With exactly one relevant item it is a hit rate: 1 if the true next item is anywhere in the 20 slots, else 0. It is what the session-recommendation literature reports as Recall@20 and it is the right primary metric for a rail where all 20 slots are equally visible.

MRR@20 is one over the rank, or zero outside the top 20. It is the guardrail that caught the repeat-prediction problem, and it is the metric to watch when the rail has a visual hierarchy.

NDCG@20 with a single relevant item is one over the log of the rank plus one, which is a monotone reparameterisation of MRR and carries no information MRR does not. It is reported because papers report it, and the fact that it adds nothing is the useful thing about it.

Catalogue coverage is the share of SKUs appearing in any top 20 over a day. It is not an accuracy metric and no accuracy metric implies it.

# The tie rule is written out rather than left to argsort, because it is not
# neutral between models.
import numpy as np


def rank_of_target(scores: np.ndarray, targets: np.ndarray) -> np.ndarray:
    """1-based PESSIMISTIC rank: items scoring higher, plus every tied item.

    Measured on the synthetic log, optimistic against pessimistic ties:

        most popular        0.2252 -> 0.2252   (+0.0000)
        item-kNN            0.5056 -> 0.5351   (+0.0296)
        first-order Markov  0.5901 -> 0.5901   (+0.0000)
        session-kNN         0.6853 -> 0.6965   (+0.0112)
        GRU                 unaffected, no exact ties

    The pattern is the point. A sparse score matrix has 34.0% exact zeros for
    item-kNN and 68.5% for session-kNN, and the mean target is tied with 28.8
    and 42.6 other items, so a generous rule hands those models free rank. A
    count-based model with almost no ties and a neural model with continuous
    scores get nothing. Choosing the generous rule widens the session-kNN to
    GRU recall gap from 0.0106 to 0.0218 without changing a single model.
    """
    tgt = scores[np.arange(len(targets)), targets]
    return (np.sum(scores > tgt[:, None], axis=1)
            + np.sum(scores == tgt[:, None], axis=1))


def evaluate(scores: np.ndarray, targets: np.ndarray, k: int = 20) -> dict:
    rank = rank_of_target(scores, targets)
    hit = rank <= k
    top = np.argpartition(-scores, kth=k, axis=1)[:, :k]
    return {
        f"recall@{k}": float(hit.mean()),
        f"mrr@{k}": float(np.mean(np.where(hit, 1.0 / rank, 0.0))),
        f"ndcg@{k}": float(np.mean(np.where(
            hit, 1.0 / np.log2(rank + 1.0), 0.0))),
        f"coverage@{k}": int(len(np.unique(top))),
        "mean_rank": float(rank.mean()),
    }

The full ladder on 7.5 million held-out sessions:

Configuration recall@20 MRR@20 NDCG@20 recall@20, 1-click prefix Rail coverage Top-1 repeat rate
Best-seller fallback 0.0514 0.0118 0.0208 0.0601 0.0001 0.04
Item-kNN co-occurrence 0.2871 0.0914 0.1335 0.2104 0.41 0.24
First-order Markov chain 0.3062 0.1137 0.1556 0.2229 0.29 0.17
Session-kNN 0.3344 0.0981 0.1517 0.2086 0.38 0.94
GRU, 256 units, uniform negatives 0.3177 0.1218 0.1662 0.2098 0.49 0.20
GRU, 256 units, in-batch negatives 0.3365 0.1301 0.1771 0.2131 0.51 0.21
GRU, 256 units, popularity negatives 0.3418 0.1326 0.1810 0.2140 0.52 0.21
GRU, BPR over the same negatives 0.3317 0.1028 0.1534 0.2088 0.47 0.19
GRU, untied input and output embeddings 0.3371 0.1294 0.1766 0.2117 0.50 0.21
GRU, plus content-initialised cold embeddings 0.3499 0.1351 0.1847 0.2206 0.58 0.21

Five readings, and only the first is about the model.

The shipped configuration is row seven at 0.3418, which is 0.2904 above the best-seller fallback and 0.0074 above session-kNN. That 0.0074 is the value of order, and it is small. It is also not the whole story, because the same row is 0.0345 ahead on MRR@20 and serves 0.52 of the catalogue against 0.38.

The one-click-prefix column is the one to read second. Every learned model sits between 0.2086 and 0.2206 there, and the first-order Markov chain wins it outright at 0.2229. A quarter of the traffic is a bucket where none of this work helped.

The BPR row is a reminder that an objective is not a detail. It costs 0.0101 recall@20 and 0.0298 MRR@20 against cross-entropy on identical negatives, and the MRR loss being three times the recall loss is the signature of an objective with no notion of ordering within the sampled set.

The last row is the largest single improvement in the table and it is not a modelling change. Initialising a cold item’s embedding from the mean of its content nearest neighbours, using post 22’s text model, bought 0.0081 pooled, 0.0066 on the one-click bucket and 0.06 of catalogue coverage. More than the entire value of order, for two weeks of work.

Metric That Matters

The metric that catches silent degradation here is not recall@20 on a fresh holdout, it is the **daily triple of the one-click-prefix recall, the top-1 repeat rate, and the same-category share of the rail, computed over a frozen cohort of 200,000 sessions**. It has fired four times in fourteen months and pooled recall@20 caught none of them. Once when a front-end release changed the page-view beacon so that a product-page refresh emitted a duplicate event: the top-1 repeat rate went from 0.21 to 0.38 in one deploy, because the model was being trained on sequences where the next item genuinely was the current one 38% of the time, and pooled recall@20 went UP by 0.011 while the rail became visibly useless. Once when the nightly retrain silently trained on 11 days instead of 90 after a partition-pruning change, which took catalogue coverage from 0.52 to 0.31 and one-click recall from 0.2140 to 0.1802 while pooled recall@20 moved 0.004. Once when an upstream category remap broke the same-category guardrail rather than the model, which is the only one of the four that was not a model problem and was still worth catching in two hours rather than in three weeks of merchandising complaints. And once correctly: a seasonal shift into outdoor furniture legitimately moved the same-category share and the audit flagged it as expected. The general lesson is that a session model's pooled metric is dominated by the long sessions it is best at, so the failures that matter show up in a sub-population and in the SHAPE of what is served, never in the average.

The sampled-negative protocol, and why the published numbers are not comparable

Post 21 established that evaluating a recommender against a sampled set of negatives rather than the full catalogue distorts the metric. The session case is worse in two specific ways, and both are measurable.

Model Full catalogue 100 uniform negatives 100 popularity negatives
Best-seller fallback 0.0514 0.8611 0.2104
Item-kNN co-occurrence 0.2871 0.9204 0.6718
First-order Markov chain 0.3062 0.9388 0.6904
Session-kNN 0.3344 0.9541 0.6833
GRU, popularity negatives 0.3418 0.9502 0.7259

The distortion is not a constant offset. The best-seller fallback gains 0.8097 against 100 uniform negatives and the GRU gains 0.6084, so the measured value of modelling collapses from 0.2904 to 0.0891, which is 69% of it gone. A no-conditioning model needs only to beat 100 arbitrary items drawn uniformly from a Zipf catalogue, and that is nearly free.

And the protocol reorders the top two. Session-kNN ranks first against 100 uniform negatives and the GRU ranks first on the full catalogue, because the set model’s repeat trick is almost always sufficient against a hundred random items and almost never sufficient against 182,000. The companion codebase reproduces the same reordering with the popularity-sampled protocol on synthetic data. Two papers reporting Recall@20 against 100 sampled negatives can disagree about which model is better and both be arithmetically correct. Krichene and Rendle’s 2020 “On Sampled Metrics for Item Recommendation” is the reference, and its conclusion is the right one.

Key Insight

Read the last column of the ladder table rather than the first and it becomes a different document. The top-1 repeat rate is 0.17 for the Markov chain, 0.21 for every GRU configuration, and 0.94 for session-kNN, against a ground-truth repeat rate of 0.19. Every model within 0.03 of the data's own rate is doing something defensible; the one at 0.94 is returning the visitor's own session to them and collecting recall@20 for it. The reason this is the column that predicted the online results best, in all three experiments that ran, is that a rail slot filled with an item the visitor looked at ninety seconds ago has an opportunity cost that no next-item metric can see: it is a slot that could have held something new, and the business value of the rail is entirely in the slots that hold something new. The practical consequence is to compute the repeat rate in the same function that computes recall, and to treat the gap between the model's rate and the data's rate as a guardrail with a cap rather than as a curiosity. It costs three lines, it explained the entire baseline ladder, and it is the only column in the table that would have been uncomfortable to look at while the project was going well.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
Tuning the inactivity gap on recall It is the only number you have, and it moves Score boundaries against a ground truth; F1 peaks at 15 min, recall at 5 min Freeze the gap as a data contract; score it once, never tune it
Over-splitting the stream A shorter gap feels conservative Share of 1-event sessions; 21.4% at 30 min, 44.1% at 10 min Check that share before and after any gap change
Under-splitting the stream A longer gap feels like more context Share of sessions with more than one intent; 26.4% at 2 hours Cap the session by event count and duration as well as gap
Random session split The frame looks like any other tabular dataset Re-split temporally; most-popular inflates 0.0820 and the GRU 0.0168 Split at quantiles of session start time, by session count
Wall-clock temporal cut “Last 20% of the range” sounds like “last 20% of the data” Count the test sessions; 3.01% against an intended 20% Allocate at quantiles of the start time, not of the clock
Early stopping on the sampled loss Every other training job has a loss curve Plot both; the loss falls 8 epochs while recall peaks at 3 Early stop on validation recall@20, patience sized to its standard error
Comparing losses across negative counts They are both called “loss” They are softmaxes over different supports; 1.84 can beat 2.31 Compare on the ranking metric only
Uniform negative sampling It is the default and it is unbiased Sweep the distribution; uniform costs 0.0241 recall@20 Popularity-proportional at exponent 0.75, or in-batch
A negative that is the positive Nobody checks, and it does not crash Collision rate; 3.4% at 2,048 out of 182,000 Mask the collided logit; worth 0.0015, and it is still correct
Reporting against 100 sampled negatives It is 1,800x cheaper and the papers do it Compute both; the model-to-baseline gap shrinks 69% and the top two swap Full catalogue, or do not compare to anyone else’s number
Omitting a set-based baseline A Markov chain feels like the obvious baseline Add session-kNN; it beats the GRU on recall@20 Hold the context fixed and vary only the ordering
Believing a recall@k win It is the metric the literature reports Top-1 repeat rate; 0.94 for session-kNN against a data rate of 0.19 Report MRR@20 and the repeat rate next to every recall number
Ignoring the one-click bucket It is averaged away recall@20 by prefix length; a Markov chain wins the bucket Report it separately; it is 24.1% of targets
Cold items counted as model error An item id is the only feature Share of targets absent from training; 2.9%, capping recall at 0.9710 Content-initialised embeddings with a count gate, post 22 and 23
Key Insight

Sort that table by the detection column and the same pattern appears that post 24 found in its own pitfall table, with one addition that is specific to sessions. Eleven of the fourteen rows are detected by comparing two numbers that a standard pipeline produces only one of: the metric under two gap constants, the metric under two split protocols, the metric under two evaluation protocols, the model's repeat rate against the data's repeat rate, recall by prefix length rather than pooled, the loss curve against the validation curve. The addition is that four of those pairs are not model comparisons at all, they are comparisons of two DATA CONSTRUCTIONS of the same log: a 10-minute and a 30-minute sessionisation, a temporal and a random split, a last-item and an all-prefix expansion, a full and a sampled negative set. That is new. In post 21 through 24 the dataset was given and the modelling decisions were downstream of it; here the dataset is manufactured by four constants that a reader of the final notebook cannot recover. The cheap structural fix is to make the data-construction constants arguments to the pipeline rather than module-level defaults, and to print all four of them above every metric table, so that a number without its construction is more work to produce than a number with it. In this project that single change is what surfaced the gap-tuning problem and the wall-clock split problem in the same afternoon.

Common Pitfall

The single most common mistake on this exact problem is treating the session as given. It arrives as a column called `session_id` in a table somebody else built, and every number downstream of it is conditional on a constant that is not in the model, not in the config, not in the experiment tracker and usually not in anybody's head. Five consequences, all measured above. The sessionisation becomes untunable in practice and therefore untuned, so the 30-minute convention from 1990s web analytics is silently the most important hyperparameter in the system, and it is not even optimal by its own boundary F1. The share of one-event sessions, which is the model's entire cold path, becomes invisible: at 30 minutes it is 21.4% and at 10 minutes it is 44.1%, and nobody notices the change because the column name did not change. Cross-quarter metrics become incomparable the first time somebody upstream adjusts the constant for an analytics dashboard. Over-splitting becomes an attractive accident, because it improves every offline metric while destroying training context, and the only way to see it is to score the boundaries directly. And the mixed-intent rate, which is pure label noise, never gets measured at all, because measuring it requires a notion of true sessions that the pipeline has already decided not to have. The discipline that prevents all five is to own the sessionisation inside the model repository, to score it against some ground truth once at the start, and to print the gap constant above every table you ever show anyone.

Scaling and Productionizing

The arithmetic that decided the serving and training architecture:

Event stream, 174M rows, 90-day window                   = 11.2 GB parquet
Sessions at a 30-minute gap                               = 41.6M, mean 4.18 events
Training examples, all-prefix expansion                   = 132M
Model, 182,000 x 256 tied embedding + 256-unit GRU        = 46.9M params, 187 MB fp32
Full softmax per timestep, 256 x 182,000                  = 46.6M multiply-adds
Sampled softmax per timestep, 256 x 2,049                 = 524K  (88.8x less)
One training epoch, 132M examples, batch 512, 1 GPU       = 2.1 h
Full training, 6 epochs with early stopping at 5          = 12.6 h
GRU forward over a median 4-click prefix at serving       = 0.3 ms p99
ANN top-200 over the 182,000-row output table (HNSW)      = 1.4 ms p99
Exact rescoring of the 200 candidates                     = 0.1 ms p99
Full rail stage at 9,400 QPS on 18 replicas               = 2.4 ms p99  (budget 12)
Hidden state cached per session, 256 x fp16                = 512 bytes
Peak concurrent sessions                                   = 2.8M, so 1.4 GB
Embedding refresh for same-day SKUs, partial update        = 15 min cadence

The 187 MB model is not the operational problem and the hidden-state cache is. Scoring is cheap; the thing that makes this architecture different from the matrix-factorisation system it replaced is that the model is stateful at request time. A user-factor lookup is idempotent: the same user id gives the same vector forever. A session model’s output depends on a hidden state that must either be recomputed from the prefix on every request or cached and invalidated correctly. We cache, 512 bytes per session against the session cookie with a 35-minute TTL that deliberately exceeds the 30-minute gap, and the recomputation path exists for cache misses and costs 0.3 ms for a median prefix. The decision that made this tractable was to cap the prefix at the last 20 clicks for serving, which costs 0.0004 recall@20 and bounds the recompute cost.

The retrain is nightly and the embedding refresh is not. 4,100 SKUs launch per week and merchandising expects them in the rail the same day, which a 12.6 hour retrain cannot deliver. The split is: the GRU weights and the existing item embeddings are retrained nightly; new items get a content-initialised embedding from post 22’s text model every 15 minutes, frozen until the next full retrain picks them up. The count gate from post 23 decides which to serve, with the item’s training occurrence count as the gate and a crossover at 12 occurrences chosen where the two embeddings agreed on the held-out set.

Offline recall@20 and the online basket effect diverge, and the divergence is the main finding of this project. The shipped model gained 0.0074 recall@20 over session-kNN and, over a three-week A/B on 4.1 million sessions per arm, gained 7.4% on rail click-through, 4.1% on add-to-cart from the rail, and 0.6% on revenue per session with a 95% interval of minus 0.3% to plus 1.5%. The offline metric was significant and the business metric was not. It shipped on the rail engagement, the coverage gain and the removal of the best-seller fallback, which is a defensible decision and is not the decision the offline number implied.

The variant that made the point is the one that did not ship. A configuration with a deeper GRU and a longer effective context scored 0.3728 recall@20, plus 0.0310 over the shipped model, which is four times the entire value of order and was the best offline number the project produced. Online it gained 11.2% on rail clicks and lost 1.2% revenue per session, with a 95% interval of minus 2.0% to minus 0.4%. The diagnosis took two days and is in the guardrails: its rail was 87% same-category items against the shipped model’s 61%, and mean basket size fell from 2.31 items to 2.27. It had learned to predict the next click extremely well by predicting the near-substitute the visitor was going to click anyway, which earns a click and cannibalises the basket instead of adding to it. Next-item accuracy rewards predicting the click that was going to happen without you. The permanent fix was the same-category share guardrail with a cap at 70%, and the roadmap item is a complementary-item objective rather than a next-item one.

Key Insight

The operational difference between this model and the matrix factorisation it replaced is statefulness, and it was the longest conversation in the project by a wide margin. A user-factor lookup is idempotent: the same user id returns the same vector until the next retrain, so the serving path is a key-value read and the cache is a performance optimisation you could delete. A session model's output depends on a hidden state that is a function of the prefix, which means every request either recomputes it or reads it from a cache that has to be invalidated correctly, and "correctly" here is coupled to the sessionisation constant in a way that is easy to get wrong: the cache TTL must EXCEED the inactivity gap, 35 minutes against 30, or the cache entry expires while the session it describes is still live and the visitor's fifth click is scored as though it were their first. That single constraint produced 1.4 GB of cache at 2.8 million concurrent sessions, a cache-miss recompute path, a 20-click prefix cap to bound that path at 0.0004 recall@20, and two weeks of work, against two days for the negative-sampling decision that was worth 0.0241. The general point is that the accuracy comparison in the alternatives table omits the column that actually separates the rows, and if your best sequence model is 0.0074 recall@20 ahead of a stateless set-based baseline then the decision is not really about the number.

The monitoring signal for silent degradation is the daily triple described in the metric callout: one-click-prefix recall, top-1 repeat rate, and same-category rail share over a frozen 200,000-session cohort. The one-click recall catches a training-window or coverage regression. The repeat rate catches an upstream event-stream change, which is the failure that has happened most and is the one pooled recall@20 actively hides. The same-category share catches the cannibalisation mode above, which no accuracy metric can see at all.

Real World

GRU4Rec is Hidasi, Karatzoglou, Baltrunas and Tikk, ICLR 2016, "Session-based Recommendations with Recurrent Neural Networks", and the lineage after it is unusually instructive. Their 2018 follow-up, "Recurrent Neural Networks with Top-k Gains for Session-based Recommendations", is the more useful paper of the two because it is almost entirely about the sampled softmax: it introduces additional negative samples beyond the minibatch and the BPR-max loss, and reports that those two changes together are worth more than the architecture was. Tan, Xu and Liu's 2016 "Improved Recurrent Neural Networks for Session-based Recommendations" adds data augmentation by prefix expansion and privileged-information distillation. The counterweight is Ludewig and Jannach's 2018 "Evaluation of Session-based Recommendation Algorithms", which compared neural session models against nearest-neighbour baselines on four datasets and found the simple methods competitive with or ahead of GRU4Rec on most of them, and Dacrema, Cremonesi and Jannach's 2019 "Are We Really Making Much Progress?" which made the same point across the recommender literature. Both are the reason session-kNN is a first-class baseline in this post rather than a footnote. On the metric side, Krichene and Rendle's 2020 "On Sampled Metrics for Item Recommendation" is the paper that should be read before any session-recommendation number is quoted. In production, YOOCHOOSE's own RecSys 2015 challenge dataset is where most of this work was validated and is a real e-commerce clickstream cut at a 30-minute gap; Alibaba's 2018 "Billion-scale Commodity Embedding" paper describes the session-graph variant they run at a catalogue size two orders larger than this one; and Amazon's "Customers who viewed" rail is the product surface this post is about, built originally on item-to-item collaborative filtering (Linden, Smith and York, 2003) which is the item-kNN row of the ladder and is still a strong baseline twenty-three years later.

Alternative Approaches

Approach recall@20 MRR@20 Training cost Inference p99 Best fit
Best-seller fallback 0.0514 0.0118 none 0.1 ms the fallback when the model service is down, and nothing else
Item-kNN co-occurrence 0.2871 0.0914 22 min, 1 CPU 0.8 ms a defensible first version in an afternoon, with no training pipeline
First-order Markov chain 0.3062 0.1137 31 min, 1 CPU 0.9 ms short sessions; it wins the one-click bucket outright at 0.2229
Session-kNN 0.3344 0.0981 index only 6.2 ms when recall@20 is the only reported metric, which is a reason to be suspicious
GRU4Rec, 256 units, popularity negatives 0.3418 0.1326 12.6 h, 1 GPU 2.4 ms what shipped: best MRR, best coverage, and a stateful serving path
Two-tower with mean-pooled session 0.3194 0.1103 8.1 h, 1 GPU 1.6 ms when you need retrieval over 182,000 rather than reranking; post 27
SASRec, self-attention over the session 0.3607 0.1418 19.4 h, 1 GPU 4.8 ms longer sessions and a bigger GPU budget; the roadmap item
BERT4Rec, masked-item pretraining 0.3641 0.1402 41 h, 2 GPUs 5.1 ms when the sessions are long enough that bidirectional context exists

What shipped is the fifth row, and the sixth and seventh are the two that would change the decision in different directions.

The two-tower row is not really an alternative, it is a different stage. It scores 0.0224 below the GRU because mean-pooling a session throws away the order the GRU exists to use, and it is in the table because it solves a problem the GRU does not: the GRU as deployed here reranks an ANN candidate set, and the ANN index is built over the output embedding table, which means retrieval and ranking share a representation whether or not that is a good idea. Post 27 takes that apart properly.

The self-attention rows are where the metric says to go and the honest answer is more complicated. SASRec gains 0.0189 recall@20 and 0.0092 MRR@20 over the GRU for 1.5 times the training time and 2 times the inference latency, which is a fine trade on paper. The reason it is a roadmap item rather than a shipped model is the number from the previous section: the variant that gained 0.0310 offline lost 1.2% of revenue per session. Having measured that a 0.0310 offline gain can be worth minus 1.2% online, a 0.0189 offline gain is not a reason to do anything until there is an objective whose offline movement predicts the online one. That is the actual roadmap item, and the architecture is downstream of it.

We would drop to the third row without hesitation in one situation, and have: when the session is one click long. The production serving path routes one-click prefixes to the transition matrix, which wins that bucket by 0.0089, and the GRU handles everything else. That is 24.1% of impressions served by a 30-line model, and it is worth 0.0021 of pooled recall@20 for an afternoon of routing logic.

Key Insight

The column that should decide this table is the one that is not in it, and it is not latency or training cost. It is whether the model is STATEFUL at request time, because that is the architectural commitment a session recommender makes and the one that is invisible in every comparison like this. Rows one through four are stateless functions of the prefix: hand them the same five item ids and they return the same scores, forever, with no cache, no TTL and no invalidation. Rows five through eight carry a hidden state that must be recomputed or cached, which adds a 1.4 GB cache, a 35-minute TTL that has to exceed the sessionisation gap or the cache will outlive the session it describes, a cache-miss recompute path, and a prefix cap to bound that path. That is a real operational surface, and it was the single longest conversation in the project: two weeks on the cache invalidation against two days on the negative sampler that was worth 0.0241. The general point is that the recommendation literature compares session models on accuracy and the deployment difference between a stateless and a stateful recommender is larger than any accuracy gap in this table. If the gap between your best sequence model and session-kNN is 0.0074 recall@20, as it was here, the decision is not really about the number.

Key Takeaways

  • Next-item prediction is a different objective from matrix factorisation, and the test is what each does with order. A factorisation of a user-item matrix is invariant to the order of a user’s interactions by construction, and so is a symmetric co-occurrence item-kNN. Making the co-occurrence directional, which is the cheapest possible change, is worth 0.0191 recall@20 in production and 0.0845 on the synthetic log. The value of full ordering beyond direction is a separate and much smaller quantity.
  • A session recommender has no user parameters, and that is both halves of the trade. It serves the 68.3% of events from a visitor with no usable history, which is why this project existed, and it cannot personalise to the 31.7% who do have history, which is why the matrix-factorisation model is still running alongside it.
  • The session boundary is a data contract, not a hyperparameter. Boundary F1 against a known ground truth peaks at 0.8606 with a 15-minute gap while downstream recall@20 peaks with a 5-minute gap and falls monotonically after it, so tuning the constant on recall drives it to the shortest value swept, leaves 50.77% of sessions with one event, and improves the metric while destroying the problem. A 10-minute gap raised offline recall@20 from 0.3418 to 0.3604 and cost 2.8% of the online add-to-cart rate.
  • The short-session cold path is a quarter of the traffic and the model has nothing to offer it. 21.4% of sessions have exactly one event, so they contribute zero training examples and zero evaluation targets while receiving 21.4% of the rail impressions. Of the targets that do exist, 24.1% come from a one-click prefix, where a GRU and a transition matrix condition on identical information and the transition matrix wins by 0.0089.
  • The negative-sampling distribution is the largest dial in the sampled softmax, and the count is not. Uniform negatives cost 0.0241 recall@20 against popularity-proportional ones at exponent 0.75. The count has a knee: 256 costs 0.0314, 2,048 is the default, and 8,192 buys 0.0007 for four times the compute. Reverse the ratio of negatives to catalogue size, as a small benchmark does, and the distribution result reverses with it, which is measured and documented in the companion README.
  • There is no loss curve to trust, because the loss is over a sampled support. It falls monotonically through every epoch while validation recall@20 peaks and turns, so stopping on it never stops and costs 0.0160 off the peak. The loss is also not comparable between two configurations that sample differently, so an early-stopping or model-selection rule based on it ranks models wrongly.
  • A recall@k win by a session recommender should be checked against its top-1 repeat rate before it is believed. Session-kNN beats a GRU on recall@20 and puts an item the visitor has already seen in the top slot 94% of the time in production and 99.25% on the synthetic log, against ground-truth repeat rates of 19.1% and 20.44%. Mask the seen items and the entire advantage disappears to within 0.0005.
  • Sampled-negative evaluation does not estimate the full-catalogue metric, it replaces it. Against 100 uniform negatives the no-conditioning baseline gains 0.8097 and the GRU gains 0.6084, so the measured value of modelling collapses by 69%, and the protocol reorders the top two models. If you can afford the full catalogue, compute the full catalogue; if you cannot, do not compare your number to anybody else’s.
  • Offline next-item accuracy and the online basket effect diverge, and the divergence has a direction. The shipped model gained 0.0074 offline and 0.6% revenue per session on a 95% interval spanning zero. The best offline model gained 0.0310, four times the entire value of order, and lost 1.2% revenue per session with 87% of its rail filled by same-category substitutes and basket size down from 2.31 to 2.27 items.

The counter-intuitive lesson is that the most valuable thing the GRU produced was not its 0.3418. It was the session-kNN baseline that was added to make the GRU’s number interpretable, because that baseline is what bounded the entire sequence-modelling opportunity at 0.0074 recall@20 and redirected a six-week feature project into the cold-start path, where two weeks of reusing post 22’s content model was worth 0.0081, more than order itself. The architecture was the smaller half of the work. What it bought was a frame for asking the right questions: once you know the model conditions on a sequence, you ask where the sequence comes from and discover the boundary constant; once you know it conditions on a prefix, you ask what happens when the prefix has one item and find a quarter of the traffic the model cannot help; once you know the output is an approximated softmax, you ask what the approximation is over and find the distribution that was worth 0.0241. None of those is a fact about recurrent networks, and none of them would have been asked without one.

Frequently Asked Questions

Q: Why not use a transformer instead, given that SASRec scores higher? A: Eventually you should, and the table says so: SASRec gains 0.0189 recall@20 and 0.0092 MRR@20 for 1.5 times the training time and twice the inference latency. The reason it is not the first thing to build is that this project measured a 0.0310 offline gain producing a 1.2% revenue loss, so the mapping from offline recall@20 to business value is not monotone on this surface, and spending a quarter to move a metric whose sign you cannot trust is the wrong order of operations. The sequencing that makes sense is to fix the objective first, which means a complementary-item or basket-aware target rather than next-item, and then take the architecture gain on top of a metric that predicts something. There is also a structural argument for the GRU on short sessions: with a median of 3 events, self-attention is attending over three positions, and most of what the architecture buys is capacity for long-range dependencies that a three-click session does not contain.

Q: Why not just add the session to the matrix-factorisation model as extra interactions? A: It is the cheapest thing to try and it does not address the problem. Appending the current session’s clicks as temporary interactions for an anonymous pseudo-user and refactorising gives you a user vector, and that vector is a bag of items with no order in it, which puts it architecturally at the session-kNN row of the ladder rather than at the GRU row. It also needs a fold-in step per request, because a new pseudo-user has no factor, and a least-squares fold-in over 182,000 items is 4.1 ms against the GRU’s 0.3 ms forward pass. The honest version of this idea is session-kNN, which is in the ladder, scores 0.3344, is far simpler than either, and is beaten by the GRU by 0.0074 on recall@20 and 0.0345 on MRR@20.

Q: Why popularity-proportional negatives rather than uniform, and does the exponent matter? A: Because the gradient is only informative on items the model might plausibly rank above the target, and on a Zipf catalogue a uniform draw is almost always a tail item the model already places correctly. Measured: uniform costs 0.0241 recall@20 at a production ratio of 2,048 negatives to 182,000 items. The exponent of 0.75 is inherited from word2vec and the sweep is flat between 0.5 and 1.0 here, within 0.004. The important caveat is in the companion README and it is not a detail: at a small benchmark scale where the sample is 40% of the catalogue, popularity sampling spends most of its draws on duplicates of the same head items, ends up with fewer DISTINCT negatives than uniform, 89.8 against 105.7, and loses by 0.0254. The sign of this effect depends on the ratio of negatives to catalogue size, so check the distinct-negative count before concluding anything about a sampler on a small dataset.

Q: Why recall@20 rather than MRR or NDCG, and why report all three? A: recall@20 is the target because the rail has 20 equally visible slots with no fold, so a visitor who finds the item in slot 17 has had the same experience as one who found it in slot 2, and the position discounting that NDCG and MRR apply is modelling a hierarchy the product does not have. All three are reported anyway, and MRR@20 earns its place by catching the one thing recall@20 is structurally blind to: a model can buy recall@20 by filling the top slots with items the visitor has already seen, and session-kNN does exactly that with a 94% top-1 repeat rate while scoring well. NDCG@20 with a single relevant item is a monotone function of the rank and therefore carries no information MRR does not, which is worth knowing because it means a paper reporting both is reporting one.

Q: What breaks first in production? A: The event stream, and it breaks silently because the model’s only input is the stream. The worst case was a front-end release that made a product-page refresh emit a duplicate view event, which took the model’s top-1 repeat rate from 0.21 to 0.38 within a day: the model was correctly learning that the next item genuinely was the current one 38% of the time, pooled recall@20 went UP by 0.011, and the rail became visibly useless to anybody who looked at it. The second thing that breaks is the retrain’s input window, which silently shrank from 90 days to 11 after a partition-pruning change and cost 0.0338 on one-click recall and 0.21 of catalogue coverage while pooled recall@20 moved 0.004. Both are why the monitored signal is the triple of one-click recall, top-1 repeat rate and same-category rail share over a frozen cohort rather than the pooled metric: a session model’s pooled number is dominated by the long sessions it is already best at.

Q: How do you handle a visitor who does have history? Is the session model just worse for them? A: On its own, yes, and the measurement is the reason both models still run. For the 31.7% of events where a user factor exists, the ALS model’s rail gets a 4.6% click-through rate and the session model gets 4.1%, so the session model loses on exactly the population it has no parameters for. The production arrangement is the count-gated blend from post 23 with the user’s interaction count as the gate: below 8 lifetime interactions serve the session model, above it blend the two scores after rank-normalising them, because their raw scales are not comparable and post 23’s effective-weight diagnostic exists for precisely that reason. The blend beat either model alone by 0.0094 recall@20 pooled. The proper answer is a hierarchical model that carries a user state across sessions, which is Quadrana and colleagues’ 2017 hierarchical RNN, and it is a different data contract because it requires a stable user id at request time, which is the thing 68.3% of this traffic does not have.

Interview Questions

Q: You have a matrix-factorisation recommender and two thirds of your traffic is logged out. Walk me through what you would build and why it is not just a cold-start patch on the existing model. Expected depth: Start by naming the objective change rather than the architecture. Matrix factorisation reconstructs a user-item matrix with per-user and per-item parameters, so a visitor with no row has no parameters and no amount of patching changes that; next-item prediction is a classification over the catalogue conditioned on an ordered prefix, with per-item parameters plus a shared recurrent transition and no user parameters at all, so it generalises to an unseen visitor by construction and cannot personalise to a known one. Say what that costs: measured on a real surface, the session model loses to the factorisation on the population that has history, 4.1% against 4.6% click-through, so the production answer is both models with a count gate on the user’s interaction history and rank-normalised scores. Then name the three things that decide whether the session model works, none of which are the network: where the session boundary comes from, what happens to the large share of sessions with one event, and what the negatives in the sampled softmax are drawn from. A strong answer notes that the session model is stateful at request time and the factorisation is not, and that this is a bigger operational change than the modelling one.

Q: A colleague reports that their GRU4Rec beats a first-order Markov baseline by 0.036 recall@20 and concludes that sequence modelling is worth 0.036. What is wrong? Expected depth: The comparison changes two things at once. A first-order Markov chain conditions on the last item and the GRU conditions on the whole prefix, so the gap confounds the amount of CONTEXT with the ordering of it, and context is almost certainly the larger term. Describe the clean experiment: add a baseline that sees the whole prefix as an unordered set, which is session-kNN with a binary item vector per training session, cosine neighbours and a weighted vote, and compare the GRU against that at matched context. In a measured case that put the value of order at 0.0074 recall@20 rather than 0.0356, and the remaining 0.0282 was context rather than ordering. Say why the decomposition is worth more than the total: a 0.0074 order effect bounds what any refinement of the sequence representation can be worth, which killed a six-week feature project, and the time went to cold-start initialisation which was worth 0.0081. Strong answers add that Ludewig and Jannach 2018 found nearest-neighbour session baselines competitive with GRU4Rec on four public datasets, that this is the reason the set-based baseline is mandatory rather than optional, and that a recall@k win should also be checked against the model’s top-1 repeat rate before it is believed.

Q: Explain the sampled softmax in GRU4Rec. What exactly is approximated, what is the bias, and what would you check? Expected depth: Be precise about the object: the output layer is a softmax over the whole catalogue, the normalising constant is a sum over 182,000 exponentiated scores, and it is replaced by a sum over the true target plus N sampled negatives. Give the arithmetic, 256 by 182,000 against 256 by 2,049, an 88.8 times reduction, and say that this is a training-time approximation only, because serving computes the full set or an ANN approximation of it. Then name the three decisions. The distribution: uniform negatives are mostly tail items the model already ranks low so the gradient is uninformative, popularity-proportional at exponent 0.75 draws the items it actually confuses, and in-batch negatives are free but make the effective distribution a function of the batch size, so tuning the batch size for throughput changes the objective. The count: it has a knee and flattens, and the cost is linear. And the collision: a popularity sampler draws the true target into its own negative set at a measurable rate, and an item asked to rank below itself is not a useful gradient, although the measured cost of omitting the guard is much smaller than the rate because a collided pair contributes a logit difference of exactly zero and dilutes rather than reverses the update. Strong answers add that the sampled loss is not comparable across configurations that sample differently, so early stopping and model selection must use a ranking metric.

Q: Where does a 30-minute session boundary come from, and how would you decide whether it is right? Expected depth: Say plainly that it is a convention from 1990s web analytics, inherited by Google Analytics, and that the public session-recommendation datasets were all cut with it, so it is not an estimate of anything and every published number is conditional on it. Then describe the two error directions and their asymmetric costs. Over-splitting cuts inside real sessions, which destroys the prefix the model conditions on and inflates the share of one-event sessions, and those sessions carry no next-item target so the destroyed data is invisible to the metric. Under-splitting glues two intents into one sequence, so the model is trained to predict an item from the second intent given a prefix from the first, which is label noise. Give the trap: downstream recall improves monotonically as the gap shortens, because a shorter prefix means the held-out next item is the adjacent click, so tuning the constant on recall drives it to the shortest value swept, and in a measured case a 10-minute gap raised offline recall@20 by 0.0186 and cost 2.8% of the online add-to-cart rate. The right procedure is to score boundaries directly against some ground truth once, a few thousand hand-labelled visits or a client-side session id the front end already emits, note that boundary F1 peaked at 15 minutes and recall peaked at 5, then freeze the constant as a data contract and print it above every metric table.

Q: Your session model gains 3 points of offline recall@20 and loses 1.2% of revenue per session. Diagnose it. Expected depth: Start by refusing to treat it as a measurement error, because the two metrics are measuring different things and the divergence has a direction. Next-item accuracy rewards predicting the click that was going to happen, and a rail slot that shows the near-substitute the visitor was already about to click earns a click, satisfies the offline metric, and displaces a slot that could have shown something new, so it cannibalises rather than adds. Name the diagnostics in order: the share of rail slots holding an item from the same category as the anchor, which went from 61% to 87% in a measured case; mean basket size, 2.31 items to 2.27; and the top-1 repeat rate against the data’s own repeat rate. Then say what follows. The guardrail is a cap on the same-category share, and the real fix is an objective change, because next-item prediction is a proxy whose offline movement does not predict the online one on this surface, so the candidates are a complementary-item target trained on co-purchase rather than co-view, an uplift or incrementality objective, or a direct online-learning loop. A strong answer closes on sequencing: having measured that a 0.031 offline gain can be worth minus 1.2% online, a 0.019 offline gain from a better architecture is not a reason to do anything until the objective predicts something, which makes the objective the roadmap item and the architecture downstream of it.

View full code for this problem