Download code/methods/_vendored/itformer/engine.py from DeepAuto-AI/MacroLens: direct link, hf CLI and curl.
- Browser
- Download file 20.7 kB
-
https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/methods/_vendored/itformer/engine.py
- Command line
-
hf download hf://datasets/DeepAuto-AI/MacroLens/code/methods/_vendored/itformer/engine.py
-
curl -L -o engine.py https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/methods/_vendored/itformer/engine.py
20.7 kB
| """ITFormer authors' inference pipeline wrapped behind a Pythonic engine. | |
| This module exposes :class:`ITFormerEngine`, a thin adapter that drives | |
| the official ITFormer (ICML 2025 Poster) ``inference.py`` script in | |
| batched mode. Each batch of (prompt, time-series) pairs is written to a | |
| temp ``ts_data.h5`` + ``qa_data.jsonl`` + ``infer.yaml`` triple, the | |
| authors' CLI is invoked once, and the resulting ``inference_results_*.json`` | |
| is read back and split into one generated string per input. | |
| Usage from :mod:`methods.llm_ts_reason.ITFormer` (per-task predictors): | |
| engine = ITFormerEngine.create( | |
| upstream_dir=..., # auto-detected if None | |
| checkpoint=..., # default Pandalin98/ITFormer-ICML25 (0.5B) | |
| input_len=600, # ITFormer architecture default | |
| prefix_num=10, | |
| batch_size=8, | |
| max_new_tokens=200, | |
| device="cuda" or "cpu", | |
| ) | |
| texts = engine.predict_batch( | |
| ts_arr=np.ndarray (N, L) float32, # one signal per prompt | |
| prompts=[str, ...] (length N), | |
| ) | |
| Why this exists (limitation disclosure) | |
| --------------------------------------- | |
| ITFormer's published inference is a CLI driver over the EngineMT-QA | |
| schema (HDF5 single-channel signals + JSONL conversation pairs), not a | |
| Python-importable function. The authors' ``main_inference(args)`` pulls | |
| in ``Accelerator()``, parses YAML, materialises a ``DataLoader``, and | |
| calls ``model.generate()``. Wrapping that as a per-prompt Python call | |
| would mean re-implementing dataset / collator / generate semantics, | |
| which the user explicitly forbids ("ALWAYS use the authors' official | |
| repo code; never re-implement from the paper text"). | |
| The compromise here is faithful but coarse: we drive the authors' code | |
| verbatim via subprocess, paying one process startup per | |
| :meth:`predict_batch` call. The Method-level adapter | |
| (:class:`methods.llm_ts_reason.ITFormer`) calls ``predict_batch`` ONCE | |
| per task (not once per sample), so subprocess overhead is amortised. | |
| What is faithful | |
| ---------------- | |
| - Authors' ``inference.py`` runs unmodified: same model class, same | |
| ``generate`` call, same tokenizer, same chat-template substitution of | |
| ``<ts>`` -> ``<|image_pad|> * prefix_num``. | |
| - HDF5 + JSONL format matches the authors' ``TsQaDataset`` reader. | |
| - YAML config fields mirror ``yaml/infer.yaml`` defaults verified against | |
| upstream commit on 2026-05-05 via WebFetch. | |
| What is NOT faithful (documented limitation; mirrored in DRAFT.md) | |
| ------------------------------------------------------------------ | |
| - The published pipeline expects EngineMT-QA (industrial engine sensor | |
| signals); we feed it (close-price lookback, financial QA prompt) pairs. | |
| This is the same domain transfer the legacy | |
| :func:`baselines.llm_ts_reason.run_itformer` already performed; we are | |
| not making any NEW deviation, only honouring the published format. | |
| - Stages 2/3 in ITFormer's protocol are MULTIPLE-CHOICE; our T2..T7 are | |
| open-ended numeric / structured. We therefore mark every prompt as | |
| ``stage='1'`` (open question) so the model emits free-form text, which | |
| the calling parser then coerces to a number / dict / DataFrame row. | |
| """ | |
| from __future__ import annotations | |
| import glob | |
| import json | |
| import logging | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import Any, Sequence | |
| import numpy as np | |
| logger = logging.getLogger(__name__) | |
| # Upstream repo locator. We prefer to reuse the existing legacy clone at | |
| # ``baselines/_vendor/itformer/`` (3.5 MB; already cloned by the legacy | |
| # baselines path) over a duplicate clone under ``methods/_vendored/``. | |
| # If neither path exists we shallow-clone into ``methods/_vendored/itformer/upstream``. | |
| _UPSTREAM_URL = "https://github.com/Pandalin98/ITFormer-ICML25.git" | |
| _UPSTREAM_REF = "main" | |
| def _legacy_clone_dir() -> Path: | |
| """Return the legacy ``baselines/_vendor/itformer`` clone path.""" | |
| return ( | |
| Path(__file__).resolve().parents[3] | |
| / "baselines" | |
| / "_vendor" | |
| / "itformer" | |
| ) | |
| def _vendored_clone_dir() -> Path: | |
| """Return the canonical ``methods/_vendored/itformer/upstream`` clone path.""" | |
| return Path(__file__).resolve().parent / "upstream" | |
| def _is_repo(path: Path) -> bool: | |
| return (path / "inference.py").is_file() and (path / "models").is_dir() | |
| def _ensure_upstream(*, allow_clone: bool = True) -> Path: | |
| """Locate an upstream ITFormer clone, optionally cloning if missing. | |
| Lookup order: | |
| 1. ``$MACROLENS_ITFORMER_REPO`` env var (explicit override). | |
| 2. ``baselines/_vendor/itformer/`` (legacy clone — preferred to avoid | |
| duplicating 3.5 MB on disk). | |
| 3. ``methods/_vendored/itformer/upstream/`` (this module's local | |
| clone slot). | |
| 4. Shallow-clone into slot (3) if ``allow_clone`` is True. | |
| """ | |
| explicit = os.environ.get("MACROLENS_ITFORMER_REPO", "").strip() | |
| if explicit: | |
| path = Path(explicit).expanduser().resolve() | |
| if not _is_repo(path): | |
| raise FileNotFoundError( | |
| f"MACROLENS_ITFORMER_REPO={path} is not an ITFormer repo " | |
| "(expected inference.py + models/ at the path root)." | |
| ) | |
| return path | |
| legacy = _legacy_clone_dir() | |
| if _is_repo(legacy): | |
| return legacy | |
| vendored = _vendored_clone_dir() | |
| if _is_repo(vendored): | |
| return vendored | |
| if not allow_clone: | |
| raise FileNotFoundError( | |
| "ITFormer upstream clone not found. Set " | |
| "MACROLENS_ITFORMER_REPO=<path> or run with allow_clone=True." | |
| ) | |
| vendored.parent.mkdir(parents=True, exist_ok=True) | |
| logger.info("Cloning %s into %s ...", _UPSTREAM_URL, vendored) | |
| subprocess.run( | |
| [ | |
| "git", "clone", "--depth", "1", "--branch", _UPSTREAM_REF, | |
| _UPSTREAM_URL, str(vendored), | |
| ], | |
| check=True, | |
| capture_output=True, | |
| ) | |
| return vendored | |
| # ── ITFormer config defaults (verified against upstream yaml/infer.yaml, | |
| # fetched 2026-05-05) ───────────────────────────────────────────────── | |
| class _ITFormerCfg: | |
| # Architecture (must match the checkpoint that ``model_checkpoint`` loads). | |
| d_model: int = 512 | |
| n_heads: int = 8 | |
| e_layers: int = 4 | |
| patch_len: int = 60 | |
| stride: int = 60 | |
| input_len: int = 600 | |
| dropout: float = 0.1 | |
| it_d_model: int = 896 | |
| it_n_heads: int = 16 | |
| it_layers: int = 2 | |
| it_dropout: float = 0.1 | |
| prefix_num: int = 25 | |
| # I/O. | |
| fp16: bool = True | |
| dataloader_pin_memory: bool = True | |
| dataloader_num_workers: int = 4 | |
| # Per-batch override fields (filled at run time). | |
| ts_path_test: str = "" | |
| qa_path_test: str = "" | |
| def to_dict(self) -> dict[str, Any]: | |
| d = { | |
| "d_model": self.d_model, | |
| "n_heads": self.n_heads, | |
| "e_layers": self.e_layers, | |
| "patch_len": self.patch_len, | |
| "stride": self.stride, | |
| "input_len": self.input_len, | |
| "dropout": self.dropout, | |
| "it_d_model": self.it_d_model, | |
| "it_n_heads": self.it_n_heads, | |
| "it_layers": self.it_layers, | |
| "it_dropout": self.it_dropout, | |
| "prefix_num": self.prefix_num, | |
| "fp16": self.fp16, | |
| "dataloader_pin_memory": self.dataloader_pin_memory, | |
| "dataloader_num_workers": self.dataloader_num_workers, | |
| "ts_path_test": self.ts_path_test, | |
| "qa_path_test": self.qa_path_test, | |
| } | |
| return d | |
| # ── Engine ───────────────────────────────────────────────────────────────── | |
| class ITFormerEngine: | |
| """Thin Python wrapper over the authors' ``inference.py`` CLI. | |
| Public surface: | |
| - :meth:`create` (classmethod) — locate / clone the upstream repo and | |
| validate it; returns a configured engine. | |
| - :meth:`predict_batch` — run one CLI invocation over N samples. | |
| Construction is cheap (validates paths only); the actual model load | |
| happens inside the subprocess on every :meth:`predict_batch` call. | |
| """ | |
| def __init__( | |
| self, | |
| *, | |
| upstream_dir: Path, | |
| checkpoint: str = "pandalin98/ITFormer-7B", | |
| cfg: _ITFormerCfg | None = None, | |
| batch_size: int = 8, | |
| max_new_tokens: int = 200, | |
| seed: int = 42, | |
| timeout_sec: float = 3600.0, | |
| python_exe: str | None = None, | |
| ) -> None: | |
| if not _is_repo(upstream_dir): | |
| raise FileNotFoundError( | |
| f"upstream_dir={upstream_dir} is not a valid ITFormer repo." | |
| ) | |
| self.upstream_dir = upstream_dir | |
| self.checkpoint = str(checkpoint) | |
| self.cfg = cfg or _ITFormerCfg() | |
| self.batch_size = int(batch_size) | |
| self.max_new_tokens = int(max_new_tokens) | |
| self.seed = int(seed) | |
| self.timeout_sec = float(timeout_sec) | |
| # The authors' ``inference.py`` imports torch / transformers / | |
| # accelerate / h5py from the active interpreter's site-packages, | |
| # so we default to the same Python that imported this module. | |
| self.python_exe = python_exe or sys.executable | |
| def create( | |
| cls, | |
| *, | |
| upstream_dir: Path | str | None = None, | |
| checkpoint: str = "pandalin98/ITFormer-7B", | |
| input_len: int = 600, | |
| prefix_num: int = 25, | |
| batch_size: int = 8, | |
| max_new_tokens: int = 200, | |
| seed: int = 42, | |
| allow_clone: bool = True, | |
| ) -> "ITFormerEngine": | |
| """Locate / clone the upstream repo and return a configured engine.""" | |
| if upstream_dir is None: | |
| up = _ensure_upstream(allow_clone=allow_clone) | |
| else: | |
| up = Path(upstream_dir).expanduser().resolve() | |
| if not _is_repo(up): | |
| raise FileNotFoundError( | |
| f"upstream_dir={up} is not a valid ITFormer repo." | |
| ) | |
| cfg = _ITFormerCfg( | |
| input_len=int(input_len), | |
| prefix_num=int(prefix_num), | |
| patch_len=min(60, int(input_len)), | |
| stride=min(60, int(input_len)), | |
| ) | |
| return cls( | |
| upstream_dir=up, | |
| checkpoint=checkpoint, | |
| cfg=cfg, | |
| batch_size=batch_size, | |
| max_new_tokens=max_new_tokens, | |
| seed=seed, | |
| ) | |
| # ── HF checkpoint resolver ── | |
| def _resolve_checkpoint_path(self) -> str: | |
| """Return a local-filesystem path to the checkpoint directory. | |
| ``self.checkpoint`` may be either a local path (passed straight | |
| through after existence check) or a HuggingFace repo id like | |
| ``pandalin98/ITFormer-7B``. The authors' ``inference.py`` does | |
| ``os.path.exists(model_checkpoint)`` rather than HF auto-download, | |
| so we resolve repo ids via ``huggingface_hub.snapshot_download`` | |
| (cached) and pass the resulting local directory. | |
| Cached on the instance so multi-task runs hit the resolver once. | |
| """ | |
| if hasattr(self, "_resolved_checkpoint") and self._resolved_checkpoint: | |
| return self._resolved_checkpoint | |
| ckpt = str(self.checkpoint) | |
| if os.path.isdir(ckpt) or os.path.isfile(ckpt): | |
| self._resolved_checkpoint = ckpt | |
| return ckpt | |
| try: | |
| from huggingface_hub import snapshot_download # lazy | |
| except ImportError as exc: | |
| raise RuntimeError( | |
| "ITFormer engine: huggingface_hub is required to resolve " | |
| f"checkpoint repo id {ckpt!r}; install or pass a local " | |
| "directory path instead." | |
| ) from exc | |
| local_path = snapshot_download(repo_id=ckpt) | |
| self._resolved_checkpoint = str(local_path) | |
| return self._resolved_checkpoint | |
| # ── Batch driver ── | |
| def predict_batch( | |
| self, | |
| *, | |
| ts_arr: np.ndarray, | |
| prompts: Sequence[str], | |
| scratch_dir: Path | None = None, | |
| ) -> list[str]: | |
| """Run one CLI invocation over N samples; return N decoded strings. | |
| Args: | |
| ts_arr: ``(N, L)`` float32 single-channel signals. ``L`` should | |
| match ``self.cfg.input_len``; if shorter, the array is | |
| left-padded with zeros (the authors' loader has no notion | |
| of attention masks for the time series so zero-padding is | |
| the standard convention). | |
| prompts: ``N`` natural-language prompts. ``"<ts>"`` is | |
| inserted at position 0 if not already present (the | |
| authors' chat-template substitutes it for prefix_num | |
| ``<|image_pad|>`` tokens). | |
| scratch_dir: optional override; defaults to a fresh tempdir. | |
| Returns: | |
| A length-N list of generated text strings, in the same order | |
| as ``prompts``. Missing entries (parse failure / index gap) | |
| are returned as empty strings — the caller decides how to | |
| handle parse errors. | |
| """ | |
| prompts = list(prompts) | |
| n = len(prompts) | |
| if ts_arr.ndim != 2: | |
| raise ValueError( | |
| f"ts_arr must be 2-D (N, L); got shape {ts_arr.shape}" | |
| ) | |
| if ts_arr.shape[0] != n: | |
| raise ValueError( | |
| f"ts_arr.shape[0]={ts_arr.shape[0]} != len(prompts)={n}" | |
| ) | |
| if n == 0: | |
| return [] | |
| # Pad / truncate to input_len. | |
| L_target = int(self.cfg.input_len) | |
| L_in = ts_arr.shape[1] | |
| if L_in == L_target: | |
| ts_padded = ts_arr.astype(np.float32, copy=False) | |
| elif L_in > L_target: | |
| ts_padded = ts_arr[:, -L_target:].astype(np.float32, copy=False) | |
| else: | |
| ts_padded = np.zeros((n, L_target), dtype=np.float32) | |
| ts_padded[:, -L_in:] = ts_arr.astype(np.float32, copy=False) | |
| # Materialise scratch directory. | |
| owns_scratch = scratch_dir is None | |
| scratch = ( | |
| Path(tempfile.mkdtemp(prefix="itformer_engine_")) | |
| if owns_scratch | |
| else Path(scratch_dir) | |
| ) | |
| scratch.mkdir(parents=True, exist_ok=True) | |
| try: | |
| return self._invoke(scratch, ts_padded, prompts) | |
| finally: | |
| if owns_scratch: | |
| shutil.rmtree(scratch, ignore_errors=True) | |
| # ── Internals ── | |
| def _invoke( | |
| self, | |
| scratch: Path, | |
| ts_padded: np.ndarray, | |
| prompts: list[str], | |
| ) -> list[str]: | |
| # Lazy h5py import so this module is importable on minimal envs. | |
| import h5py | |
| import yaml | |
| n = len(prompts) | |
| h5_path = scratch / "ts_data.h5" | |
| # Authors' TimeSeriesEncoder.forward expects (B, L, F) tensors (it | |
| # transposes dims (1, 2) before patching). The TsQaDataset returns | |
| # ``ts_values`` straight from this HDF5 row, so we must write the | |
| # dataset as (N, L, 1) — single-channel signals — to get | |
| # batched (B, L, 1) tensors at training time. | |
| if ts_padded.ndim == 2: | |
| ts_padded_3d = ts_padded[..., None] | |
| else: | |
| ts_padded_3d = ts_padded | |
| with h5py.File(str(h5_path), "w") as f: | |
| f.create_dataset("seq_data", data=ts_padded_3d) | |
| # Build JSONL — one entry per prompt; id is 1-indexed (the authors | |
| # subtract 1 in TsQaDataset before HDF5 lookup). All prompts are | |
| # tagged stage='1' (open question) since our parsers consume | |
| # free-form text, not multiple-choice answers; the upstream | |
| # build_index loop drops any entry whose stage is outside | |
| # {'1','2','3','4'}, so '1' is the only safe open-text choice. | |
| jsonl_path = scratch / "qa_data.jsonl" | |
| with open(jsonl_path, "w", encoding="utf-8") as f: | |
| for i, prompt in enumerate(prompts): | |
| # Insert <ts> marker once if absent so chat-template | |
| # substitutes the prefix_num image_pad tokens. | |
| q = prompt if "<ts>" in prompt else f"<ts> {prompt}" | |
| entry = { | |
| "id": i + 1, | |
| "conversations": [ | |
| {"stage": "1", "attribute": "open", | |
| "value": q}, | |
| # The upstream loader requires an answer slot for | |
| # eval mode (it tokenises labels for free-form | |
| # comparison). A blank suffices since we only | |
| # consume ``prediction``, never ``is_correct``. | |
| {"stage": "1", "attribute": "open", "value": ""}, | |
| ], | |
| } | |
| f.write(json.dumps(entry) + "\n") | |
| # Write YAML. | |
| yaml_path = scratch / "infer.yaml" | |
| cfg_dict = self.cfg.to_dict() | |
| cfg_dict["ts_path_test"] = str(h5_path) | |
| cfg_dict["qa_path_test"] = str(jsonl_path) | |
| with open(yaml_path, "w", encoding="utf-8") as f: | |
| yaml.safe_dump(cfg_dict, f) | |
| # Output dir for inference_results_*.json. | |
| output_dir = scratch / "results" | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| # Compose the subprocess command. We invoke ``inference.py`` | |
| # directly (no ``accelerate launch``) since single-GPU / | |
| # single-process is sufficient for our batch sizes; ``Accelerator()`` | |
| # gracefully degrades to a no-op single-process when launched | |
| # without ``accelerate``. | |
| # Authors' inference.py does ``os.path.exists(model_checkpoint)`` | |
| # rather than HF auto-download, so an HF repo id like | |
| # ``pandalin98/ITFormer-7B`` is rejected. Resolve to a local | |
| # snapshot path (cached after first hit) so the subprocess gets | |
| # an actual directory. | |
| resolved_ckpt = self._resolve_checkpoint_path() | |
| cmd = [ | |
| self.python_exe, | |
| str(self.upstream_dir / "inference.py"), | |
| "--config", str(yaml_path), | |
| "--model_checkpoint", resolved_ckpt, | |
| "--output_dir", str(output_dir), | |
| "--seed", str(self.seed), | |
| "--batch_size", str(self.batch_size), | |
| "--max_new_tokens", str(self.max_new_tokens), | |
| ] | |
| env = dict(os.environ) | |
| # Harden against the upstream's relative imports (``from dataset...`` | |
| # ``from models...``) by pinning PYTHONPATH and cwd to the repo root. | |
| env["PYTHONPATH"] = ( | |
| f"{self.upstream_dir}{os.pathsep}{env.get('PYTHONPATH','')}" | |
| ) | |
| t0 = time.time() | |
| try: | |
| rc = subprocess.run( | |
| cmd, | |
| cwd=str(self.upstream_dir), | |
| env=env, | |
| capture_output=True, | |
| text=True, | |
| timeout=self.timeout_sec, | |
| ) | |
| except subprocess.TimeoutExpired as exc: | |
| logger.error( | |
| "ITFormer inference timed out after %.0fs (n=%d): %s", | |
| self.timeout_sec, n, exc, | |
| ) | |
| return [""] * n | |
| elapsed = time.time() - t0 | |
| if rc.returncode != 0: | |
| tail = (rc.stderr or rc.stdout or "")[-1000:] | |
| logger.error( | |
| "ITFormer inference failed (rc=%d, n=%d, %.1fs): %s", | |
| rc.returncode, n, elapsed, tail, | |
| ) | |
| return [""] * n | |
| return self._read_results(output_dir, n) | |
| def _read_results(output_dir: Path, n: int) -> list[str]: | |
| files = sorted(glob.glob(str(output_dir / "inference_results_*.json"))) | |
| if not files: | |
| logger.error("ITFormer: no result files in %s", output_dir) | |
| return [""] * n | |
| with open(files[-1], "r", encoding="utf-8") as f: | |
| results = json.load(f) | |
| if not isinstance(results, list): | |
| logger.error("ITFormer: result file is not a list: %s", files[-1]) | |
| return [""] * n | |
| # Result entries carry ``index`` matching JSONL line_num (0-based). | |
| # Build a dense list aligned to input order. | |
| out: list[str] = [""] * n | |
| for entry in results: | |
| try: | |
| idx = int(entry.get("index")) | |
| pred = str(entry.get("prediction", "")) | |
| except (TypeError, ValueError): | |
| continue | |
| if 0 <= idx < n: | |
| out[idx] = pred | |
| return out | |
| __all__ = ["ITFormerEngine"] | |