LLM增强序列推荐(LLMESR)模型代码详解
论文讲解见 LLM-ESR Large Language Models Enhancement for Long-tailed Sequential Recommendation

三个模型(LLMESR_SASRec、LLMESR_GRU4Rec和LLMESR_Bert4Rec)的具体代码实现细节。
首先,理解整体的继承关系:
- LLMESR_SASRec继承自DualLLMSASRec,而DualLLMSASRec继承自SASRec_seq,SASRec_seq继承自SASRec
- LLMESR_GRU4Rec继承自DualLLMGRU4Rec,而DualLLMGRU4Rec继承自GRU4Rec
- LLMESR_Bert4Rec继承自DualLLMBert4Rec,而DualLLMBert4Rec继承自Bert4Rec
这三个模型都是在序列推荐模型的基础上增加了大语言模型(LLM)的知识。
从DualLLM系列模型开始分析,因为这是三个LLMESR模型直接继承的类。从DualLLMGRU4Rec的代码可以看到:
- 加载预训练的LLM物品嵌入
- 使用adapter将LLM嵌入维度调整到模型的隐藏维度
- 可能包含cross-attention机制
下面分析具体实现差异:
1. 基础序列编码机制
- GRU4Rec: 使用GRU(门控循环单元)处理序列数据
- SASRec: 使用单向自注意力机制处理序列
- Bert4Rec: 使用双向Transformer架构处理序列
2. 输入处理方式
- GRU4Rec: 直接处理序列输入
- SASRec: 需要位置编码
- Bert4Rec: 使用位置编码和mask机制
3. DualLLM的公共设计
- 所有DualLLM模型都加载预训练的LLM物品嵌入
- 通过adapter网络调整LLM嵌入维度
- 支持跨模态注意力(cross-attention)
4. LLMESR系列的增强
-
增加了对比学习/知识蒸馏机制
-
增加物品表示正则化选项
以下从三个方面详细对比分析三种模型的实现:基础架构、大语言模型集成方式和特征对齐机制。
一、基础序列建模实现
1. LLMESR_GRU4Rec - 基于GRU的序列建模
class GRU4RecBackbone(nn.Module):
def __init__(self, device, args):
super().__init__()
# GRU核心组件
self.gru = nn.GRU(
input_size=args.hidden_size,
hidden_size=args.hidden_size,
num_layers=args.gru_layer_num, # 多层GRU
batch_first=True
)
def forward(self, seqs, log_seqs):
# GRU处理序列数据,不需要位置编码
output, hidden = self.gru(seqs) # output: [batch_size, seq_len, hidden]
return output
GRU4Rec通过循环网络处理序列,记忆门控机制能够捕捉长期依赖,实现相对简单。
2. LLMESR_SASRec - 基于自注意力的序列建模
class SASRecBackbone(nn.Module):
def __init__(self, device, args):
super().__init__()
# 自注意力核心组件
self.attention_layernorms = nn.ModuleList()
self.attention_layers = nn.ModuleList()
self.forward_layernorms = nn.ModuleList()
self.forward_layers = nn.ModuleList()
for _ in range(args.block_num):
self.attention_layernorms.append(nn.LayerNorm(args.hidden_size))
self.attention_layers.append(
nn.MultiheadAttention(
args.hidden_size,
args.num_heads,
args.dropout_rate
)

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



