liucu/Maple728-TimeMoE-200M-NPU
模型介绍
文件和版本
Pull Requests
讨论
分析

Maple728/TimeMoE-200M NPU Adapted #NPU

Model Introduction

TimeMoE-200M is a 200M-parameter Mixture-of-Experts (MoE) time-series foundation model from the paper Time-MoE: Billion-Scale Time Series Foundation Models with Mixture of Experts. Architecture: TimeMoeForPrediction, hidden_size 768, 12 layers, 12 attention heads, 8 experts (top-k 2) + shared expert, intermediate 3072, RoPE theta 10000, max positions 4096, input_size 1 univariate, horizon_lengths [1, 8, 32, 64], activation silu, RMSNorm eps 1e-6. Weight model.safetensors 906,450,104 bytes (864.5 MB), dtype bfloat16 in checkpoint, executed in float32 for high CPU-NPU consistency. Licence apache-2.0. Pipeline tag time-series-forecasting. Paper: https://arxiv.org/abs/2409.16040, code: https://github.com/time-moe/time-moe .

Original weight URL: https://huggingface.co/Maple728/TimeMoE-200M

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

Data Contract

  • Task: forecasting (point prediction, univariate).
  • Dataset: working/input.csv (provided, 2500 rows, sha256 aa5efe0121b7cc098db1a169ed38f9878681ef14a93c85d54a618fd073048899), columns timestamps, open, high, low, close, volume, amount. Time column timestamps (ISO, sorted, no invalid/duplicate).
  • Target column for TimeMoE (input_size 1): close (float64, no missing). Other OHLCV columns available but model is univariate; validation uses close only.
  • Context / Horizon: context_length 512 (first 512 rows, 2024-06-18 11:15 -> 2024-07-03 09:50), prediction_length 8 (corresponding to horizon 8 head). Axis order strictly [batch, seq_len] (input_size 1, no channel permute); for API shape [1, 512] or [1, 512, 1] equivalent, validated both.
  • Frequency: 5-minute K-line (irregular overnight gap ignored; treated as equally spaced indices).
  • Scaling: per-series z-score (x - mean)/std on context window; mean 10.936504, std 0.166452, min 10.67 max 11.35 for the validated window. Forecast denormalized pred * std + mean. Scaling parameters saved with output (mean/std in logs).
  • Missing handling: none (0 missing); if missing, would nan_to_num before norm.
  • Preprocessing contract: same mean/std, dtype float32, no data leakage (context only). CPU and NPU share same normalized input.
  • Label availability: input.csv contains only historical prices, no future labels in file; forecast is free-running. Evaluation is consistency (CPU vs NPU), not full backtest MAE on held-out labels.
  • Output: forecast tensor [8] float32 denormalized (close price), also full logits [1, 512, 8] normalized (last token's 8 values are used as forecast).
  • Validation rows: context 512 from 2500 (first window deterministic).

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, pandas 3.0.2, safetensors
  • 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)
  • Model load: AutoModelForCausalLM.from_pretrained(local_dir, trust_remote_code=True, dtype=torch.float32) then model.to("npu:0"), all compute tensors explicitly to("npu:0"), torch.npu.synchronize() before/after timing, use_cache=False to avoid DynamicCache API mismatch in transformers 4.57 (original code expects 4.40; use_cache=False gives identical accuracy with float32 error <2e-6).
  • Weight load from local /tmp/TimeMoE-200M (snapshot_download to that dir), fallback via huggingface_hub.snapshot_download if not present.

Installation

pip install -r requirements.txt
# requires: torch, torch_npu, transformers, huggingface_hub, numpy, pandas, safetensors

NPU Inference

Default command (verified on 910B):

python inference.py
  • Resolves local weight at /tmp/TimeMoE-200M (864 MB) else downloads via HF mirror.
  • Moves model and input to npu:0, reports model param device, input NPU device, output device.
  • Logs: model_name, task_type, backend, device, dtype, first param device/dtype, input summary (shape/dtype/preview/mean/std/timestamps), output summary (logits shape/device/dtype, forecast normalized & denormalized, mean/std, sync timing), and final SUCCESS with device id.
  • Exit code 0 on success, non-zero on fallback or NaN.
  • Inference details: context 512 -> horizon 8 via single forward model(input_ids=x, max_horizon_length=8, use_cache=False); picks lm_head index for horizon 8; output [1,512,8], forecast logits[0,-1,:].

Real Results (NPU npu:0, batch 1, context 512, horizon 8, float32)

  • Output logits shape: (1, 512, 8) device npu:0 dtype float32
  • Input preview (close raw first 5): [11.27, 11.27, 11.27, 11.27, 11.26]
  • Input normalized preview first 5: [2.00355, 2.00355, 2.00355, 2.00355, 1.94348]
  • Forecast normalized (NPU, last token 8): [-0.06576433, -0.07700579, -0.08654091, -0.10044055, -0.1159027, -0.12847261, -0.13859349, -0.14296186]
  • Forecast denormalized (NPU, close price): [10.925558, 10.923687, 10.922099, 10.919786, 10.917212, 10.91512, 10.913435, 10.912708]
  • CPU forecast identical within 7.6e-07 (max_abs) for same input; denormalized mean 10.9187 std 0.0045 min 10.9127 max 10.9256.
  • Synchronized inference time (warmup 3 + 10 timed, torch.npu.synchronize each side): avg 0.0633s, min 0.0607s, max 0.0645s, p50 0.0636s, p90 0.0645s, p95 0.0645s.
  • Throughput: 15.79 windows/s (batch 1).
  • First-run compile already included in warmup; stable timing reported.
  • Weight bytes: 906450104 (864.5 MB), param dtype float32 after load, param device npu:0, output device npu:0, fallback_detected: False.
  • Log warning Cannot create tensor with interal format ... is harmless and appears on NPU MoE one_hot path; does not indicate fallback.

Consistency

  • CPU vs NPU with identical weight/input/seed/dtype (float32), same z-score norm, use_cache=False:
    • python .opencode/skills/npu-adapt-skills/scripts/compare_outputs.py --cpu /tmp/timemoe_cpu_forecast.npy --npu /tmp/timemoe_npu_forecast.npy --task forecasting --atol 1e-4 --rtol 1e-3 (forecast [8])
    • Result: shape [8] both, finite true, max_abs_error 7.599e-07, mean_abs_error 4.25e-07, passed true
    • Full logits [1,512,8] also: max_abs 1.459e-04, mean 2.77e-06, passed true with same atol/rtol
    • Threshold rationale: FP32, atol 1e-4 rtol 1e-3 generous; observed errors 1e-06 to 1e-04 far below. For bfloat16 same model gives larger error (max ~0.013 normalized, 0.002 denorm) due to 7-bit mantissa; float32 chosen for stricter validation. Reported forecast error denormalized max 7.6e-07 * std ~1.2e-07 price units negligible.
    • Single-window smoke consistency (context 512 -> horizon 8) not full dataset benchmark; no quantile/argmax needed (point forecast).

Performance

  • After 3 warmup, 10 timed runs (torch.npu.synchronize each side):
    • avg 0.0633s (63.3 ms), min 0.0607s, max 0.0645s, p50 0.0636s, p90 0.0645s, p95 0.0645s
    • Throughput 15.79 windows/s, 15.79 series/s (batch 1, context 512)
    • First-run compile already inside warmup; no separate compile time reported beyond warmup avg.
    • Peak memory: not separately measured via torch.npu.memory; weight 864 MB + activations ~ few hundred MB fits 64GB HBM; weight load peaks <1GB.
    • dtype float32, context 512, horizon 8, batch 1, use_cache False.
    • Pre-processing (CSV read + z-score) not included in timed section; timed section is pure model(input_ids, max_horizon_length=8, use_cache=False) with synchronize.
    • Device 910_9362, CANN 8.5.1, torch_npu 2.9.0.post1.

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, NPU inference, consistency, benchmark).
  • 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.

agent workflow npu device call model result

Limitations

  • Univariate only (input_size 1); multivariate OHLCV not natively supported; close only validated.
  • Horizons limited to [1,8,32,64] as per config; other horizons would require interpolation or iterative generation.
  • Single NPU npu:0 only; multi-NPU not tested.
  • use_cache=False used to avoid transformers 4.57 Cache API incompatibility (get_usable_length/get_max_length/seen_tokens removed); accuracy unaffected (float32 error <2e-6), but caching speed-up disabled (≈60ms vs cached would be faster with proper 4.40 transformers). With transformers 4.40, use_cache=True would be valid.
  • BF16 checkpoint in float32 mode gives higher accuracy but uses more memory; BF16 NPU error larger (~0.01 normalized) but still small denormalized 0.002; users can switch dtype in inference.py if needed.
  • Smoke consistency only (1 window, 512 context); not full 2500-row rolling backtest or benchmark ranking.
  • No fine-tuning; foundation model zero-shot forecast only.