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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
"""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) ─────────────────────────────────────────────────


@dataclass
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

    @classmethod
    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)

    @staticmethod
    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"]