File size: 8,991 Bytes
02412f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared OpenAI-compatible client for the LLM method families.

Every LLM-family method (``methods/llm.py``, ``methods/llm_ts_reason.py``,
``methods/llm_finetune.py``) talks to a vLLM-served model via the OpenAI
HTTP API. This module owns the client lifecycle and the batch-fan-out
helper so the per-task code paths can rely on a single shared protocol::

    text: str = engine.chat_complete(messages, max_tokens=256, temperature=0.0)
    texts: list[str] = engine.chat_complete_batch(
        [messages_a, messages_b, ...], max_tokens=256, temperature=0.0,
    )

Why a shared module
-------------------
Before this refactor the three LLM-family files used three different
engine protocols (``vllm.LLM.generate``, ``engine.answer``,
``engine.generate``). Centralising the protocol on the OpenAI-compatible
HTTP client lets vLLM serve the model out-of-process behind ``vllm serve
...`` and removes the in-process Python SDK dependency from the runner.

Canonical vLLM serve commands (one terminal per model)
------------------------------------------------------
The ``model_id`` strings below match the defaults in
``methods/_config.py`` (``LlamaScoutConfig`` / ``Gemma4Config`` /
``Exaone45Config`` / ``Qwen35Config`` and the ``llm_ts_reason`` configs).
Any out-of-band fine-tune is served as a separate ``model`` id on the
LoRA-aware vLLM endpoint::

    # Llama-4 Scout 109B-MoE (FP8) — TP=4
    vllm serve meta-llama/Llama-4-Scout-17B-16E-Instruct \\
      --tensor-parallel-size 4 --gpu-memory-utilization 0.9 \\
      --port 8001 --quantization fp8

    # Gemma-4 31B (FP8) — TP=2
    vllm serve google/gemma-4-31B-it --tensor-parallel-size 2 \\
      --port 8002 --quantization fp8

    # EXAONE-4.5 33B (FP8) — TP=2
    vllm serve LGAI-EXAONE/EXAONE-4.5-33B-FP8 --tensor-parallel-size 2 \\
      --port 8003 --quantization fp8

    # Qwen-3.5 27B (FP8) — TP=1
    vllm serve Qwen/Qwen3.5-27B-FP8 --tensor-parallel-size 1 \\
      --port 8004 --quantization fp8

    # ChatTime-1-7B-Chat
    vllm serve ChengsenWang/ChatTime-1-7B-Chat --tensor-parallel-size 1 \\
      --port 8005

    # ITFormer-ICML25
    vllm serve Pandalin98/ITFormer-ICML25 --tensor-parallel-size 1 \\
      --port 8006

    # Time-MQA (LoRA over Qwen2.5-7B)
    vllm serve Qwen/Qwen2.5-7B-Instruct --tensor-parallel-size 1 \\
      --port 8007 --enable-lora \\
      --lora-modules time_mqa=Time-MQA/Qwen-2.5-7B

    # LLMFineTuned (LoRA-served on top of one of the panel base models)
    vllm serve <BASE_MODEL_ID> --enable-lora \\
      --lora-modules llm_finetuned=<ADAPTER_DIR_OR_HF_REPO> \\
      --port 8008
"""

from __future__ import annotations

import logging
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Sequence

logger = logging.getLogger(__name__)


# ── Real engine: OpenAI Python SDK against a vLLM HTTP endpoint ──────────


class OpenAIChatEngine:
    """Thin wrapper around the OpenAI Python SDK targeting a vLLM endpoint.

    Construction::

        engine = OpenAIChatEngine(
            base_url="http://localhost:8001/v1",
            api_key="EMPTY",
            model_id="meta-llama/Llama-4-Scout-17B-16E-Instruct",
            n_workers=8,
            request_timeout_sec=300.0,
        )

    The OpenAI SDK is sync-per-call; ``chat_complete_batch`` fans out N
    independent requests over a thread pool (the standard pattern for
    parallelising HTTP I/O without requiring an async event loop).
    """

    def __init__(
        self,
        *,
        base_url: str,
        api_key: str = "EMPTY",
        model_id: str,
        n_workers: int = 8,
        request_timeout_sec: float = 300.0,
    ) -> None:
        import os, json
        from openai import OpenAI

        self.base_url = base_url
        self.model_id = model_id
        self.n_workers = int(n_workers)
        self.request_timeout_sec = float(request_timeout_sec)
        self._client = OpenAI(
            base_url=base_url,
            api_key=api_key,
            timeout=request_timeout_sec,
        )
        # Optional OpenRouter provider routing via env var.
        # MACROLENS_LLM_EXTRA_BODY = JSON dict, e.g.
        #   '{"provider": {"order": ["DeepInfra"]}}'
        # Forwarded as extra_body to chat.completions.create.
        eb = os.environ.get("MACROLENS_LLM_EXTRA_BODY", "").strip()
        self._extra_body: dict | None = None
        if eb:
            try:
                self._extra_body = json.loads(eb)
            except json.JSONDecodeError:
                self._extra_body = None

    def chat_complete(
        self,
        messages: list[dict[str, str]],
        *,
        max_tokens: int = 256,
        temperature: float = 0.0,
        top_p: float = 1.0,
    ) -> str:
        """Single chat completion. Returns the assistant message text."""
        kwargs: dict = dict(
            model=self.model_id,
            messages=messages,
            max_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
        )
        if self._extra_body:
            kwargs["extra_body"] = self._extra_body
        resp = self._client.chat.completions.create(**kwargs)
        return resp.choices[0].message.content or ""

    def chat_complete_batch(
        self,
        batched_messages: Sequence[list[dict[str, str]]],
        *,
        max_tokens: int = 256,
        temperature: float = 0.0,
        top_p: float = 1.0,
    ) -> list[str]:
        """Fan out N chat completions over a thread pool. Order preserved.

        Per-request exceptions (HTTP errors, JSON-decode failures from a
        provider returning HTML error pages, connection resets) are caught
        here so one bad response cannot kill an entire batch of 1,000
        predictions: the failed slot returns the empty string and the
        downstream parser substitutes NaN, which the eval-side fillna(0)
        rule scores as the predict-zero penalty.
        """
        if not batched_messages:
            return []
        def _safe(msgs: list[dict[str, str]]) -> str:
            try:
                return self.chat_complete(
                    msgs, max_tokens=max_tokens,
                    temperature=temperature, top_p=top_p,
                )
            except Exception as e:
                logger.warning(
                    "chat_complete failed for one prompt: %s; emitting empty "
                    "string (downstream parser will yield NaN).",
                    type(e).__name__,
                )
                return ""
        with ThreadPoolExecutor(max_workers=self.n_workers) as ex:
            futs = [ex.submit(_safe, msgs) for msgs in batched_messages]
            return [f.result() for f in futs]


# ── Dry-run engine for CPU-only smoke tests ──────────────────────────────


class DryRunEngine:
    """Deterministic CPU-only stand-in for unit-test / dry-run paths.

    ``chat_complete`` returns a single parseable fake response that
    matches every parser path the LLM-family methods use simultaneously
    (number, JSON object, JSON list). The horizon is parameterised so T1
    JSON-array predictions tile to the right width.
    """

    def __init__(self, horizon: int = 21) -> None:
        self.horizon = int(horizon)
        self.model_id = "dry-run"

    def chat_complete(
        self,
        messages: list[dict[str, str]],
        *,
        max_tokens: int = 256,
        temperature: float = 0.0,
        top_p: float = 1.0,
    ) -> str:
        # Inspect the user prompt to honour task-specific horizon hints
        # (e.g. T1 prompts that say "JSON array of N floats"). If the
        # message lists do not surface a hint, fall back to ``self.horizon``.
        horizon = self.horizon
        try:
            text = " ".join(
                str(m.get("content", "")) for m in (messages or [])
            ).lower()
        except Exception:
            text = ""
        import re as _re

        m = _re.search(r"json array of (\d+) floats", text)
        if m:
            try:
                horizon = int(m.group(1))
            except ValueError:
                pass

        list_str = "[" + ", ".join(["1.0"] * horizon) + "]"
        return (
            f'{{"value": 1.0, "rent": 2000.0, "price": 500000.0, '
            f'"Revenues": 1000000, "NetIncomeLoss": 100000}} '
            f"forecast=1.0 return=0.0 trajectory={list_str}"
        )

    def chat_complete_batch(
        self,
        batched_messages: Sequence[list[dict[str, str]]],
        *,
        max_tokens: int = 256,
        temperature: float = 0.0,
        top_p: float = 1.0,
    ) -> list[str]:
        return [
            self.chat_complete(
                msgs,
                max_tokens=max_tokens,
                temperature=temperature,
                top_p=top_p,
            )
            for msgs in batched_messages
        ]


__all__ = ["OpenAIChatEngine", "DryRunEngine"]