Designing Query, Key, and Value Vectors for Recommender Cross-Attention
Machine LearningModel answerLast updated
Explain and contrast Query-Key-Value representations for cross-attention mechanisms in candidate-aware recommendation systems.
When building deep-learning recommenders (such as CTR models or video ranking systems), Transformer-style cross-attention is widely used to capture fine-grained interactions between user history, target items, and context.
Consider a model with the following available representations:
- User Engagement History: An ordered list of $L$ historical items the user consumed, represented as embedding vectors of dimension $d$.
- Candidate Item: A target item being scored for the user, embedded as a vector of dimension $d$.
- Context: Additional features (e.g., time of day, location, current network condition) embedded into a vector of dimension $d$.
In this setup:
- Provide a primary formulation defining the Query ($Q$), Key ($K$), and Value ($V$) matrices for a cross-attention layer. Detail the semantic meaning and tensor shape for each.
- Formulate two distinct alternative architectures for setting up $Q$, $K$, and $V$. For every approach (including the primary one), explain:
- What inputs map to $Q$, $K$, and $V$.
- The specific interaction being modeled.
- Trade-offs, computational complexity, and where in a recommendation pipeline (e.g., candidate generation vs. candidate ranking) it should be applied.
- Compare cross-attention over user history against running self-attention over user history. Explain why cross-attention is beneficial in production recommendation systems.
Hints
Hint 1
Think of attention as a soft dictionary lookup: Query is what you are searching for, Key is what you match against, and Value is what you retrieve.
Hint 2
Consider how candidate-dependent queries affect offline inference vs. online evaluation. Can a user embedding be cached if the Query depends on the target candidate?
Hint 3
Pay attention to tensor dimensions when setting history items or multi-field candidate features as Keys/Values—single-token Keys make softmax trivial.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Standard Attention Formulation
In standard multi-head cross-attention, given query inputs $X_q$, key inputs $X_k$, and value inputs $X_v$, projections are defined as:
$$Q = X_q W_Q, \quad K = X_k W_K, \quad V = X_v W_V$$
The attention score computation is:
$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{Q K^\top}{\sqrt{d_k}} + M\right)V$$
where $M$ is a padding mask containing $-\infty$ for padded sequence positions and $0$ elsewhere.
Part 1: Primary Target-Attention Design (Candidate Queries History)
In candidate ranking models (such as DIN or BST variants), the most common formulation is Target Cross-Attention, where the candidate item acts as the query over the user's historical actions.
Definition & Dimensions
Let $B$ be the batch size, $L$ the length of the user history sequence, and $d$ the hidden dimension.
- Query ($Q$): Projected candidate item embedding (optionally concatenated with context features).
- Shape: $[B, 1, d]$
- Semantics: "Given this target candidate, which past actions in the user's profile are relevant?"
- Key ($K$): Projected sequence of user history item embeddings (augmented with sequence position, action type, or time-delta embeddings).
- Shape: $[B, L, d]$
- Semantics: The search index or match criteria of historical actions.
- Value ($V$): Projected sequence of user history items (augmented with engagement signals like watch ratio, implicit feedback, or reaction intensity).
- Shape: $[B, L, d]$
- Semantics: The information content extracted once a historical action is matched.
The resulting output shape is $[B, 1, d]$ (or $[B, d]$ after squeezing), representing a candidate-conditioned dynamic user representation.
Query (Candidate) [B, 1, d] ──┐
├──> Scaled Dot-Product Attention ──> User Context Vector [B, 1, d]
Keys (User History) [B, L, d] ──┤
Values (User History) [B, L, d] ──┘
Separating $K$ and $V$ projections is important: $K$ captures features that determine relevance (e.g., category or creator match), while $V$ encodes magnitude or feedback (e.g., completion rate or like status).
Part 2: Alternative Design Architectures
Architecture 1: Candidate as Query, History as Key/Value (Target Attention)
- Setup: $Q = \text{Candidate } [B, 1, d]$, $K, V = \text{History } [B, L, d]$.
- Interaction Modeled: Evaluates how much each historical item contributes to the interest score for a specific candidate.
- Complexity: $O(B \cdot L \cdot d)$ floating-point operations per candidate item.
- Pros & Cons:
- Pros: High expressiveness; prevents unimodal compression (avoids averaging out niche interests); highly interpretable via attention weights.
- Cons: The dynamic user representation depends on the target candidate, preventing pre-computation or caching of user vectors.
- Use Case: Fine Ranking Stage (scoring tens to hundreds of items).
Architecture 2: Multi-Field Candidate as Key/Value, History Items as Query
- Setup:
- $Q = \text{History Items } [B, L, d]$
- $K, V = \text{Candidate Features } [B, F, d]$ where $F > 1$ represents multiple candidate attribute fields (e.g., Item ID, Brand, Category, Tags).
- Interaction Modeled: For every past action, calculates which specific attribute field of the candidate matches it.
- Complexity: $O(B \cdot L \cdot F \cdot d)$ ops, followed by a sequence pooling step over $L$.
- Pros & Cons:
- Pros: Models fine-grained item-field interactions rather than treating the candidate as a single pooled vector.
- Cons: Requires $F > 1$. If $F = 1$, $\text{softmax}(QK^\top / \sqrt{d})$ over dimension $1$ yields $1.0$ everywhere, reducing attention to broadcasting $V$.
- Use Case: Recommender systems with structured multi-attribute items (e.g., e-commerce products with brand, seller, category, and price tiers).
Architecture 3: Contextual / Learned Queries over History (Candidate-Independent)
- Setup:
- $Q = \text{Context Embedding or } k \text{ Learned Latent Interest Queries } [B, k, d]$
- $K, V = \text{History } [B, L, d]$
- Interaction Modeled: Extracts $k$ general interest clusters or context-driven intent vectors (e.g., "weekend morning activities") independent of any specific target candidate.
- Complexity: $O(B \cdot k \cdot L \cdot d)$.
- Pros & Cons:
- Pros: Candidate-independent. The resulting vector(s) can be computed once per user request and cached or used in approximate nearest neighbor (ANN) retrieval.
- Cons: Lower ranking precision compared to direct candidate cross-attention.
- Use Case: Candidate Generation / Retrieval Stage (e.g., Two-Tower or Multi-Interest models like MIND/ComiRec).
Part 3: Cross-Attention vs. Self-Attention in Recommendation
| Dimension | History Self-Attention (e.g., SASRec) | Target Cross-Attention (e.g., DIN) |
|---|---|---|
| Input Sources | $Q, K, V$ all derived from History $[B, L, d]$ | $Q$ from Candidate $[B, 1, d]$; $K, V$ from History $[B, L, d]$ |
| Target Function | Item-to-item transition dynamics & sequential patterns | Direct affinity between candidate and historical actions |
| Candidate Dependence | Candidate-independent (computes once per sequence) | Candidate-dependent (recomputes per candidate) |
| Time Complexity | $O(L^2 \cdot d)$ | $O(L \cdot d)$ per candidate |
Why Cross-Attention is Essential in Recommenders
- Multi-Faceted User Interest: Users exhibit diverse behaviors (e.g., sports, technology, cooking). Direct mean-pooling or fixed-size sequence encoders blur these distinct signals. Cross-attention dynamically retrieves history relevant to the current candidate.
- Explicit Interaction Modeling: Performs explicit similarity matching early in the network architecture, rather than forcing late-stage MLP layers to infer relationship patterns from concatenated embeddings.
- Robustness to History Noise: Long behavioral logs often contain accidental clicks or transient interests. Candidate cross-attention assigns low attention weights to irrelevant historical items, suppressing noise.
In production systems, self-attention and cross-attention are frequently combined: self-attention first contextualizes the history sequence (encoding sequential transitions), and cross-attention subsequently matches the candidate against those contextualized representations.
Code Implementation (Target Cross-Attention Module)
import torch
import torch.nn as nn
import torch.nn.functional as F
class CandidateTargetAttention(nn.Module):
"""
Candidate-conditioned Target Cross-Attention for Recommendation Systems.
Queries: Candidate embeddings [B, 1, d]
Keys/Values: User history embeddings [B, L, d]
"""
def __init__(self, d_model: int, n_heads: int = 4, dropout: float = 0.1):
super().__init__()
self.mha = nn.MultiheadAttention(
embed_dim=d_model,
num_heads=n_heads,
dropout=dropout,
batch_first=True
)
self.layer_norm = nn.LayerNorm(d_model)
def forward(
self,
candidate: torch.Tensor, # [B, d]
history: torch.Tensor, # [B, L, d]
history_mask: torch.Tensor # [B, L], True for valid items, False for padding
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Returns:
user_interest_rep: [B, d] candidate-aware user representation
attn_weights: [B, 1, L] attention weights over history
"""
# Expand candidate to sequence length 1: [B, 1, d]
q = candidate.unsqueeze(1)
# PyTorch key_padding_mask requires True for padded (masked-out) positions
padding_mask = ~history_mask if history_mask.dtype == torch.bool else history_mask
# Cross-Attention step
attn_out, attn_weights = self.mha(
query=q,
key=history,
value=history,
key_padding_mask=padding_mask
)
# Residual connection and layer normalization
output = self.layer_norm(q + attn_out).squeeze(1) # [B, d]
return output, attn_weights