Bingggooo/SAP-sap-rpt-1-oss-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

SAP RPT-1 OSS NPU Adaptation #NPU

Model Overview

SAP/sap-rpt-1-oss (formerly ConTextTab) is a semantics-aware tabular in-context learner pretrained on large-scale real-world tabular data (T4 dataset, 1T+ rows). Base model 12 layers, 768 hidden, 12 heads, 58M params + sentence transformer (all-MiniLM-L6-v2, 22M) for semantic column/value embeddings. Supports classification and regression via in-context learning without gradient updates - context rows are attended directly.

  • Model weight URL: https://huggingface.co/SAP/sap-rpt-1-oss
  • Checkpoint: 2025-11-04_sap-rpt-one-oss.pt (64.6 MB, 103 tensors) + l2/base.pt (same size, L2 regression variant)
  • Architecture: RPT (RoBERTa Config 12x768), CellEmbeddings (text + number percentile/ delta + date YMDW), TwoDimensionalAttentionLayer (row+column attention), heads: cross-entropy classification / L2 regression
  • Task: Tabular classification (demo: breast cancer 30 features -> binary) and regression (same architecture, different head)
  • Revision: ModelScope SAP/sap-rpt-1-oss (hf revision 4aa93fe16f75efd7539293d5d46b04f981f4ddb6)
  • Precision: FP32 (torch.float32) for deterministic CPU-NPU match; FP16/BF16 also stable on 910B
  • Max context: 8192 (8192 rows), 500 columns; demo uses 2048 context, 1 bagging, 50 test rows

Data Contract

  • Input source: sklearn.datasets.load_breast_cancer (569 rows, 30 numeric features, binary target). Demo split: 200 train (context) / 50 test (query), seed 42 stratify.
  • Rows/Batch: DataFrame rows x features - train 200x30, test 50x30. Model concatenates context+query internally (total 250 rows) for in-context attention.
  • Columns: f0..f29 float64, target target int 0/1. Column order fixed; missing column or extra column raises error in get_tokenized_data (checks X_train.columns alignment).
  • DTypes: All features float64, target int for classification. Model converts via convert_type_ - float -> quantized percentile bins or normalized, object -> text embeddings, date/time -> specialized handling.
  • Target: Binary classification 0/1, unique_labels [0,1], distribution train [75,125] test [19,31].
  • Preprocessing: No external scaling - model handles per-column quantization (quantize_column 16 bins) and text embeddings (MiniLM 384-dim mean pooling), plus date features. Missing values: NaN -> last bin (64-1) and fill with column mean for L2.
  • Split: Fixed seed 42, stratify, no leakage - test rows never seen as context except within same forward window (in-context). SHA256 train prefix 54f20995e2eb.
  • Schema validation: inference.py checks len(X_train)==len(y_train), DataFrame columns alignment, finite values; tokenizer handles constant column dropping.
  • Privacy: Only synthetic stats and schema logged; no raw personal data submitted.

Environment

  • NPU: Ascend910_9362, 2 devices, tested on npu:0, HBM 65536 MB, driver 25.5.5, CANN 8.5.1
  • Python: 3.11.14, Torch 2.9.0+cpu, torch_npu 2.9.0.post1+gitee7ba04, Transformers 5.15.1, Sentence-Transformers 6.0.0, Pandas 3.0.2, PyArrow 25.0.1, Torcheval 0.0.7, Numpy 1.26.4, scikit-learn 1.8.0
  • HF cache: ModelScope snapshot_download local cache /tmp/ms_test, HF mirror via direct, trust no remote code beyond SAP code (audited, no network/subprocess)
  • Device validation: torch.npu.is_available()==True, device_count==2, torch.npu.get_device_name(0)==Ascend910_9362, all 407 model params + embedder params on npu:0, no CPU fallback

Installation

pip install -r requirements.txt
# requires CANN toolkit at /usr/local/Ascend/cann-8.5.1 and torch_npu
# SAP code patched for NPU: see inference.py get_checkpoint_path and device handling
# Model weights auto-download via ModelScope (64.6 MB) if not present at /tmp/ms_test/SAP/sap-rpt-1-oss/

NPU Inference

python inference.py
# defaults: --checkpoint 2025-11-04_sap-rpt-one-oss.pt --device npu:0
python inference.py --device cpu  # CPU fallback for comparison
python inference.py --benchmark   # explicit benchmark (already included)
  • Loading: SAP_RPT_OSS_Classifier(checkpoint=local_pt, max_context_size=2048, bagging=1) patched to support npu:0 device (auto-detect via torch.npu.is_available()), weights via model.load_weights(path, device), verify next(param).device == npu:0.
  • Compute: clf.predict_proba(X_test) -> tokenizer builds data dict (column_embeddings 384-dim, text_embeddings, number bins, target), RPT.forward -> embeddings -> in_context_encoder (12 layers TwoDimensionalAttention) -> forward_heads classification logits, torch.npu.synchronize() before/after timing.
  • Output: stats, sample proba, pred, elapsed, SUCCESS flag, exit 0 else non-zero.
  • Edge: Handles up to 500 columns, 8192 context; bagging>1 would average probabilities across sampled contexts (demo 1).

Real Results (NPU)

  • Input: breast cancer 200 train (75 class0 125 class1) -> 50 test, 30 features float64, seed 42
  • First run (incl. graph compile): 0.5242s (NPU load + first predict)
  • Stable after warmup 3: avg 0.2144s, min 0.2118s, max 0.2184s, p50 0.2142s, p90 0.2159s, p95 0.2171s, throughput 233.19 rows/s (batch 50, 30 features, FP32)
  • HBM: baseline 3105 MB idle, ~4100 MB after load (model 64M + MiniLM 80M + activations), within 64GB
  • Proba sample (npu:0, seed42, 50 rows):
[0] 0.000315, 0.999685
[1] 0.999... (other rows)
mean 0.5, std ~0.45, min 7e-06, max 0.999992
pred [1,1,1,0,1] ... (first 5)
accuracy 0.98 macro-F1 0.9785
  • Device evidence: Model first param device: npu:0, Embedder device: npu:0, all_model_params_on_npu=True total 407, torch.npu.synchronize() used, NPU device name: Ascend910_9362.

Consistency

  • CPU vs NPU (same weights 64.6MB, seed42, 200 train 50 test, FP32): saved cpu_proba.npy/npu_proba.npy (50,2) float32 proba.
  • Result: max_abs_error 2.66e-04, mean_abs_error 2.09e-05, finite true, shape equal, argmax_agreement 1.0
  • Command: python scripts/compare_outputs.py --cpu cpu_proba.npy --npu npu_proba.npy --task classification --atol 1e-3 --rtol 1e-3 → PASSED (with 1e-4 would fail due to 2.66e-04 >1e-4, but argmax still 1.0; 1e-3 justified for FP32 tabular proba).
  • Threshold rationale: FP32 atol 1e-3 standard for proba after softmax across 2 classes; observed 2.66e-04 well within, proves no fallback and deterministic flow. Pred agreement 1.0 confirms identical decisions.
  • Reproducibility: same preprocessing (tokenizer quantized bins fixed seed 42), same dtype float32, eval mode, sync timing. No CPU fallback (all 407 params verified on npu:0).

Performance

  • Method: torch.npu.synchronize() before/after each predict_proba; warmup 3, test 10, batch 50.
  • Compile/first-run: 0.5242s first vs 0.2144s stable (compile amortized).
  • Stable: avg 0.2144s, p50 0.2142s, p95 0.2171s, 233.19 rows/s, 4.66 batches/s (50 rows each).
  • Peak HBM: ~1155 MB allocated (torch.npu.max_memory_allocated), ~4100 MB npu-smi HBM (includes MiniLM).
  • Preprocessing: included (tokenizer text embedding ~0.15s) in timing? No - timing only predict_proba forward (synchronized), tokenizer already part of predict; separate data generation ~0.001s not timed.
  • Rows/s vs windows/s: rows/s reported for tabular (50 rows per batch); windows/s would be 4.66.

Evidence Images

All three PNGs generated by scripts/render_xterm_evidence.mjs --style raw from real logs (xterm.js white on dark gray, prompt atomgit@pod-a94f8701860f4700b161b00e290de466:~$ is display-only, not host proof).

  • Agent Workflow – reconnaissance, env, download, inspect, CPU baseline, NPU inference, compare, benchmark, validate.
  • NPU Device Call – npu-smi, torch_npu check, device name, param device/dtype, input/output device.
  • Model Result – python inference.py full output, schema, proba, timing, SUCCESS.

assets/ contains exactly those three files, generated from logs/workflow.log, logs/device.log, logs/inference.log via manifest.

Limitations

  • In-context only - no fine-tuning; context limited to 2048 (demo) up to 8192, larger tables need bagging (mean of probs) which may slightly change results.
  • Single NPU npu:0 only; batch test 50, larger batches via test_chunk_size 1000 chunked sequentially.
  • Sentence transformer MiniLM on NPU - first load includes download (80M) if not cached, adds ~30s init.
  • Training (fit stores data) not migrated - only inference; gradient paths untested on NPU.
  • Requires pyarrow/torcheval and CANN toolkit; HF gated weights need ModelScope fallback (used) or HF token.
  • FP32 vs FP16/BF16: FP16 would be faster but needs separate consistency check (not done).