waylong/Maple728-TimeMoE-50M-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Maple728/TimeMoE-50M NPU Adapted

#NPU

Model Information

  • Model Name: Maple728/TimeMoE-50M
  • Model Weight URL: https://huggingface.co/Maple728/TimeMoE-50M
  • Model Revision: 446753ee48ff3726d0606a81d0092d54acee995e
  • Pipeline Tag: time-series-forecasting
  • Architecture Family: Time-Series Foundation Model with Mixture-of-Experts (MoE) - Decoder-only Autoregressive
  • Task Type: forecasting (univariate, point prediction, arbitrary horizon via autoregressive generation)
  • Parameter Count: ~113M BF16 params (217MB safetensors), Config: hidden 384, 12 layers, 12 heads, 8 experts (2 per token), intermediate 1536, horizon [1,8,32,64], max_position 4096
  • Paper: https://arxiv.org/abs/2409.16040 (Time-MoE: Billion-Scale Time Series Foundation Models with Mixture of Experts, ICLR25 Spotlight)
  • License: apache-2.0
  • Original Repository: https://github.com/Time-MoE/Time-MoE
  • Torch Dtype: bfloat16 (inference tested with float32 for precise CPU-NPU comparison; bfloat16 also works on NPU)

Architecture Details

ComponentConfig
Modelhidden_size=384, num_hidden_layers=12, num_attention_heads=12, num_key_value_heads=12, intermediate_size=1536, hidden_act=silu, num_experts=8, num_experts_per_tok=2, rms_norm_eps=1e-6, rope_theta=10000, attention_dropout=0.0, use_cache=True, tie_word_embeddings=False
Inputinput_size=1 (univariate, channel-independent), max_position_embeddings=4096
OutputTimeMoeOutputLayer per horizon (1/8/32/64) -> Linear hidden->input*horizon
GenerationTSGenerationMixin._greedy_search (autoregressive, picks lm_head that matches remaining max_new_tokens)
Devicenpu:0 (Ascend910_9362)
Precisionfloat32 baseline (verified), bfloat16 native (config torch_dtype=bfloat16)
Context400 used (configurable, max 4096 - pred_len)

Data Contract

  • Data Source: working/sample_data.csv (synthesized fallback uses same schema), SHA c389b492a121af65d1c6f502c8e7c3044f0d01ba1da16fc20062b07d953e0b6f, 599 rows, 35683 bytes
  • Format: CSV with columns timestamps, open, high, low, close, volume, amount
  • Used Column: close univariate series (input_size=1). Other columns ignored for TimeMoE (channel-independent). Full schema preserved for generic time-series datasets.
  • Rows: 599 (example uses first 400 as context, next 64 as forecast, total 464 <4096; remaining rows unused)
  • Columns / Dtypes: timestamps: datetime64[us], open/high/low/close/volume/amount: float64
  • Missing Values: 0
  • Time Column: timestamps (5min frequency, 2024-06-18 11:15 -> 2024-07-04 14:35)
  • Target: close (univariate forecasting)
  • Preprocessing:
    • Per-window z-score normalization: normed = (x - mean) / std where mean/std computed on context window (400). mean=10.960475, std=0.176887 for the default window.
    • Input tensor shape [1, 400] float32, [Batch, Time] (unsqueezed internally to [B,T,1]).
    • No inverse scaling of timestamps; only series values.
    • Generation: model.generate(normed_context, max_new_tokens=64) -> normed_pred = output[0,-64:] -> pred = normed_pred * std + mean
  • Axis Order: [Batch, Time] input, [Batch, Time+Pred] output; multivariate case would be channel-independent per series
  • Frequency: 5min (irregular market hours, but model is frequency-agnostic)
  • Scaling: Inverse transform applied before returning forecast; normed values kept for debugging
  • Seeds: 42 fixed for deterministic greedy generation (top_k=1, T=1.0)

Data privacy: no private data submitted; logs only show schema statistics and close forecasts.

Environment

ItemVersion
Python3.11.14
Torch2.9.0+cpu
torch_npu2.9.0.post1+gitee7ba04
Transformers4.40.1 (required; 4.57 incompatible without patch)
Accelerate1.14.0
Pandas3.0.2
Numpy1.26.4
Huggingface_hub0.36.2
Safetensors0.7.0
Ascend Toolkit/usr/local/Ascend/cann-8.5.1 (SOC ascend910_9391)
NPUAscend910_9362, 2 devices, visible 4,5
CANN8.5.1

NPU check:

torch.npu.is_available()==True, device_count=2, device_name=Ascend910_9362
npu-smi info OK

Peak memory for TimeMoE-50M on npu:0: ~500 MB (weights 217MB + KV cache + activations for 400+64 length; well within 64GB).

Installation

pip install -r requirements.txt
# For Chinese mirror: pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt

Requirements (pinned for reproducibility):

torch==2.9.0
torch_npu==2.9.0.post1
transformers==4.40.1
accelerate==1.14.0
huggingface_hub
safetensors
pandas==3.0.2
numpy==1.26.4
tqdm
scikit-learn

Model download (first run, then cached):

export HF_ENDPOINT=https://hf-mirror.com
export HF_HUB_DISABLE_XET=1
# model will be auto-downloaded to working/models/TimeMoE-50M or huggingface cache

NPU Inference

Default command (verified on Ascend 910B, npu:0):

python inference.py

What it does:

  1. Checks torch.npu.is_available() and npu-smi info
  2. Sets torch.npu.set_device(0)
  3. Loads model from local working/models/TimeMoE-50M or downloads from HF hub with revision pinned (446753...)
  4. Moves model to npu:0 via .to("npu:0")
  5. Loads sample data (seed 42, context 400, pred 64, univariate close)
  6. Normalizes, runs model.generate(normed_context, max_new_tokens=64) under torch.no_grad() and torch.npu.synchronize() timing
  7. Inverse normalizes, prints input/output device, shape, stats, timing, and success status (exit 0 = success)
  8. Runs warmup 3 + benchmark 10, reports avg/min/max/p50/p90/p95

Expected output excerpt:

[LOAD] model first param device: npu:0
[INFER] Completed in 0.3166s (sync timed)
[RESULT] Forecast tensor shape (64,), finite True
[RESULT] pred head (first 5): [10.815929 10.811933 10.808162 10.80629  10.805475]
[STATUS] NPU inference SUCCESS on npu:0, elapsed 0.3166s

Dummy tensor verification:

[VERIFY] Dummy tensor device: npu:0
[VERIFY] Model param device after inference: npu:0

No CPU fallback: explicit device="npu:0" and torch.npu.synchronize(); if NPU unavailable, script exits non-zero. Model params remain on npu:0 throughout; next(model.parameters()).device == npu:0.

Results

Real NPU inference on Ascend910_9362 (context 400 -> pred 64, batch 1, FP32, seed 42, deterministic greedy):

MetricValue
Context mean/std10.960475 / 0.176887
First forecast close10.815929
Fifth forecast close10.805475
Last forecast close10.817074
Forecast mean close10.7944
Forecast std close0.0135
Forecast min / max10.7712 / 10.8171
Elapsed (first compile)0.3057s
Second run0.0587s
Stable avg (10 runs)0.0603s
FiniteTrue
Ground truth MAE (next 64 closes)0.067848

Full forecast head (first 5, denormalized):

[10.815929 10.811933 10.808162 10.80629  10.805475]

Normed head:

[-0.81716263 -0.83976007 -0.86107695 -0.87165713 -0.87626255]

Tail (last 5):

[10.811561 10.815245 10.815043 10.816345 10.817074]

Ground truth future close head (for reference, zero-shot):

[10.82 10.81 10.78 10.76 10.75]  # from sample_data.csv rows 400-404

Consistency

CPU vs NPU on identical weights, data, preprocessing, seed=42, dtype float32, eval mode, greedy:

  • CPU: torch.manual_seed(42) on cpu, AutoModelForCausalLM.from_pretrained(..., torch_dtype=torch.float32, device_map="cpu")
  • NPU: torch.npu.set_device(0) + same seed, same model.generate(normed_context, max_new_tokens=64) with same normalization
  • Fresh input tensor per run (to avoid in-place unsqueeze_ mutation side-effect)

Outputs saved as .npy (forecast tensor shape [64] float32):

  • CPU: working/cpu_output.npy (and cpu_normed.npy)
  • NPU: working/npu_output.npy

Compare via scripts/compare_outputs.py --task regression --atol 1e-4 --rtol 1e-3:

{
  "task": "regression",
  "cpu_shape": [64],
  "npu_shape": [64],
  "finite": true,
  "atol": 0.0001,
  "rtol": 0.001,
  "max_abs_error": 9.5367431640625e-07,
  "mean_abs_error": 6.407499313354492e-07,
  "passed": true
}

Max abs error 9.5e-07 on close price scale ~10.96, relative ~8.7e-08, far within tolerance. Normed space max diff 5.48e-06. Smoke consistency only (single window 400->64), not full dataset benchmark.

No CPU fallback observed; model params remain on npu:0 throughout (next(model.parameters()).device == npu:0, dummy tensor on npu:0). Second run 0.0587s confirms stable NPU execution after compile.

Performance

Measured on npu:0, float32, batch=1, context=400, pred=64, input_size=1, horizon [1,8,32,64] (single step 64 via horizon 64):

  • First run (compile, includes MoE routing, RoPE, KV cache init): 0.3057s
  • Second run (stable): 0.0587s
  • Warmup 3 + Formal 10: avg 0.0603s, min 0.0600s, max 0.0607s, p50 0.0604s, p90 0.0606s, p95 0.0607s
  • Throughput: 16.58 windows/s (or series/s) stable (=1/0.0603)
  • Tokens: context 400 + generate 64 in single autoregressive step (horizon 64)
  • Peak NPU memory: ~500 MB estimated (weights 217MB + runtime)
  • Rows/s: not applicable (time-series). Windows/s reported.
  • Preprocessing timed included? Timing wraps only model.generate (includes embed, 12 decoder layers with MoE, RoPE, output head). CSV I/O and normalization outside timed region. torch.npu.synchronize() before and after.
  • CPU baseline same window: 0.90s (15x slower than NPU stable, 3x slower than NPU compile), confirming NPU acceleration.

Detailed perf.json:

{
  "context_length": 400,
  "prediction_length": 64,
  "max_position_embeddings": 4096,
  "first_run_sec": 0.3056674003601074,
  "second_run_sec": 0.05869007110595703,
  "stable_avg_sec": 0.0603276252746582,
  "min_sec": 0.05998039245605469,
  "max_sec": 0.06069016456604004,
  "p50": 0.06035566329956055,
  "p90": 0.060616135597229004,
  "p95": 0.06065315008163452,
  "dtype": "torch.float32",
  "batch": 1,
  "device": "npu:0"
}

Evidence

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

  • assets/agent_workflow.png - full adaptation workflow: inspect, data check, download, load, NPU inference, consistency, benchmark, validation
  • assets/npu_device_call.png - npu-smi and NPU device calls (model param device npu:0, dummy tensor npu:0)
  • assets/model_result.png - default python inference.py output (forecast head, timing, SUCCESS)

Rendered with xterm.js raw style, dark grey background, white monospace. Logs sanitized for tokens.

workflow device result

Evidence generated by xterm.js from real stdout/stderr, UTC timestamps, exit codes preserved.

Limitations

  • Only single window (400->64) smoke consistency, not full dataset evaluation (599 rows would be multiple windows; full benchmark not done)
  • Float32 only for precise comparison; bfloat16 native supported but not benchmarked (config torch_dtype=bfloat16; NPU bf16 may have slightly higher error)
  • Deterministic greedy generation only (max_new_tokens with argmax); stochastic sampling not tested
  • Univariate close only; multivariate would require per-channel independence (input_size=1) and not validated
  • Data is 5min K-line from Jun-Jul 2024 (Chinese A-share style); other frequencies/markets/domains not validated
  • 4096 max context; longer contexts truncated
  • Requires Ascend CANN 8.5.1, torch_npu 2.9.0, transformers 4.40.1, internet for HF download on first run (cached thereafter)
  • Not training adaptation, only inference (TimeMoE is zero-shot foundation model)
  • Weight size 217MB, total 113M params; fits single 910B but not tested on smaller memory variants
  • Original TimeMoE-50M paper: 50M active? but total 113M due to MoE (8 experts, 2 active per token)

References

  • Time-MoE paper: https://arxiv.org/abs/2409.16040
  • GitHub: https://github.com/Time-MoE/Time-MoE
  • HF Model: https://huggingface.co/Maple728/TimeMoE-50M
  • Datasets: https://huggingface.co/datasets/Maple728/Time-300B