File size: 50,903 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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
"""Frontier-LLM methods (family 7 ZS) — OpenAI-compatible HTTP rewrite.

Three classes, one per HF model id, all sharing a single OpenAI-compatible
HTTP client (talking to a ``vllm serve``-hosted endpoint) that is
**dependency-injected** by the runner. One engine per HF model id is
constructed once and reused across method instances. The classes
themselves own only the task-specific prompt templates and response
parsers.

| Class        | name           | tasks              | config_class       |
|--------------|----------------|--------------------|--------------------|
| LlamaScout   | llama_scout    | T1..T7             | LlamaScoutConfig   |
| Gemma4       | gemma4         | T1..T7             | Gemma4Config       |
| Qwen35       | qwen35         | T1..T7             | Qwen35Config       |

Per-task ``predict`` output (per plan §9 method × task matrix):

    T1 : (N, horizon) np.ndarray float32 — close trajectory
    T2 : (N,) np.ndarray float64 — predicted equity_value
    T3 : pd.DataFrame [ticker, fiscal_year, field, pred] long-form
    T4 : (N,) np.ndarray float32 — predicted return_pct
    T5 : (N,) np.ndarray float64 — predicted equity_value
    T6 : pd.DataFrame [ticker, fiscal_year, field, pred] long-form
    T7 : pd.DataFrame [address, pred_rent, pred_price]

Hard rules (enforced by ``tests/test_layer_isolation.py``):
- Zero IO of benchmark data.
- Zero eval imports.
- Zero ``meta`` consumption.
- Engine NOT instantiated in ``__init__``; the runner injects it.

Engine protocol (see :mod:`methods._openai_engine`):
- ``engine.chat_complete(messages, max_tokens, temperature, top_p) -> str``
- ``engine.chat_complete_batch(batched_messages, max_tokens, ...) -> list[str]``

Chat-template formatting is no longer applied client-side: ``vllm serve``
applies the model's chat template server-side from the structured
``messages`` payload, so this module passes
``[{"role": "user", "content": prompt}]`` directly.

Dry-run mode (``config.dry_run=True`` AND ``engine is None``): a
:class:`methods._openai_engine.DryRunEngine` is instantiated internally so
``predict`` can be exercised without a live vLLM endpoint (the path the
``test_method_contract`` and sanity-matrix smoke tests use).

Prompt templates and response parsers are lifted **verbatim** from
``baselines/llm_baseline.py`` (the legacy code path); the only changes
are removing benchmark IO, canonical-index joins, and result packaging
(those concerns moved to ``dataloader/`` and ``eval.py``).
"""

from __future__ import annotations

import json
import logging
import re
from typing import Any, ClassVar

import numpy as np
import pandas as pd

logger = logging.getLogger(__name__)

from ._config import (
    Gemma4Config,
    LlamaScoutConfig,
    LLMConfig,
    Qwen35Config,
)
from ._openai_engine import DryRunEngine
from ._registry import register
from .base import Method, _HFSaveMixin


# ── Task-set covered by every LLM in this file ──────────────────────────

_LLM_TASKS = frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"})


# ── Lifted-verbatim helpers from baselines/llm_baseline.py ──────────────

_THINK_RE = re.compile(r"<think>.*?</think>", re.DOTALL)

_NUM_PATTERNS = [
    # Keyword-prefixed: "Prediction: $1.23 billion"
    r"\*?\*?(?:final\s+answer|final\s+prediction|prediction|forecast|estimate|"
    r"answer|price|value|market\s+cap(?:italization)?|return|equity|valuation)"
    r"[:\s]*\$?\s*([-\d,]+(?:\.\d+)?(?:[eE][-+]?\d+)?)\s*"
    r"(billion|million|thousand|trillion)?",
    # Number with magnitude suffix (spelled-out only — 'B'/'M' alone are too ambiguous):
    r"\$?\s*([-\d,]+(?:\.\d+)?(?:[eE][-+]?\d+)?)\s+(billion|million|thousand|trillion)\b",
    # Fallback: any plain number with optional $.
    r"\$?([-\d,]+(?:\.\d+)?(?:[eE][-+]?\d+)?)",
]

_MAGNITUDE_MAP = {
    "thousand": 1e3,
    "million":  1e6,
    "billion":  1e9,
    "trillion": 1e12,
}


def _strip_thinking(response: str) -> str:
    """Remove ``<think>...</think>`` reasoning blocks from a response.

    Preserves the legacy behaviour: also handles unclosed ``<think>``
    fragments by taking the trailing portion.
    """
    response = _THINK_RE.sub("", response).strip()
    m = re.search(r"<think>(.*)", response, flags=re.DOTALL)
    if m and "</think>" not in response:
        response = m.group(1).strip()
    return response


def _extract_json_object(response: str) -> dict | None:
    """Extract a structured ``{field: value}`` map from an LLM response.

    Two paths:

    1. **JSON object**: legacy support for replies like
       ``{"Revenues": 1000000, "Assets": 5000000}``. Slices from the first
       ``{`` to the last ``}`` and tries ``json.loads``.
    2. **Plain-text key/value**: line-oriented format ``<Field>: <number>``
       which is what current prompts request. Each line is matched by
       regex; numbers may use ``$``, commas, scientific notation. This is
       the natural LLM output mode and avoids JSON parse failures.

    Returns ``None`` if neither path yields any field/value pair.
    """
    if not response:
        return None
    # Path 1: legacy JSON object.
    start = response.find("{")
    end = response.rfind("}")
    if start >= 0 and end > start:
        try:
            j = json.loads(response[start:end + 1])
            if isinstance(j, dict):
                return j
        except json.JSONDecodeError:
            pass
        depth = 0
        for i in range(start, len(response)):
            ch = response[i]
            if ch == "{":
                depth += 1
            elif ch == "}":
                depth -= 1
                if depth == 0:
                    try:
                        j = json.loads(response[start:i + 1])
                        if isinstance(j, dict):
                            return j
                    except json.JSONDecodeError:
                        break
    # Path 2: plain-text "<Field>: <number>" lines (one or many).
    out: dict[str, float] = {}
    line_re = re.compile(
        r"\*?\*?\s*([A-Za-z][A-Za-z0-9_]*)\s*:\s*\$?\s*"
        r"(-?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?)"
    )
    for m in line_re.finditer(response):
        field = m.group(1)
        num_str = m.group(2).replace(",", "")
        try:
            out[field] = float(num_str)
        except ValueError:
            continue
    return out or None


def _parse_number(text: str) -> float | None:
    """Extract the first plausible number from an LLM response.

    Strips ``<think>...</think>`` blocks, list-numbered prefixes
    (``1. ``, ``2. ``), and CoT step markers before number extraction.
    Honors magnitude suffixes (B / billion, M / million, K / thousand,
    T / trillion). Returns ``None`` only when no number is found.
    """
    if not text:
        return None
    # Strip CoT thinking blocks first
    text = _strip_thinking(text)
    # Drop "Thinking Process:" / "Reasoning:" / "Step N:" prefix sections by
    # taking the trailing portion after a "Final answer" / "Therefore" cue.
    for cue in ["Final answer:", "Final Answer:", "FINAL ANSWER:",
                "Therefore,", "So, ", "Answer:", "answer:"]:
        idx = text.rfind(cue)
        if idx >= 0:
            text = text[idx + len(cue):]
            break
    # Strip list-numbered prefixes like "1. " at start of lines so the
    # parser doesn't pick up step indices instead of values.
    text = re.sub(r"(?m)^\s*\d+\.\s+", "", text)
    for pat in _NUM_PATTERNS:
        match = re.search(pat, text, re.IGNORECASE)
        if match:
            num_str = match.group(1).replace(",", "")
            mag_str = (
                match.group(2) if match.lastindex and match.lastindex >= 2
                else None
            )
            try:
                v = float(num_str)
            except ValueError:
                continue
            if mag_str:
                v *= _MAGNITUDE_MAP.get(mag_str.lower(), 1.0)
            return v
    return None


def _parse_horizon_list(response: str, horizon: int) -> np.ndarray | None:
    """Extract a list of floats representing a forecast trajectory.

    Strategy: try a bracketed JSON-array slice first; otherwise extract
    every numeric token from the whole response. Plain-text replies like
    ``"123.45, 124.10, 125.00, ..."`` or ``"123.45\\n124.10\\n..."`` parse
    just as well as JSON.

    Returns a ``(horizon,)`` float32 ndarray, padding with the last value
    when the parsed list is shorter and truncating when longer. Returns
    ``None`` only when zero numeric tokens are found.
    """
    if not response:
        return None
    # Strip CoT thinking blocks (this is a known issue for chain-of-thought
    # models; the safe pattern.) Do NOT strip "N. " line prefixes — that
    # regex was too aggressive and dropped real digits in some outputs.
    response = _strip_thinking(response)
    # Prefer a bracketed slice if present (still works for legacy JSON output).
    start = response.find("[")
    end = response.rfind("]")
    candidate = response[start : end + 1] if start >= 0 and end > start else response
    parsed: list[Any] | None = None
    if start >= 0 and end > start:
        try:
            j = json.loads(candidate)
            if isinstance(j, list):
                parsed = j
        except json.JSONDecodeError:
            parsed = None
    if parsed is None:
        # Plain-text fallback: extract every signed/decimal/scientific number.
        tokens = re.findall(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", candidate)
        if not tokens:
            return None
        try:
            parsed = [float(t) for t in tokens]
        except ValueError:
            return None
    vals: list[float] = []
    for v in parsed:
        try:
            f = float(v)
        except (TypeError, ValueError):
            continue
        if not (f != f):  # not NaN
            vals.append(f)
    if not vals:
        return None
    if len(vals) >= horizon:
        out = np.asarray(vals[:horizon], dtype=np.float32)
    else:
        pad = [vals[-1]] * (horizon - len(vals))
        out = np.asarray(vals + pad, dtype=np.float32)
    return out


def _safe_float(v: Any, default: float = 0.0) -> float:
    """Coerce ``v`` to float; fall back to ``default`` on missing / non-numeric."""
    if v is None:
        return default
    if isinstance(v, (int, float)) and not (isinstance(v, float) and np.isnan(v)):
        return float(v)
    try:
        if pd.isna(v):  # type: ignore[arg-type]
            return default
    except (TypeError, ValueError):
        pass
    try:
        return float(v)
    except (TypeError, ValueError):
        return default


def _format_macro_snapshot(row: pd.Series) -> str:
    """Render the at-anchor macro snapshot for T2/T5 prompts.

    Picks four widely-recognised series whose level is itself meaningful
    (rates / vol / index level) so the LLM does not need to derive a YoY
    change from a single observation. Lines are silently dropped when a
    column is missing or NaN, so the prompt stays compact when the macro
    join failed.
    """
    items: list[str] = []
    series = {
        "10-Year Treasury Yield (DGS10, %)": row.get("fred_DGS10"),
        "Fed Funds Rate (FEDFUNDS, %)": row.get("fred_FEDFUNDS"),
        "VIX (VIXCLS, equity vol)": row.get("fred_VIXCLS"),
        "CPI Headline Level (CPIAUCSL)": row.get("fred_CPIAUCSL"),
    }
    for label, val in series.items():
        if val is None:
            continue
        try:
            if pd.isna(val):
                continue
            items.append(f"{label}: {float(val):,.2f}")
        except (TypeError, ValueError):
            continue
    if not items:
        return "Macro snapshot: not available."
    return "Macro snapshot at anchor date:\n" + "\n".join(items)


def _find_close_idx_from_array(X: np.ndarray) -> int:
    """Heuristic close-column finder when feature_names are unavailable.

    Matches ``methods.llm.FrontierLLM`` from the legacy file: pick a
    feature column whose values are all-positive across observed
    timesteps and whose median magnitude is in the price-shaped range
    [1, 5000]; tie-break by closeness to the median magnitude in
    log-space. Falls back to column 0.
    """
    if X.ndim != 3 or X.shape[2] == 0:
        return 0
    samples = X.reshape(-1, X.shape[2])
    pos_mask = (samples >= 0).all(axis=0)
    if not pos_mask.any():
        return 0
    medians = np.median(np.abs(samples), axis=0)
    candidates = np.where(pos_mask & (medians >= 1.0) & (medians <= 5000.0))[0]
    if len(candidates) == 0:
        return 0
    cand_meds = medians[candidates]
    log_cand = np.log10(cand_meds + 1e-9)
    target = np.median(log_cand)
    return int(candidates[np.argmin(np.abs(log_cand - target))])


# ── Default XBRL field panel for T3/T6 when y_train is unavailable ──────

_DEFAULT_T3_T6_FIELDS = (
    # MUST match dataloader.load._T3_DENSE_FIELDS exactly (the eval-side
    # canonical field set). Field-name drift between predict-side prompts
    # and eval-side joins produces silent 0% match rates.
    "Revenues",
    "NetIncomeLoss",
    "Assets",
    "Liabilities",
    "StockholdersEquity",
    "OperatingIncomeLoss",
    "CashAndCashEquivalentsAtCarryingValue",
    "PropertyPlantAndEquipmentNet",
    "LongTermDebt",
    "ResearchAndDevelopmentExpense",
    "NetCashProvidedByUsedInOperatingActivities",
)

# LLMs frequently emit common-English variants of XBRL canonical names;
# accept these aliases at parse time so predictions are usable instead of
# being forced to predict_failed on every field-name drift.
_T3_T6_FIELD_ALIASES: dict[str, list[str]] = {
    "Revenues":                                    ["revenues","revenue","totalrevenue","totalrevenues","sales","totalsales","netrevenue","netrevenues","stmt_revenue"],
    "NetIncomeLoss":                               ["netincomeloss","netincome","netearnings","netprofit","income","earnings","stmt_net_income"],
    "Assets":                                      ["assets","totalassets","stmt_total_assets"],
    "Liabilities":                                 ["liabilities","totalliabilities","stmt_total_liabilities"],
    "StockholdersEquity":                          ["stockholdersequity","totalstockholdersequity","shareholdersequity","totalshareholdersequity","totalequity","equity","stmt_total_equity","bookvalue"],
    "OperatingIncomeLoss":                         ["operatingincomeloss","operatingincome","operatingprofit","operatingearnings","ebit","stmt_operating_income"],
    "CashAndCashEquivalentsAtCarryingValue":       ["cashandcashequivalentsatcarryingvalue","cashandcashequivalents","cashequivalents","cash","stmt_cash","cashandshortterminvestments"],
    "PropertyPlantAndEquipmentNet":                ["propertyplantandequipmentnet","propertyplantandequipment","ppe","netppe","ppenet","fixedassets","stmt_ppe_net"],
    "LongTermDebt":                                ["longtermdebt","longtermborrowings","noncurrentdebt","longtermliabilities","stmt_lt_debt"],
    "ResearchAndDevelopmentExpense":               ["researchanddevelopmentexpense","researchanddevelopment","rd","rnd","rdexpense","rndexpense"],
    "NetCashProvidedByUsedInOperatingActivities":  ["netcashprovidedbyusedinoperatingactivities","operatingcashflow","cashfromoperations","operatingcash","netcashoperating","stmt_operating_cashflow"],
}


def _resolve_canonical_field(parsed: dict | None, canon_field: str) -> Any:
    """Resolve ``canon_field`` from a parsed LLM dict using a canonical-name
    alias map. Lookup is case- and underscore-insensitive. Returns ``None``
    when ``parsed`` is None or no alias matches.
    """
    if parsed is None:
        return None
    aliases = _T3_T6_FIELD_ALIASES.get(canon_field, [canon_field.lower()])
    norm = {
        str(k).lower().replace(" ", "").replace("_", ""): v
        for k, v in parsed.items()
    }
    for alias in [canon_field.lower(), *aliases]:
        key = alias.replace(" ", "").replace("_", "")
        if key in norm:
            return norm[key]
    return None




# ── Shared base class ───────────────────────────────────────────────────


class _LLMBase(_HFSaveMixin, Method):
    """Shared scaffolding for the four frontier-LLM methods.

    Subclasses set ``name``, ``family``, ``tasks``, and ``_config_class``
    via the ``@register`` decorator. The engine — an
    :class:`methods._openai_engine.OpenAIChatEngine` exposing
    ``chat_complete`` / ``chat_complete_batch`` — is **injected** by the
    runner via the ``engine=`` ctor kwarg.

    When ``engine is None`` AND ``config.dry_run=True``, a
    :class:`methods._openai_engine.DryRunEngine` is instantiated lazily on
    first ``predict`` so smoke tests can run without a live HTTP endpoint.

    Chat-template formatting is delegated to the vLLM server (it sees
    structured ``messages`` and applies the model's tokenizer chat
    template before generation), so this class no longer needs a
    tokenizer kwarg or a client-side ``apply_chat_template`` step.
    """

    family: ClassVar[str] = "llm"
    tasks: ClassVar[frozenset[str]] = _LLM_TASKS
    schema_version: ClassVar[int] = 1

    _config_class: ClassVar[type[LLMConfig]] = LLMConfig

    def __init__(
        self,
        *,
        task: str,
        config: LLMConfig | None = None,
        engine: Any = None,
        **kwargs: Any,
    ) -> None:
        if task not in self.tasks:
            raise ValueError(
                f"{type(self).__name__} does not support task {task!r}; "
                f"supported: {sorted(self.tasks)}"
            )
        self.task: str = task
        self.config: LLMConfig = config or self._config_class(**kwargs)

        # Runner-managed shared resource. One OpenAIChatEngine per HF
        # model id; many method instances share it.
        self.engine: Any = engine

        # Populated by ``fit``: in-context examples (when in_context_k>0)
        # and the long-form fitted-fields set for T3/T6 (per plan §7b.1).
        self._y_train: Any = None
        self._X_train: Any = None
        self._fitted_fields_per_ticker: dict[str, list[str]] = {}
        self._fitted_fields_global: list[str] = []

        # Populated after each predict call.
        self.last_predict_meta: dict[str, Any] = {}

        # Resolved at fit time when the runner provides feature_names via
        # ``set_feature_names``; T1 falls back to the magnitude heuristic.
        self._t1_close_idx: int | None = None
        self._t1_horizon: int | None = None

    # ── default_config plumbed by @register if absent ─────────────────

    @classmethod
    def default_config(cls) -> LLMConfig:
        return cls._config_class()

    # ── Optional setter mirroring the TSFM pattern ────────────────────

    def set_feature_names(self, feature_names: list[str]) -> None:
        """T1 close-column resolver. Optional; runner may or may not call."""
        if "close" in feature_names:
            self._t1_close_idx = feature_names.index("close")
        else:
            self._t1_close_idx = None  # fall back to heuristic at predict time

    # ── fit: zero-shot, but record the fitted field set for T3/T6 ────

    def fit(self, X: Any, y: Any, *, seed: int = 42) -> "_LLMBase":
        """Zero-shot fit.

        For T3/T6 we record the unique field set per ticker (and global)
        from ``y`` so ``predict`` emits one row per ``(ticker, fiscal_year,
        field)`` for every fitted field — matching the plan's per-task
        long-form contract.

        For T1 we capture the horizon from ``y.shape[1]`` so the prompt
        wording and the output tile width are consistent.

        For ``config.in_context_k > 0`` we additionally retain ``X`` and
        ``y`` so ``predict`` can build in-context examples (currently a
        thin handle; the IC builder is task-specific and can be added
        without breaking the API).
        """
        if self.config.in_context_k > 0:
            self._X_train = X
            self._y_train = y

        if self.task == "T1":
            if isinstance(y, np.ndarray) and y.ndim == 2:
                self._t1_horizon = int(y.shape[1])

        if self.task in ("T3", "T6"):
            if isinstance(y, pd.DataFrame) and not y.empty and "field" in y.columns:
                # Per-ticker fitted fields
                self._fitted_fields_per_ticker = {
                    str(t): sorted(grp["field"].astype(str).unique().tolist())
                    for t, grp in y.groupby("ticker", sort=False)
                }
                # Global fitted-field set (used as fallback when a test
                # ticker is unseen in training)
                self._fitted_fields_global = sorted(
                    y["field"].astype(str).unique().tolist()
                )

        return self

    # ── predict: dispatch on self.task ───────────────────────────────

    def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
        """Emit predictions for ``X``. Shape is per the plan §9 matrix."""
        # Engine-availability check: dry_run lets the smoke test pass
        # without a real vLLM engine.
        if self.engine is None and not self.config.dry_run:
            raise RuntimeError(
                f"{type(self).__name__}.predict: no engine was injected and "
                f"config.dry_run=False; the runner must inject a vLLM engine "
                f"(or set dry_run=True for CI smoke tests)."
            )

        if self.task == "T1":
            return self._predict_t1(X)
        if self.task in ("T2", "T5"):
            return self._predict_t2_t5(X, task=self.task)
        if self.task in ("T3", "T6"):
            return self._predict_t3_t6(X, task=self.task)
        if self.task == "T4":
            return self._predict_t4(X)
        if self.task == "T7":
            return self._predict_t7(X)
        raise ValueError(f"Unknown task: {self.task!r}")  # pragma: no cover

    # ── HF save/load hooks (manifest only — model weights live in HF cache) ─

    def _hf_save(self, path: Any) -> None:  # noqa: ARG002 -- manifest-only
        """No-op: frontier model weights are too large; the HF cache is
        the SSOT. ``manifest.json`` written by the mixin records the
        ``model_id`` so ``load`` can re-use the same shared engine.
        """
        return None

    def _hf_load(self, path: Any) -> None:  # noqa: ARG002 -- manifest-only
        """No-op counterpart to :meth:`_hf_save`. The runner is
        responsible for re-injecting the engine after construction.
        """
        return None

    # ── Engine call (OpenAI-compatible HTTP, batched via thread-pool) ─

    def _ensure_engine(self) -> Any:
        """Return the injected engine, instantiating a DryRunEngine when
        ``engine is None`` and ``config.dry_run=True``.
        """
        if self.engine is not None:
            return self.engine
        if self.config.dry_run:
            self.engine = DryRunEngine(horizon=int(self._t1_horizon or 21))
            return self.engine
        raise RuntimeError(
            f"{type(self).__name__}.predict: no engine was injected and "
            f"config.dry_run=False; the runner must inject an "
            f"OpenAIChatEngine (or set dry_run=True for CI smoke tests)."
        )

    def _call_batch(
        self,
        prompts: list[str],
        *,
        max_tokens: int | None = None,
    ) -> list[str]:
        """Batched LLM inference via the injected OpenAI-compatible engine.

        Each prompt becomes a one-message ``[{"role": "user", ...}]``
        payload. ``vllm serve`` applies the model's chat template
        server-side, so no client-side tokenizer is needed.
        """
        if not prompts:
            return []
        engine = self._ensure_engine()
        # Qwen3.5 has thinking enabled by default in the chat template;
        # the upstream Qwen team document /no_think as the in-prompt switch
        # to disable it for direct-answer generation. Honor LLMConfig.enable_thinking=False.
        prefix = ""
        if not bool(getattr(self.config, "enable_thinking", False)):
            mid = str(getattr(self.config, "model_id", "") or "")
            if "Qwen3" in mid or "qwen3" in mid:
                prefix = "/no_think\n"
        batched_messages = [
            [{"role": "user", "content": prefix + p}] for p in prompts
        ]
        responses = engine.chat_complete_batch(
            batched_messages,
            max_tokens=int(max_tokens or self.config.max_tokens),
            temperature=float(self.config.temperature),
            top_p=1.0,
        )
        return [_strip_thinking(str(r)) for r in responses]

    # ── T1: TSF (true horizon-list trajectory forecast) ────────────────

    def _predict_t1(self, X: np.ndarray) -> np.ndarray:
        if not isinstance(X, np.ndarray) or X.ndim != 3:
            raise ValueError(
                f"T1 X must be (N, lookback, F) np.ndarray, got "
                f"shape={getattr(X, 'shape', None)} type={type(X).__name__}"
            )
        n, lookback, _ = X.shape
        horizon = int(self._t1_horizon or 21)

        if n == 0:
            self.last_predict_meta = {
                "task": "T1", "n_attempted": 0, "n_parse_errors": 0,
            }
            return np.zeros((0, horizon), dtype=np.float32)

        close_idx = (
            self._t1_close_idx
            if self._t1_close_idx is not None
            else _find_close_idx_from_array(X)
        )

        prompts: list[str] = []
        for i in range(n):
            close_series = X[i, :, close_idx]
            last_close = float(close_series[-1])
            mean_close = float(np.mean(close_series))
            std_close = float(np.std(close_series))
            denom = max(float(close_series[0]), 0.01)
            trend = float((close_series[-1] - close_series[0]) / denom * 100)
            prompts.append(
                f"You are a quantitative analyst. Predict the daily closing "
                f"prices of the stock for each of the next {horizon} trading "
                f"days, given:\n"
                f"- Current close: ${last_close:.2f}\n"
                f"- Past {lookback} closes: "
                f"mean=${mean_close:.2f}, std=${std_close:.2f}, "
                f"trend={trend:+.1f}%\n\n"
                f"Reply with {horizon} closing prices in chronological order, "
                f"one per line, dollars only (no $ sign, no commentary)."
            )

        # Trajectory output requires more tokens than a single scalar: budget
        # ~8 tokens per horizon step plus brackets/separators.
        max_tokens = max(64, 12 * horizon + 16)
        responses = self._call_batch(prompts, max_tokens=max_tokens)

        preds = np.full((n, horizon), np.nan, dtype=np.float32)
        unparsed_idx: list[int] = []
        for i, resp in enumerate(responses):
            traj = _parse_horizon_list(resp, horizon)
            if traj is None:
                unparsed_idx.append(i)
                continue
            preds[i, :] = traj

        # Re-prompt unparseable rows ONCE with stricter format guidance.
        if unparsed_idx:
            retry_prompts = [
                prompts[i]
                + f"\n\nIMPORTANT: Reply with EXACTLY {horizon} numbers "
                  "separated by commas or newlines, no other text."
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=max_tokens)
            still_unparsed = []
            for k, i in enumerate(unparsed_idx):
                traj = _parse_horizon_list(retries[k], horizon)
                if traj is None:
                    still_unparsed.append(i)
                else:
                    preds[i, :] = traj
            unparsed_idx = still_unparsed

        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        self.last_predict_meta = {
            "task": "T1", "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
            "horizon": horizon, "close_idx": int(close_idx),
        }
        return preds

    # ── T2 / T5: scalar valuation ────────────────────────────────────

    def _predict_t2_t5(self, X: pd.DataFrame, *, task: str) -> np.ndarray:
        if not isinstance(X, pd.DataFrame):
            raise ValueError(
                f"{task} X must be a DataFrame, got type={type(X).__name__}"
            )
        n = len(X)
        if n == 0:
            self.last_predict_meta = {
                "task": task, "n_attempted": 0, "n_parse_errors": 0,
            }
            return np.zeros(0, dtype=np.float64)

        prompts: list[str] = []
        if task == "T2":
            for _, row in X.iterrows():
                sector = row.get("sector", "Unknown")
                revenue = row.get("stmt_revenue", 0)
                net_income = row.get("stmt_net_income", 0)
                total_assets = row.get("stmt_total_assets", 0)
                employees = row.get("fullTimeEmployees", "N/A")
                macro_str = _format_macro_snapshot(row)
                # NB: derived_pe stripped at build time to avoid the
                # market-cap-leakage path (T2/T5 leakage fix).
                prompts.append(
                    f"You are a financial analyst. Estimate the total equity "
                    f"market capitalization of this company.\n\n"
                    f"Sector: {sector}\n"
                    f"Revenue: ${_safe_float(revenue):,.0f}\n"
                    f"Net Income: ${_safe_float(net_income):,.0f}\n"
                    f"Total Assets: ${_safe_float(total_assets):,.0f}\n"
                    f"Employees: {employees}\n"
                    f"{macro_str}\n\n"
                    f"Reply with ONLY a single number: the estimated market cap "
                    f"in dollars."
                )
        else:  # T5 — Val-Priv
            stmt_cols = [c for c in X.columns if c.startswith("stmt_")]
            for _, row in X.iterrows():
                sector = row.get("sector", "Unknown")
                industry = row.get("industry", "Unknown")
                stmt_items = []
                for c in stmt_cols:
                    val = row.get(c)
                    if pd.notna(val):
                        try:
                            stmt_items.append(f"{c}: ${float(val):,.0f}")
                        except (TypeError, ValueError):
                            continue
                stmt_str = (
                    "\n".join(stmt_items) if stmt_items
                    else "No financial statement data available"
                )
                macro_str = _format_macro_snapshot(row)
                prompts.append(
                    f"You are a private equity analyst. Given ONLY financial "
                    f"statement data (no market price), estimate the market "
                    f"capitalization of this company.\n\n"
                    f"Sector: {sector}\n"
                    f"Industry: {industry}\n"
                    f"{stmt_str}\n"
                    f"{macro_str}\n\n"
                    f"Reply with ONLY a single number: the estimated market cap "
                    f"in dollars."
                )

        responses = self._call_batch(prompts, max_tokens=64)
        preds = np.full(n, np.nan, dtype=np.float64)
        unparsed_idx: list[int] = []
        for i, resp in enumerate(responses):
            v = _parse_number(resp)
            if v is None or v <= 0:
                unparsed_idx.append(i)
                continue
            preds[i] = float(v)
        # Retry once with stricter format guidance.
        if unparsed_idx:
            retry_prompts = [
                prompts[i] + "\n\nIMPORTANT: Reply with ONLY a single positive "
                "number (no units, no commas, no currency symbol, no other text)."
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=64)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                v = _parse_number(retries[k])
                if v is None or v <= 0:
                    still.append(i)
                else:
                    preds[i] = float(v)
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        self.last_predict_meta = {
            "task": task, "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
        }
        return preds

    # ── T3 / T6: per-(ticker, fiscal_year) XBRL field generation ────

    def _predict_t3_t6(self, X: pd.DataFrame, *, task: str) -> pd.DataFrame:
        if not isinstance(X, pd.DataFrame):
            raise ValueError(
                f"{task} X must be a DataFrame, got type={type(X).__name__}"
            )
        n = len(X)
        if n == 0:
            self.last_predict_meta = {
                "task": task, "n_attempted": 0, "n_parse_errors": 0,
            }
            return pd.DataFrame(
                columns=["ticker", "fiscal_year", "field", "pred"]
            )

        # Field set: per-ticker if fitted, else global, else default panel.
        global_fields = (
            self._fitted_fields_global
            or list(_DEFAULT_T3_T6_FIELDS)
        )

        prompts: list[str] = []
        meta_rows: list[tuple[str, Any, list[str]]] = []
        for _, row in X.iterrows():
            ticker = str(row.get("ticker", "?"))
            fy = row.get("fiscal_year", None)
            fields_for_row = (
                self._fitted_fields_per_ticker.get(ticker)
                or global_fields
            )
            fields_str = ", ".join(fields_for_row)
            example_key = fields_for_row[0] if fields_for_row else "Revenues"
            meta_rows.append((ticker, fy, fields_for_row))

            if task == "T3":
                sector = row.get("sector", "Unknown")
                revenue = _safe_float(row.get("stmt_revenue", 0))
                net_income = _safe_float(row.get("stmt_net_income", 0))
                total_assets = _safe_float(row.get("stmt_total_assets", 0))
                total_equity = _safe_float(row.get("stmt_total_equity", 0))
                prompts.append(
                    f"You are a financial analyst. Given company fundamentals, "
                    f"predict each of the following financial statement fields.\n\n"
                    f"Company: {ticker} ({sector})\n"
                    f"Revenue: ${revenue:,.0f}\n"
                    f"Net Income: ${net_income:,.0f}\n"
                    f"Total Assets: ${total_assets:,.0f}\n"
                    f"Total Equity: ${total_equity:,.0f}\n\n"
                    f"Reply with one line per field, format `<FieldName>: <number>`. "
                    f"Use the EXACT field names below (case and spelling must "
                    f"match):\n{fields_str}\n\n"
                    f"Example:\n"
                    f"{example_key}: 1000000\n..."
                )
            else:  # T6 — Gen-Eval (NL company description, no stmt_*)
                description = row.get(
                    "company_description", f"A company with ticker {ticker}",
                )
                sector = row.get("sector", "Unknown")
                industry = row.get("industry", "Unknown")
                prompts.append(
                    f"You are a financial analyst. Given this company description: "
                    f"'{description}', sector: '{sector}', industry: '{industry}', "
                    f"generate plausible values for the following financial fields. "
                    f"Use the EXACT field names below (case and spelling must "
                    f"match): {fields_str}.\n\n"
                    f"Reply with one line per field, format `<FieldName>: <number>`. "
                    f"Example:\n"
                    f"{example_key}: 1000000\n..."
                )

        responses = self._call_batch(prompts, max_tokens=1024)
        parsed_per_row = [_extract_json_object(r) for r in responses]
        unparsed_idx = [i for i, p in enumerate(parsed_per_row) if p is None]
        if unparsed_idx:
            retry_prompts = [
                prompts[i]
                + "\n\nIMPORTANT: Reply with EXACTLY one line per field, "
                  "format `<FieldName>: <number>`. No extra commentary."
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=1024)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                p = _extract_json_object(retries[k])
                if p is None:
                    still.append(i)
                else:
                    parsed_per_row[i] = p
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        rows: list[dict[str, Any]] = []
        n_valid = 0
        for (ticker, fy, fields_for_row), parsed in zip(meta_rows, parsed_per_row):
            for field in fields_for_row:
                # Use the alias-aware canonical-field resolver so common
                # LLM variants (Revenue, NetIncome, TotalAssets, ...)
                # match the canonical XBRL names in y_true.
                v = _resolve_canonical_field(parsed, str(field))
                try:
                    pred_val = float(v) if v is not None else np.nan
                except (TypeError, ValueError):
                    pred_val = np.nan
                if not np.isnan(pred_val):
                    n_valid += 1
                rows.append({
                    "ticker": ticker,
                    "fiscal_year": fy,
                    "field": str(field),
                    "pred": pred_val,
                })

        # 100% unparseable — log + emit NaN frame; eval-side fillna(0)
        # substitutes the missing field-tuple values, contributing APE=100%
        # per missed field. The cell remains MEASURABLE.
        if n_valid == 0:
            logger.warning(
                "%s %s predict: 0/%d (canonical_field, value) cells "
                "extracted; emitting NaN frame — eval will substitute 0.",
                type(self).__name__, task, len(rows),
            )

        self.last_predict_meta = {
            "task": task, "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
            "n_valid_field_cells": int(n_valid),
        }
        return pd.DataFrame(rows, columns=["ticker", "fiscal_year", "field", "pred"])

    # ── T4: scenario-conditioned return ──────────────────────────────

    def _predict_t4(self, X: Any) -> np.ndarray:
        """Per the canonical T4 loader, ``X`` is a DataFrame with columns
        ``lookback`` (object), ``event_type``, ``event_description``.
        For backward compatibility with the legacy dict layout we accept
        a dict too.
        """
        if isinstance(X, pd.DataFrame):
            if "event_type" not in X.columns:
                raise ValueError("T4 X DataFrame missing 'event_type' column")
            event_type = X["event_type"].astype(str).to_numpy()
            event_desc = (
                X["event_description"].astype(str).to_numpy()
                if "event_description" in X.columns
                else np.array([""] * len(X))
            )
        elif isinstance(X, dict):
            event_type = np.asarray(X.get("event_type", []))
            event_desc = np.asarray(X.get("event_description", []))
        else:
            raise ValueError(
                f"T4 X must be a DataFrame or dict, got type={type(X).__name__}"
            )

        n = int(len(event_type))
        if n == 0:
            self.last_predict_meta = {
                "task": "T4", "n_attempted": 0, "n_parse_errors": 0,
            }
            return np.zeros(0, dtype=np.float32)
        if len(event_desc) != n:
            raise ValueError(
                f"T4 X: event_type ({len(event_type)}) and event_description "
                f"({len(event_desc)}) length mismatch."
            )

        prompts: list[str] = []
        for et, ed in zip(event_type, event_desc):
            et_s = str(et) if et is not None else "unknown"
            ed_s = str(ed)[:200] if ed is not None else ""
            prompts.append(
                f"You are a quantitative analyst. Predict the percentage return "
                f"for the stock over the next 21 trading days following this "
                f"macroeconomic event.\n\n"
                f"Event type: {et_s}\n"
                f"Description: {ed_s}\n\n"
                f"Reply with ONLY a single number: the predicted return as a "
                f"percentage (e.g., 2.5 for +2.5% or -1.3 for -1.3%)."
            )

        responses = self._call_batch(prompts, max_tokens=64)
        preds = np.full(n, np.nan, dtype=np.float32)
        unparsed_idx: list[int] = []
        for i, resp in enumerate(responses):
            v = _parse_number(resp)
            if v is None:
                unparsed_idx.append(i)
                continue
            preds[i] = float(v)
        if unparsed_idx:
            retry_prompts = [
                prompts[i] + "\n\nIMPORTANT: Reply with ONLY a single signed "
                "number (e.g. 2.5 or -1.3). No units, no percent sign, no text."
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=64)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                v = _parse_number(retries[k])
                if v is None:
                    still.append(i)
                else:
                    preds[i] = float(v)
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        self.last_predict_meta = {
            "task": "T4", "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
        }
        return preds

    # ── T7: real-estate per-property rent / price ────────────────────

    def _predict_t7(self, X: pd.DataFrame) -> pd.DataFrame:
        if not isinstance(X, pd.DataFrame):
            raise ValueError(
                f"T7 X must be a DataFrame, got type={type(X).__name__}"
            )
        n = len(X)
        if n == 0:
            self.last_predict_meta = {
                "task": "T7", "n_attempted": 0, "n_parse_errors": 0,
            }
            return pd.DataFrame(columns=["address", "pred_rent", "pred_price"])

        prompts: list[str] = []
        addrs: list[Any] = []
        for _, row in X.iterrows():
            addrs.append(row.get("address", None))
            city = row.get("city", "Unknown")
            state = row.get("state", "Unknown")
            property_type = row.get("property_type", "Unknown")
            sqft = row.get("sqft", "N/A")
            beds = row.get("bedrooms", row.get("beds", "N/A"))
            baths = row.get("bathrooms", row.get("baths", "N/A"))
            year_built = row.get("year_built", "N/A")
            last_sale_date = row.get("last_sale_date", None)
            years_since_last_sale = row.get("years_since_last_sale", None)
            sale_block = ""
            if pd.notna(last_sale_date) and pd.notna(years_since_last_sale):
                try:
                    lsd = pd.to_datetime(last_sale_date).strftime("%Y-%m-%d")
                    sale_block = (
                        f"Last sale: {lsd} "
                        f"({float(years_since_last_sale):.1f} years before today). "
                    )
                except Exception:
                    sale_block = ""

            prompts.append(
                f"You are a real estate appraiser estimating value AS OF "
                f"2026-04-11. Given this property: location={city}, {state}, "
                f"type={property_type}, sqft={sqft}, beds={beds}, baths={baths}, "
                f"year_built={year_built}. {sale_block}"
                f"Estimate the monthly rent and sale price.\n\n"
                f"Reply on two lines, dollars only (no $ sign, no commentary):\n"
                f"Rent: <monthly_rent_dollars>\n"
                f"Price: <sale_price_dollars>"
            )

        responses = self._call_batch(prompts, max_tokens=128)
        parsed_per_row = [_extract_json_object(r) for r in responses]
        unparsed_idx = [i for i, p in enumerate(parsed_per_row) if p is None]
        if unparsed_idx:
            retry_prompts = [
                prompts[i] + "\n\nIMPORTANT: Reply on EXACTLY two lines, "
                "no units / no $ / no commentary:\nRent: <number>\n"
                "Price: <number>"
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=128)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                p = _extract_json_object(retries[k])
                if p is None:
                    still.append(i)
                else:
                    parsed_per_row[i] = p
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        rows: list[dict[str, Any]] = []
        n_valid_rent = 0
        n_valid_price = 0
        for addr, parsed in zip(addrs, parsed_per_row):
            if parsed is None:
                rows.append({"address": addr, "pred_rent": np.nan,
                             "pred_price": np.nan})
                continue
            ci = {str(k).lower(): v for k, v in parsed.items()}
            try:
                rent_val = float(ci.get("rent", np.nan))
            except (TypeError, ValueError):
                rent_val = np.nan
            try:
                price_val = float(ci.get("price", np.nan))
            except (TypeError, ValueError):
                price_val = np.nan
            if not np.isnan(rent_val):
                n_valid_rent += 1
            if not np.isnan(price_val):
                n_valid_price += 1
            rows.append({
                "address": addr,
                "pred_rent": rent_val,
                "pred_price": price_val,
            })

        # 100% rent+price unparseable — log + emit NaN frame; eval-side
        # fillna(0) substitutes both, APE=100% per row. Cell stays measurable.
        if n_valid_rent == 0 and n_valid_price == 0:
            logger.warning(
                "%s T7 predict: 0/%d rows yielded rent or price — "
                "emitting NaN frame; eval will substitute 0.",
                type(self).__name__, n,
            )

        self.last_predict_meta = {
            "task": "T7", "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
            "n_valid_rent": int(n_valid_rent),
            "n_valid_price": int(n_valid_price),
        }
        return pd.DataFrame(rows, columns=["address", "pred_rent", "pred_price"])


# ── Concrete classes (one per HF model id) ──────────────────────────────


@register(
    name="llama_scout",
    family="llm",
    tasks=_LLM_TASKS,
    config_class=LlamaScoutConfig,
)
class LlamaScout(_LLMBase):
    """Llama-4 Scout 109B MoE (FP8), TP=4. Covers T1..T7 zero-shot."""

    name: ClassVar[str] = "llama_scout"
    _config_class: ClassVar[type[LLMConfig]] = LlamaScoutConfig


@register(
    name="gemma4",
    family="llm",
    tasks=_LLM_TASKS,
    config_class=Gemma4Config,
)
class Gemma4(_LLMBase):
    """Gemma-4 31B (FP8), TP=2. Covers T1..T7 zero-shot."""

    name: ClassVar[str] = "gemma4"
    _config_class: ClassVar[type[LLMConfig]] = Gemma4Config


@register(
    name="qwen35",
    family="llm",
    tasks=_LLM_TASKS,
    config_class=Qwen35Config,
)
class Qwen35(_LLMBase):
    """Qwen-3.5 27B (FP8), TP=1. Covers T1..T7 zero-shot."""

    name: ClassVar[str] = "qwen35"
    _config_class: ClassVar[type[LLMConfig]] = Qwen35Config


# Frontier closed-source LLMs served via OpenRouter (replace gemma4 + llm_finetuned).
class Gpt51Config(LLMConfig):
    model_id: str = "openai/gpt-5.1"


@register(
    name="gpt51",
    family="llm",
    tasks=_LLM_TASKS,
    config_class=Gpt51Config,
)
class Gpt51(_LLMBase):
    """OpenAI GPT-5.1 served via OpenRouter. Zero-shot."""
    name: ClassVar[str] = "gpt51"
    _config_class: ClassVar[type[LLMConfig]] = Gpt51Config


class Gemini3FlashConfig(LLMConfig):
    model_id: str = "google/gemini-3-flash-preview"


@register(
    name="gemini3_flash",
    family="llm",
    tasks=_LLM_TASKS,
    config_class=Gemini3FlashConfig,
)
class Gemini3Flash(_LLMBase):
    """Google Gemini-3 Flash (preview) via OpenRouter. Zero-shot."""
    name: ClassVar[str] = "gemini3_flash"
    _config_class: ClassVar[type[LLMConfig]] = Gemini3FlashConfig


class Exaone45Config(LLMConfig):
    model_id: str = "LGAI-EXAONE/EXAONE-4.5-33B-FP8"
    tensor_parallel_size: int = 4


@register(
    name="exaone",
    family="llm",
    tasks=_LLM_TASKS,
    config_class=Exaone45Config,
)
class Exaone45(_LLMBase):
    """LG AI Research EXAONE-4.5-33B (open weights, FP8). Local vLLM, TP=4. Zero-shot."""
    name: ClassVar[str] = "exaone"
    _config_class: ClassVar[type[LLMConfig]] = Exaone45Config


__all__ = ["LlamaScout", "Gemma4", "Qwen35", "Gpt51", "Gemini3Flash", "Exaone45"]