NextRec
A unified, efficient, and extensible PyTorch-based recommendation library
Install / Use
/learn @zerolovesea/NextRecREADME
中文文档 | English Version
统一、高效、可扩展的推荐系统框架
</div>目录
简介
NextRec是一个基于PyTorch的现代推荐系统框架,旨在为研究工程团队提供快速的建模、训练与评估流。框架内置丰富的模型库、数据处理工具和工程化训练组件。此外提供了易上手的接口,命令行工具及教程,推荐算法学习者能以最快速度了解模型架构,复现学术论文并进行训练和部署。
Why NextRec
- 多场景推荐能力:覆盖排序(CTR/CVR)、匹配、多任务学习、生成式召回等推荐/营销模型,持续跟进业界进展。
- 统一的特征工程与数据流水线:提供了统一的特征定义、可持久化的数据处理、批处理优化,符合工业大数据Spark/Hive场景下,基于离线特征的模型训练推理流程。
- 友好的工程体验:支持多种格式数据(
csv/parquet/pathlike)的流式处理/分布式训练/推理与可视化指标监控,方便业务算法工程师和推荐算法学习者快速复现实验。 - 灵活的命令行工具:支持通过命令行和配置文件,一键启动训练和推理进程,方便快速实验迭代和敏捷部署。
- 丰富的模型注解:提供了详细的模型背景介绍,实现流程,维度变化注释,方便学习者第一时间快速了解模型架构。
- 高效训练与评估:内置多种优化器、学习率调度、早停、模型检查点与详细的日志管理(Wandb/Swanlab/Tensorboard),开箱即用。
NextRec近期进展
- 03/02/2026 在v0.5.3中,我们引入了NextRec Studio前端项目,初期作为NextRec CLI的配套辅助工具使用,并提供了相关教程
- 28/01/2026 在v0.4.39中加入了对onnx导出和加载的支持,并大大加速了数据预处理速度(最高9x加速)
- 01/01/2026 新年好,在v0.4.27中加入了多个多目标模型的支持:APG, ESCM, HMoE, Cross Stitch
- 21/12/2025 在v0.4.16中加入了对GradNorm的支持,通过compile的
loss_weight='grad_norm'进行配置 - 12/12/2025 在v0.4.9中加入了RQ-VAE模块。配套的数据集和代码已经同步在仓库中
- 07/12/2025 发布了NextRec CLI命令行工具,它允许用户根据配置文件进行一键训练和推理,我们提供了相关的教程和教学代码
- 06/12/2025 在v0.4.1中支持了单机多卡的分布式DDP训练,并且提供了配套的代码
- 11/11/2025 NextRec v0.1.0发布,我们提供了10余种排序模型,11种多任务模型和4种召回模型,以及统一的训练/日志/指标管理系统
架构
NextRec采用模块化工程设计,核心组件包括:统一特征驱动的BaseModel架构;独立Layer模块;支持训练推理的统一的DataLoader;命令行工具NextCLI等。

安装
开发者可以通过pip install nextrec快速安装NextRec的最新版本,环境要求为Python 3.10+(对于需要使用CUDA加速的开发者,建议安装对应版本的pytorch)。如果需要执行示例代码,则需要先拉取仓库:
git clone https://github.com/zerolovesea/NextRec.git
cd NextRec/
pip install nextrec # or pip install -e .
实验跟踪组件
wandb和swanlab不作为默认依赖安装,因为部分 Linux 环境在安装wandb时可能会回退到源码构建,并因缺少go编译环境而失败。如果你只需要训练、评估、推理,执行
pip install nextrec即可。如果你需要导出 ONNX 或使用 ONNX Runtime 推理,请额外安装:
pip install "nextrec[onnx]"如果你需要启用 WandB 或 SwanLab,请额外安装:
pip install "nextrec[tracking]"
示例代码
我们在tutorials/ 目录提供了多个示例,覆盖排序、召回、多任务、数据处理等场景:
-
movielen_ranking_deepfm.py - movielen 100k数据集上的 DeepFM 模型训练示例
-
example_ranking_din.py - 电商数据集上的DIN 深度兴趣网络训练示例
-
example_multitask.py - 电商数据集上的ESMM多任务学习训练示例
-
movielen_retrieval_dssm.py - 基于movielen 100k数据集训练的 DSSM 召回模型示例
-
example_onnx.py - 使用NextRec训练和导出onnx模型
-
example_distributed_training.py - 使用NextRec进行单机多卡训练的代码示例
-
run_all_ranking_models.py - 快速校验所有排序模型的可用性
-
run_all_multitask_models.py - 快速校验所有多任务模型的可用性
-
run_all_retrieval_models.py - 快速校验所有召回模型的可用性
如果想了解更多NextRec框架的细节,我们还提供了Jupyter notebook来帮助你了解:
使用 ONNX 示例前,请先执行 pip install "nextrec[onnx]"。
5分钟快速上手
我们提供了详细的上手指南和配套数据集,帮助您熟悉NextRec框架的不同功能。我们在dataset/路径下提供了一个来自电商场景的测试数据集,数据示例如下:
| user_id | item_id | dense_0 | dense_1 | dense_2 | dense_3 | dense_4 | dense_5 | dense_6 | dense_7 | sparse_0 | sparse_1 | sparse_2 | sparse_3 | sparse_4 | sparse_5 | sparse_6 | sparse_7 | sparse_8 | sparse_9 | sequence_0 | sequence_1 | label | |--------|---------|-------------|-------------|-------------|------------|-------------|-------------|-------------|-------------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|-----------------------------------------------------------|-----------------------------------------------------------|-------| | 1 | 7817 | 0.14704075 | 0.31020382 | 0.77780896 | 0.944897 | 0.62315375 | 0.57124174 | 0.77009535 | 0.3211029 | 315 | 260 | 379 | 146 | 168 | 161 | 138 | 88 | 5 | 312 | [170,175,97,338,105,353,272,546,175,545,463,128,0,0,0] | [368,414,820,405,548,63,327,0,0,0,0,0,0,0,0] | 0 | | 1 | 3579 | 0.77811223 | 0.80359334 | 0.5185201 | 0.91091245 | 0.043562356 | 0.82142705 | 0.8803686 | 0.33748195 | 149 | 229 | 442 | 6 | 167 | 252 | 25 | 402 | 7 | 168 | [179,48,61,551,284,165,344,151,0,0,0,0,0,0,0] | [814,0,0,0,0,0,0,0,0,0,0,0,0,0,0] | 1 |
接下来我们将用一个简短的示例,展示如何使用NextRec训练一个DIN(Deep Interest Network)模型。您也可以直接执行python tutorials/example_ranking_din.py来执行训练推理代码。
开始训练以后,你可以在nextrec_logs/din_tutorial路径下查看详细的训练日志。
import pandas as pd
from nextrec.models.ranking.din import DIN
from nextrec.basic.features import DenseFeature, SparseFeature, SequenceFeature
df = pd.read_csv('dataset/ranking_task.csv')
# csv 默认将列表读取成文本,我们需要将其转化为对象
for col in df.columns:
if 'sequence' in col:
df[col] = df[col].apply(lambda x: eval(x) if isinstance(x, str) else x)
# 我们需要将不同特征进行定义
dense_features = [DenseFeature(name=f'dense_{i}', input_dim=1) for i in range(8)]
sparse_features = [SparseFeature(name='user_id', embedding_name='user_emb', vocab_size=int(df['user_id'].max() + 1), embedding_dim=32), SparseFeature(name='item_id', embedding_name='item_emb', vocab_size=int(df['item_id'].max() + 1), embedding_dim=32),]
sparse_features.extend([SparseFeature(name=f'sparse_{i}', embedding_name=f'sparse_{i}_emb', vocab_size=int(df[f'sparse_{i}'].max() + 1), embedding_dim=32) for i in range(10)])
sequence_features = [
SequenceFeature(name='sequence_0', vocab_size=int(df['sequence_0'].apply(lambda x: max(x)).max() + 1), embedding_dim=32, padding_idx=0, embedding_name='item_emb'),
SequenceFeature(name='sequence_1', vocab_size=int(df['sequence_1'].apply(lambda x: max(x)).max() + 1), embedding_dim=16, padding_idx=0, embedding_name='sequence_1_emb'),]
mlp_params = {
"hidden_dims": [256, 128, 64],
"activation": "relu",
"dropout": 0.3,
}
model = DIN(
dense_features=dense_features,
sparse_features=sparse_features,
sequence_features=sequence_features,
behavior_feature_name="sequence_0",
candidate_feature_name="item_id",
mlp_params=mlp_params,
attention_mlp_params={
"hidden_dims": [80, 40],
"activation": "sigmoid",
},
attention_use_softmax=True,
target=['label'], # 目标变量
device='cpu',
session_id="din_tutorial", # 实验id,用于存放训练日志
)
# 编译模型,优化器/损失/学习率调度器统一在 compile 中设置
model.compile(
optimizer="adam",
optimizer_params={"lr": 1e-3, "weight_decay": 1e-5},
loss="focal",
loss_params={"gamma": 2.0, "alpha": 0.25},
)
model.fit(
train_data=df,
metrics=['auc', 'gauc', 'logloss'], # 添加需要查看的指标
epochs=3,
batch_size=512,
shuffle=True,
user_id_column='user_id', # 用于计算GAUC的id列
valid_split=0.2, # 自动划分验证集(可选)
num_workers=4, # DataLoader 并行数
use_wandb=False, # 启用 Wandb(可选)
wandb_kwargs={"project": "NextRec", "name": "din_tutorial"},
use_swanlab=False, # 启用 SwanLab(可选)
swanlab_kwargs={"project": "NextRec", "name": "din_tutorial"},
)
# 训练完成后进行指标评估
metrics = model.evaluate(
df,
metrics=['auc', 'gauc', 'logloss'],
batch_size=512,
user_id_column='user_id'
)
如果要把训练日志同步到 WandB 或 SwanLab,请先执行 pip install "nextrec[tracking]"。
命令行工具
NextRec 提供了强大的命令行界面,支持通过 YAML 配置文件进行模型训练和预测。详细的 CLI 文档请参见:
- NextRec CLI 使用指南 - 完整的 CLI 使用文档
- NextRec CLI 配置文件示例 - CLI 使用配置文件示例
# 训练模型
nextrec --mode=train --train_config=path/to/train_config.yaml
# 运行预测
nextrec --mode=predict --predict_config=path/to/predict_config.yaml
预测结果固定保存到 {checkpoint_path}/predictions/{name}.{save_data_format}。
截止当前版本0.6.7,NextRec CLI支持单机训练,分布式训练相关功能尚在开发中。
兼容平台
当前最新版本为0.6.7,所有模型和测试代码均已在以下平台通过验证,如果开发者在使用中遇到兼容问题,请在issue区提出错误报告及系统版本:
| 平台 | 配置 | |------|------| | MacOS latest| MacBook Pro M4 Pro 24G内存 | | Ubuntu latest| AutoDL 4070D 双卡 | | Ubuntu 24.04| NVIDIA TITAN V 5卡 | | CentOS 7 | Intel Xeon 5138Y 96核 377G内存 |
支持模型
排序模型
| 模型 | 论文 | 状态 | | ------ | ------ | ------ | | FM | Factorization machines | 已支持 | | [LR](nextrec/models/ranking/lr.
Related Skills
YC-Killer
2.7kA library of enterprise-grade AI agents designed to democratize artificial intelligence and provide free, open-source alternatives to overvalued Y Combinator startups. If you are excited about democratizing AI access & AI agents, please star ⭐️ this repository and use the link in the readme to join our open source AI research team.
groundhog
398Groundhog's primary purpose is to teach people how Cursor and all these other coding agents work under the hood. If you understand how these coding assistants work from first principles, then you can drive these tools harder (or perhaps make your own!).
isf-agent
a repo for an agent that helps researchers apply for isf funding
last30days-skill
17.6kAI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
