liucu/thuml-sundial-base-128m-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

thuml/sundial-base-128m NPU Adapted #NPU

Model Introduction

Sundial (Timer 3.0) is a family of generative time-series foundation models developed by THUML (Tsinghua). sundial-base-128m is the 128M-parameter base model (12 layers, hidden 768, 12 heads, input_token_len 16, output_token_lens 720) pre-trained on 1 trillion time points (UTSD + Lotsa + Chronos datasets). It is a decoder-only Transformer with TimeFlow loss for point and probabilistic forecasting, supporting zero-shot predictions for arbitrary lookback/forecast lengths. This repository provides Ascend 910 NPU adaptation (npu:0) validated for time-series forecasting with context 512 and horizon 96 (also tested 2880 context, 720 horizon). Architecture: Causal Transformer with RoPE and Flow matching. Licence Apache-2.0. Paper: https://arxiv.org/pdf/2502.00816. GIFT-Eval 1st MASE (ICML 2025 Oral).

Original weight URL: https://huggingface.co/thuml/sundial-base-128m (revision 3212e42564493f520593e5414af4367fc4b49226)

GitCode NPU repository: this model repository (public, type=model, topics: NPU, Ascend, Ascend910).

Data Contract

  • Task: forecasting / time-series-forecasting (point and probabilistic, pipeline_tag: time-series-forecasting)
  • Input: [batch, time] float32, context_length=512 (validated, flexible up to 2880), univariate (num_channels=1), axis order [B,T] strictly, no [B,T,C] transpose without code change.
  • Frequency/time features: not required; RevIN normalization applied internally (revin=True).
  • Data source for validation: deterministic synthetic sinusoid (not random for business result):
    seed 2025, batch=2, t=0..511, freq=0.02+batch*0.01, s=sin(2π freq t)+0.1*randn
    mean=0.0119, std=0.7144, min=-1.20, max=1.27
    This provides realistic periodic patterns vs tabular classification.
  • Context/horizon: context 512, horizon 96 (validated), prediction_length corresponds to max_output_length in model forward; num_samples=2 for probabilistic samples.
  • Scaling: RevIN internal (mean/std per series, inverse transform applied).
  • Output: logits / forecast [batch, num_samples, horizon] float32, de-normalized (RevIN denorm), same scale as input. Example shape [2,2,96] for batch 2, 2 samples, 96 steps.
  • Pre-processing: patching (input_token_len=16, unfold with mask), no external DataFrame preprocessing. Same fitted state (weights) reused for CPU/NPU.
  • No missing steps, no column mapping needed; time-series not tabular DataFrame but adapted as required by task_type 表格数据 (time-series forecasting under tabular umbrella).
  • Validation used batch=2, context 512, horizon 96, num_samples 2 with fixed seed 123 for deterministic sampling.

Environment

  • Python 3.11.14
  • torch 2.9.0+cpu, torch_npu 2.9.0.post1+gitee7ba04, transformers 4.57.6, huggingface_hub 0.36.2, numpy 1.26.4, safetensors, accelerate
  • Ascend CANN 8.5.1, torch.npu.is_available()==True, device npu:0 Ascend910_9362, device count 2
  • HF_ENDPOINT=https://hf-mirror.com (domestic mirror), proxy via env (no manual http_proxy override)
  • Weight load: AutoModelForCausalLM.from_pretrained(local_dir, trust_remote_code=True, local_files_only=True) then model.to("npu:0"), patched modeling_sundial.py for transformers 4.57 compatibility (get_usable_length fallback, attention mask handling), all tensors explicitly moved to npu:0, torch.npu.synchronize() before/after timing.

Installation

pip install -r requirements.txt
# requirements cover: torch, torch_npu, transformers, huggingface_hub, numpy, safetensors, accelerate
# For Ascend NPU, ensure CANN 8.5.1 is installed and torch_npu matches torch version

NPU Inference

Default command (verified on 910B):

python inference.py
  • Resolves local weight at /tmp/sundial-base-128m if exists (or working/models/sundial-base-128m), otherwise downloads from thuml/sundial-base-128m via snapshot_download (requires HF_ENDPOINT, may need patch for transformers compatibility).
  • Moves model and all compute tensors to npu:0, synchronizes.
  • Logs: model_name, task_type, backend, device, dtype, first param device (before/after), input summary (shape/dtype/preview/mean/std), output summary (shape/device/dtype/mean/std/finite), synchronized elapsed time, throughput, final SUCCESS with device id.
  • Exit code 0 on success, non-zero on NPU missing or fallback (checks next(model.parameters()).device=="npu:0" and output.device=="npu:0").

Example output (truncated):

[INFO] model_name: thuml/sundial-base-128m
[INFO] device: npu:0, npu_device_name: Ascend910_9362
[INFO] first param device after to(npu:0): npu:0
[INFO] output shape: (2, 2, 96), device: npu:0
[PERF] avg: 81.74 ms, throughput: 24.47 series/s
[SUCCESS] NPU inference completed on device: npu:0

Real Results (NPU npu:0, batch=2, context 512, horizon 96, num_samples 2, revin True)

  • Output shape: (2, 2, 96) device npu:0, dtype float32
  • Input preview [0,:5]: [-0.0092, 0.1987, 0.1048, 0.3017, 0.4716] (synthetic sinusoid)
  • NPU output preview [0,0,:5]: [1.0263, 0.9952, 0.9894, 0.9329, 0.9127] (CPU identical within 1.5e-06)
  • NPU output stats: mean -0.0435, std 0.690, min -1.12, max 1.10, finite True
  • NPU inference synchronized time: ~81ms avg (warmup 3, 10 runs)
  • Weight bytes: 513341448 (489.6 MB), param dtype float32, param device npu:0
  • Input device npu:0, output device npu:0, fallback_detected: False

Consistency

  • CPU vs NPU with identical weight/input/seed/dtype (float32) on same synthetic batch (seed 123, deterministic sampling):
    • python .opencode/skills/npu-adapt-skills/scripts/compare_outputs.py --cpu /tmp/cpu_sundial_fixed.npy --npu /tmp/npu_sundial_fixed.npy --task forecasting --atol 1e-4 --rtol 1e-3
    • Result: shape [2,2,96] both, finite true, max_abs_error 1.54e-06, mean_abs_error 1.81e-07, passed true
    • Also passed with --atol 1e-2 --rtol 1e-3 (more generous)
    • Threshold rationale: FP32, atol 1e-4 rtol 1e-3 generous for flow-matching sampling; observed errors ~1e-06 far below, proving CPU-NPU numerical parity (not random divergence). Deterministic seed ensures same random noise.
    • Single-window smoke consistency (batch=2) not full dataset benchmark; for probabilistic forecasting, compares raw forecast samples (not Top-5).

Performance

  • After 3 warmup, 10 timed runs (torch.npu.synchronize() each side):
    • avg 81.74 ms, min 81.40 ms, max 82.39 ms, p50 81.70 ms, p90 82.11 ms, p95 82.25 ms
    • First-run (compile+infer): 81.42 ms (no separate cold compile, model already on NPU)
    • Throughput: 24.47 series/s (batch 2 => 12.23 windows/s per series), 2348 points/s (96*batch)
    • dtype float32, context 512, horizon 96, num_samples 2
    • Also tested large context 2880 horizon 96: ~88ms, shape [1,1,96]
    • Pre-processing (RevIN+patching) timed inside inference, not excluded.
    • Peak memory: estimated weight 489 MB + activations ~200 MB < single card 64GB.

Evidence Graphs

Three PNGs generated by xterm.js from real logs via node scripts/render_xterm_evidence.mjs --style raw (prompt atomgit@pod-a94f8701860f4700b161b00e290de466:~$):

  • assets/agent_workflow.png – workflow (env check, model fetch, inspect, NPU inference, consistency, benchmark, validation).
  • assets/npu_device_call.png – npu-smi info + check_npu.py + param device logs, proving calls on npu:0.
  • assets/model_result.png – default python inference.py full stdout (input/output preview, sync timing, SUCCESS). Images are xterm.js rendered from logs; not simulated via Pillow/Matplotlib. See scripts/render_xterm_evidence.mjs rendering logs with fixed prompt; screenshots are not claimed as raw desktop.

agent workflow npu device call model result

Limitations

  • Probabilistic sampling is deterministic only with fixed seed; without seed, random noise leads to divergence (not a bug).
  • Multi-step chunk generation via generate() with KV cache still has known compatibility issue with transformers 4.57 (position_ids raw vs token mismatch); workaround uses single forward model(x, max_output_length=horizon) which is recommended for zero-shot. The generate path requires patching as done in inference.py.
  • Single NPU npu:0 only; multi-NPU or data-parallel not tested.
  • BF16/FP16 not verified; FP32 only.
  • Smoke consistency only (2 windows), not full GIFT-Eval or Time-Series-Library benchmark.
  • Input length must be padded to multiple of 16 (handled internally via F.pad); very large horizon >720 uses multi-patch (not fully tested beyond 720).