liuhongwei-2026/sap-rpt-1-oss
模型介绍
文件和版本
Pull Requests
讨论
分析

sap-rpt-1-oss

{hardware NPU}

SAP Relational Pre-trained Transformer (sap-rpt-1-oss) — 昇腾 NPU 适配版

原模型:https://huggingface.co/SAP/sap-rpt-1-oss
论文:ConTextTab: A Semantics-Aware Tabular In-Context Learner (NeurIPS 2025)

模型简介

sap-rpt-1-oss(原 ConTextTab)是一个**语义感知的表格数据上下文学习(Tabular In-Context Learning)**模型。它结合了表格原生架构的高效性和 LLM 语义编码的丰富理解能力,在分类和回归任务上达到 SOTA 水平。

架构特点:

  • RPT(Relational Pre-trained Transformer):12 层 × 768 隐藏维度(base 版本),基于 RoBERTa 架构
  • 二维注意力:分别在行方向和列方向应用 Transformer 注意力层
  • 语义嵌入:使用 sentence-transformers/all-MiniLM-L6-v2 对列名和单元格文本进行语义编码
  • 多模态输入:支持数值、文本、日期、时间等多种数据类型
  • L2 回归:直接预测目标值(L2 loss),无需分箱操作

适配说明

项目内容
硬件后端昇腾 Ascend910 (NPU)
推理框架PyTorch 2.9.0 + torch_npu
精度全 fp32 推理
显存需求约 2.5 GB(含 sentence-embedder 模型)
无需改造纯 PyTorch 代码,仅 device 检测适配(cuda → npu)

快速开始

环境安装

pip install torch torch_npu
pip install transformers>=4.38.0 torcheval>=0.0.7 scikit-learn>=1.3.0 pandas>=2.0.0
pip install sentence-transformers  # 用于语义嵌入

模型权重

权重已包含在仓库的 weights/ 目录下:

  • weights/2025-11-04_sap-rpt-one-oss.pt — 默认主模型 checkpoint(61.6 MB)
  • weights/base.pt — 可选的 L2 回归 checkpoint(61.6 MB)

分类推理

import sys
sys.path.insert(0, '.')
from sap_rpt_oss import SAP_RPT_OSS_Classifier

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)

clf = SAP_RPT_OSS_Classifier(
    checkpoint='weights/2025-11-04_sap-rpt-one-oss.pt',
    bagging=1, max_context_size=2048
)
clf.fit(X_train, y_train)
preds = clf.predict(X_test)
probs = clf.predict_proba(X_test)
print(f"Accuracy: {sum(preds == y_test) / len(y_test):.4f}")

回归推理

from sap_rpt_oss import SAP_RPT_OSS_Regressor

from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)

reg = SAP_RPT_OSS_Regressor(
    checkpoint='weights/2025-11-04_sap-rpt-one-oss.pt',
    bagging=1, max_context_size=2048
)
reg.fit(X_train, y_train)
preds = reg.predict(X_test)
print(f"R²: {__import__('sklearn').metrics.r2_score(y_test, preds):.4f}")

一键推理

# 分类任务
python inference.py --mode classification

# 回归任务
python inference.py --mode regression

# 全量运行
python inference.py --mode all

# 指定 checkpoint 路径
python inference.py --mode classification --checkpoint /path/to/checkpoint.pt

# 调整 bagging 和上下文大小
python inference.py --mode classification --bagging 8 --max_context_size 8192

推理效果

在 Ascend910 NPU 上的测试结果(bagging=1, max_context_size=2048):

任务数据集指标分数推理耗时
分类Breast Cancer (569 samples, 30 features)Accuracy0.97890.72s
回归Diabetes (442 samples, 10 features)R²0.49000.45s

使用更大 bagging 和上下文大小可获得更优性能,但会相应增加显存和延时。

项目结构

sap-rpt-1-oss/
├── inference.py              # 推理脚本(分类 + 回归)
├── README.md                 # 部署说明文档
├── requirements.txt          # 环境依赖清单
├── configuration.json        # 模型配置
├── weights/                  # 模型权重目录
│   ├── 2025-11-04_sap-rpt-one-oss.pt
│   ├── base.pt
│   └── base.pt.license
├── sap_rpt_oss/              # vendored 模型代码(NPU 适配版)
│   ├── __init__.py
│   ├── rpt.py                # 主入口 Estimator 类
│   ├── constants.py
│   ├── data/
│   │   ├── __init__.py
│   │   ├── tokenizer.py       # 数据分词与嵌入
│   │   └── sentence_embedder.py  # 语义嵌入(NPU 适配)
│   ├── model/
│   │   ├── __init__.py
│   │   ├── torch_model.py     # RPT 模型核心
│   │   ├── embeddings.py      # 多模态嵌入层
│   │   └── attention.py       # 二维注意力层
│   └── utils/
│       ├── __init__.py
│       └── lru_cache.py       # LRU 缓存加速
└── assets/
    ├── agent_workflow.png     # 推理流程截图
    ├── npu_device_call.png    # NPU 设备调用截图
    └── model_result.png       # 推理结果截图

NPU 适配说明

本仓库对原始 sap-rpt-1-oss 代码进行了以下适配:

  1. 设备检测:torch.cuda.is_available() → torch.npu.is_available(),优先使用昇腾 NPU
  2. device 类型处理:sentence_embedder.py 中兼容字符串类型的 device 参数
  3. 权重加载:支持本地路径和 huggingface_hub 两种方式
  4. 精度保持:全程 fp32 推理,与 CPU 精度一致

注意事项

  • 首次运行会自动下载 sentence-transformers/all-MiniLM-L6-v2 语义嵌入模型(约 90MB)
  • 如果无法访问 huggingface.co,请设置 HF_ENDPOINT=https://hf-mirror.com
  • 所有模型权重使用 torch.load(..., weights_only=True) 安全加载
  • 使用 bagging=1 时推理速度最快,增加 bagging 可提升预测稳定性

引用

@inproceedings{spinaci2025contexttab,
  title={ConTextTab: A Semantics-Aware Tabular In-Context Learner},
  author={Marco Spinaci and Marek Polewczyk and Maximilian Schambach and Sam Thelin},
  booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
  year={2025},
  url={https://openreview.net/forum?id=kGMRb4jbTP}
}

License

Apache 2.0