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
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
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
"""LLM fine-tune (LoRA SFT) method (family ``llm_ft``).

A single concrete class :class:`LLMFineTuned` (``name="llm_finetuned"``)
that wraps QLoRA SFT over any of the three MacroLens panel LLMs:
``llama_scout``, ``gemma4``, ``qwen35``.

Per the unified-API plan §9, this method's ``tasks`` defaults to the
maximum coverage (T1..T7); the runner narrows to the post-hoc-selected
ZS-winner's coverage at config time.

Method contract (sklearn-style):

    LLMFineTuned(task="T1", config=LLMFineTunedConfig(...), dry_run=False)
        .fit(X_train, y_train, seed=42)   # LoRA SFT on (prompt, answer) pairs
        .predict(X_test)                   # generate with the merged adapter
        .save(path)                        # PEFT adapter + manifest.json
        LLMFineTuned.load(path)            # reload

Hard rules:
- Zero IO of benchmark data (the loader provides X / y).
- Zero eval imports.
- Zero ``meta`` consumption.
- Honors ``MACROLENS_DETERMINISTIC=1`` via :func:`_seed_from_env`.

Per-task input / output shapes match :mod:`methods.llm` and
:mod:`methods.llm_ts_reason`.

Inference engine
----------------
``predict`` calls go through a single shared protocol —
``engine.chat_complete(messages, max_tokens, ...) -> str`` — exposed by
:mod:`methods._openai_engine`. The runner serves the LoRA adapter via
``vllm serve --enable-lora --lora-modules <id>=<path>`` and injects an
``OpenAIChatEngine`` whose ``model_id`` resolves to the adapter id; in
``dry_run=True`` mode (no live endpoint) a
:class:`methods._openai_engine.DryRunEngine` is used so the
shape-contract smoke tests still pass.

Per-task fine-tune framing (training pair construction):

    T1 : (lookback close → forecast horizon close) — instruction is the
         numeric history serialised as text; output is the horizon close
         trajectory rounded to 2dp.
    T2/T5: fundamentals → market-cap dollar value.
    T3/T6: company snapshot → JSON of XBRL field → value pairs.
    T4 : event_type + event_description → return percentage.
    T7 : property attributes → JSON ``{rent, price}``.

Serialisation: ``LLMFineTuned.save(path)`` writes:
    - ``manifest.json``  — name, family, tasks, schema_version, task,
                            hyperparams (config.model_dump()), lib_versions.
    - ``adapter/``       — ``PeftModel.save_pretrained(adapter_path)``.
    - ``tokenizer/``     — ``AutoTokenizer.save_pretrained(...)`` so the
                            same tokenizer is used at load time.
    - ``adapter.sha256``  — sha256 of the adapter directory tree (recorded
                            in manifest as a provenance hash).

``LLMFineTuned.load(path)`` reverses the above and prepares the model
for ``predict(X)``.
"""

from __future__ import annotations

import hashlib
import json
import logging
import os
import pathlib
import re
from typing import Any, Literal

import numpy as np
import pandas as pd

from ._config import LLMFineTunedConfig
from ._openai_engine import DryRunEngine
from ._registry import register
from .base import Method, _HFSaveMixin

logger = logging.getLogger(__name__)


# ── Map a config base_model literal to a HuggingFace repo id ─────────────


_BASE_MODEL_ID: dict[str, str] = {
    "llama_scout": "meta-llama/Llama-4-Scout-17B-16E-Instruct",
    "gemma4":      "google/gemma-4-31B-it",
    "qwen35":      "Qwen/Qwen3.5-27B-FP8",
}


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


_DEFAULT_T3_T6_FIELDS = (
    "Revenues",
    "NetIncomeLoss",
    "Assets",
    "Liabilities",
    "StockholdersEquity",
    "OperatingIncomeLoss",
    "CashAndCashEquivalents",
    "PropertyPlantAndEquipmentNet",
    "LongTermDebt",
    "ResearchAndDevelopmentExpense",
)


# ── Shared helpers (kept in sync with methods.llm_ts_reason) ─────────────


_NUM_RE = re.compile(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?")


def _parse_first_number(text: str) -> float | None:
    if not text:
        return None
    m = _NUM_RE.search(text.replace(",", ""))
    if not m:
        return None
    try:
        return float(m.group(0))
    except (TypeError, ValueError):
        return None


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

    Looks for the first ``[...]`` substring in ``response`` and parses it
    as JSON. Returns a ``(horizon,)`` float32 ndarray, padding with the
    last value when shorter and truncating when longer. Falls back to
    extracting all numeric tokens from the bracketed slice when JSON
    parsing fails. Returns ``None`` on total parse failure.
    """
    if not response:
        return None
    start = response.find("[")
    end = response.rfind("]")
    if start < 0 or end <= start:
        return None
    candidate = response[start : end + 1]
    parsed: list[Any] | None = None
    try:
        loaded = json.loads(candidate)
        if isinstance(loaded, list):
            parsed = loaded
    except json.JSONDecodeError:
        parsed = None
    if parsed is None:
        tokens = _NUM_RE.findall(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:
            vals.append(float(v))
        except (TypeError, ValueError):
            continue
    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 _extract_json_object(response: str) -> dict[str, Any] | 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 _safe_float(v: Any, default: float = 0.0) -> float:
    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 _seed_from_env(seed: int) -> None:
    import random

    random.seed(seed)
    np.random.seed(seed)
    os.environ.setdefault("PYTHONHASHSEED", str(seed))
    try:
        import torch

        torch.manual_seed(seed)
        if os.environ.get("MACROLENS_DETERMINISTIC") == "1":
            try:
                torch.use_deterministic_algorithms(True)
            except Exception:
                pass
            try:
                torch.backends.cudnn.deterministic = True  # type: ignore[attr-defined]
            except Exception:
                pass
    except Exception:
        pass


def _find_close_idx_from_array(X: np.ndarray) -> int:
    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))])


def _sha256_dir(path: pathlib.Path) -> str:
    """Stable SHA256 over a directory tree (sorted file order)."""
    h = hashlib.sha256()
    if not path.exists():
        return h.hexdigest()
    for fp in sorted(path.rglob("*")):
        if not fp.is_file():
            continue
        h.update(fp.relative_to(path).as_posix().encode("utf-8"))
        h.update(b"\x00")
        h.update(fp.read_bytes())
    return h.hexdigest()


# ── Per-task (X, y) → (instruction, response) pair builders ──────────────


def _t1_pairs(
    X: np.ndarray, y: np.ndarray, *, close_idx: int,
) -> list[tuple[str, str]]:
    """T1 SFT pairs: (numeric history → horizon close trajectory).

    The instruction matches :func:`_t1_predict_prompt` so the SFT-trained
    adapter sees the same prompt at fit and predict time. The response is
    a bare JSON array of ``horizon`` floats — directly parseable by
    :func:`_parse_horizon_list`.
    """
    if X.ndim != 3 or y.ndim != 2:
        raise ValueError(
            f"T1 expects X (N,L,F), y (N,H); got X={X.shape}, y={y.shape}"
        )
    n, _lookback, _ = X.shape
    horizon = y.shape[1]
    pairs: list[tuple[str, str]] = []
    for i in range(n):
        close_history = X[i, :, close_idx]
        instr = _t1_predict_prompt(close_history, X.shape[1], horizon)
        target_str = ", ".join(
            f"{round(float(v), 2)}" for v in y[i].tolist()
        )
        resp = f"[{target_str}]"
        pairs.append((instr, resp))
    return pairs


def _t2_t5_pairs(
    X: pd.DataFrame, y: np.ndarray, *, task: str,
) -> list[tuple[str, str]]:
    pairs: list[tuple[str, str]] = []
    if task == "T2":
        for (_, row), tgt in zip(X.iterrows(), y):
            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))
            employees = row.get("fullTimeEmployees", "N/A")
            instr = (
                f"You are a financial analyst. Estimate the total equity "
                f"market capitalization of this company.\n\n"
                f"Sector: {sector}\n"
                f"Revenue: ${revenue:,.0f}\n"
                f"Net Income: ${net_income:,.0f}\n"
                f"Total Assets: ${total_assets:,.0f}\n"
                f"Employees: {employees}"
            )
            resp = f"Estimated market cap: ${float(tgt):,.0f}"
            pairs.append((instr, resp))
    else:  # T5
        stmt_cols = [c for c in X.columns if c.startswith("stmt_")]
        for (_, row), tgt in zip(X.iterrows(), y):
            sector = row.get("sector", "Unknown")
            industry = row.get("industry", "Unknown")
            items = []
            for c in stmt_cols:
                val = row.get(c)
                if pd.notna(val):
                    try:
                        items.append(f"{c}: ${float(val):,.0f}")
                    except (TypeError, ValueError):
                        continue
            block = "\n".join(items) if items else "No financial statement data available"
            instr = (
                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}\nIndustry: {industry}\n{block}"
            )
            resp = f"Estimated market cap: ${float(tgt):,.0f}"
            pairs.append((instr, resp))
    return pairs


def _t3_t6_pairs(
    X: pd.DataFrame, y: pd.DataFrame, *, task: str,
) -> list[tuple[str, str]]:
    """T3 / T6: build one pair per (ticker, fiscal_year) row of X.

    Response is a JSON object aggregating all ground-truth fields for
    that (ticker, fiscal_year). Rows missing in ``y`` are skipped (no
    silent zero-fill).
    """
    pairs: list[tuple[str, str]] = []
    # Group y by (ticker, fiscal_year)
    if y.empty:
        return pairs
    y_grouped = (
        y.groupby(["ticker", "fiscal_year"])
        .apply(lambda g: dict(zip(g["field"], g["value"])))
        .to_dict()
    )
    fields_seen: list[str] = []
    for _, row in X.iterrows():
        ticker = str(row.get("ticker", "?"))
        fy = row.get("fiscal_year", None)
        key = (ticker, fy)
        # Pandas Int64 keys may not round-trip; try a tolerant lookup.
        if key not in y_grouped:
            for cand_key in y_grouped:
                if str(cand_key[0]) == ticker and str(cand_key[1]) == str(fy):
                    key = cand_key
                    break
        gt_fields = y_grouped.get(key, {})
        if not gt_fields:
            continue
        fields_str = ", ".join(sorted(gt_fields.keys()))
        if not fields_seen:
            fields_seen = sorted(gt_fields.keys())
        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))
            instr = (
                f"You are a financial analyst. Given {ticker}'s known "
                f"fundamentals (sector={sector}, revenue=${revenue:,.0f}, "
                f"net_income=${net_income:,.0f}), predict these XBRL "
                f"fields: [{fields_str}]"
            )
        else:  # T6
            description = row.get(
                "company_description", f"A company with ticker {ticker}",
            )
            sector = row.get("sector", "Unknown")
            industry = row.get("industry", "Unknown")
            instr = (
                f"Given this company description: '{description}', "
                f"sector: '{sector}', industry: '{industry}', generate "
                f"plausible financial statement values for these XBRL "
                f"fields: [{fields_str}]"
            )
        resp = json.dumps(
            {k: round(float(v), 2) for k, v in gt_fields.items()
             if pd.notna(v)},
        )
        pairs.append((instr, resp))
    return pairs


def _t4_pairs(X: Any, y: np.ndarray) -> list[tuple[str, str]]:
    if isinstance(X, pd.DataFrame):
        event_type = X.get("event_type", pd.Series([], dtype=object)).to_numpy()
        event_desc = X.get(
            "event_description", pd.Series([""] * len(event_type), dtype=object),
        ).to_numpy()
    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 DataFrame or dict, got {type(X).__name__}"
        )
    pairs: list[tuple[str, str]] = []
    for et, ed, tgt in zip(event_type, event_desc, y):
        et_s = str(et) if et is not None else "unknown"
        ed_s = str(ed)[:200] if ed is not None else ""
        instr = (
            f"You are a financial analyst. Given the scenario:\n"
            f"- Event type: {et_s}\n"
            + (f"- Description: {ed_s}\n" if ed_s else "")
            + "\nPredict the stock return (%) following this event."
        )
        resp = f"Predicted return: {float(tgt):.2f}%"
        pairs.append((instr, resp))
    return pairs


def _t7_pairs(X: pd.DataFrame, y: pd.DataFrame) -> list[tuple[str, str]]:
    pairs: list[tuple[str, str]] = []
    y_by_addr = (
        y.set_index("address").to_dict("index")
        if "address" in y.columns else {}
    )
    for _, row in X.iterrows():
        addr = row.get("address", None)
        gt = y_by_addr.get(addr, {})
        rent_val = float(gt.get("rent", 0) or 0) if gt else 0.0
        price_val = float(gt.get("price", 0) or 0) if gt else 0.0
        if rent_val <= 0 and price_val <= 0:
            continue
        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")
        instr = (
            f"Estimate AS OF 2026-04-11. Given this property: "
            f"location={city}, {state}, type={property_type}, sqft={sqft}, "
            f"beds={beds}, baths={baths}, year_built={year_built}. "
            f"Estimate the monthly rent and sale price."
        )
        resp = json.dumps(
            {"rent": round(rent_val, 2), "price": round(price_val, 2)},
        )
        pairs.append((instr, resp))
    return pairs


# ── Per-task predict prompts (no labels) ──────────────────────────────────


def _t1_predict_prompt(
    history: np.ndarray, lookback: int, horizon: int,
) -> str:
    last = float(history[-1]) if len(history) else 0.0
    mean = float(np.mean(history)) if len(history) else 0.0
    std = float(np.std(history)) if len(history) else 0.0
    denom = max(float(history[0]) if len(history) else 1e-2, 1e-2)
    trend = float((history[-1] - history[0]) / denom * 100) if len(history) else 0.0
    last20 = ", ".join(f"{v:.4f}" for v in history[-20:])
    return (
        f"You are a quantitative analyst. Predict the daily closing prices "
        f"of the stock for each of the next {horizon} trading days, given:\n"
        f"- Current close: ${last:.2f}\n"
        f"- Past {lookback} closes: mean=${mean:.2f}, std=${std:.2f}, "
        f"trend={trend:+.1f}%\n"
        f"- Recent close series (last 20 of {lookback}): [{last20}]\n\n"
        f"Reply with ONLY a JSON array of {horizon} floats, one per future "
        f"trading day, in chronological order:\n"
        f"[float, float, ..., float]"
    )


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


class _DryRunFTEngine:
    """Deterministic stand-in for an SFT-trained LLM during smoke tests.

    Returns shape-correct placeholder responses so :meth:`predict` can be
    exercised without HF / peft / GPU. The runner never sees this in
    real runs (it injects a real OpenAIChatEngine pointed at a vLLM
    LoRA-aware endpoint via ``--enable-lora``).

    Exposes BOTH the legacy ``generate(prompt)`` hook AND the unified
    ``chat_complete(messages, ...)`` protocol so it slots into the same
    code path the real OpenAIChatEngine uses.
    """

    def __init__(self, marker: float = 1.0) -> None:
        self.marker = float(marker)
        self.model_id = "dry-run-ft"

    def generate(self, prompt: str) -> str:  # noqa: D401
        lower = prompt.lower()
        if "rent" in lower and "sale price" in lower:
            return '{"rent": 2000, "price": 500000}'
        if "xbrl" in lower:
            return '{"Revenues": 1000000, "NetIncomeLoss": 100000}'
        if "predict the stock return" in lower:
            return f"Predicted return: {self.marker:.2f}%"
        if "json array" in lower:
            # T1 horizon-list forecast: try to recover horizon from prompt.
            m = re.search(r"json array of (\d+) floats", lower)
            horizon = int(m.group(1)) if m else 21
            return "[" + ", ".join(
                [f"{self.marker:.4f}"] * horizon
            ) + "]"
        if "next" in lower and "closing prices" in lower:
            # Legacy fallback: emit a 21-element horizon list.
            return "[" + ", ".join([f"{self.marker:.4f}"] * 21) + "]"
        return f"{self.marker:.4f}"

    def chat_complete(
        self,
        messages: list[dict[str, str]],
        *,
        max_tokens: int = 256,
        temperature: float = 0.0,
        top_p: float = 1.0,
    ) -> str:
        """Adapt the unified chat-complete protocol to the legacy generate hook."""
        try:
            prompt = " ".join(
                str(m.get("content", "")) for m in (messages or [])
            )
        except Exception:
            prompt = ""
        return self.generate(prompt)

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


# ── Main class ────────────────────────────────────────────────────────────


@register(
    name="llm_finetuned",
    family="llm_ft",
    # Default: maximum coverage. The runner narrows to the post-hoc
    # ZS-winner's coverage at config time per plan §9.
    tasks={"T1", "T2", "T3", "T4", "T5", "T6", "T7"},
    config_class=LLMFineTunedConfig,
)
class LLMFineTuned(_HFSaveMixin, Method):
    """LoRA SFT wrapper around any of the four MacroLens panel LLMs.

    The base model is selected via ``LLMFineTunedConfig.model_id``; the
    corresponding panel short-name (``llama_scout`` / ``gemma4`` /
    ``qwen35``) is recovered from the HF id when needed.

    Parameters
    ----------
    task : {"T1", ..., "T7"}
        Task this instance is fitted for.
    config : LLMFineTunedConfig | None
        Hyperparameters (LoRA r/alpha, epochs, learning rate, ...).
        Defaults to :meth:`default_config`.
    base_model : {"llama_scout","gemma4","qwen35"} | None
        Convenience override; if provided, sets
        ``config.model_id`` accordingly.
    dry_run : bool
        When True, fit / predict short-circuit to a CPU-only deterministic
        stand-in for shape-only smoke testing. No HF / peft / torch GPU
        is required. Default: False.

    Notes
    -----
    The QLoRA SFT recipe is preserved verbatim from
    :mod:`baselines.llm_finetune`: bnb NF4 4-bit quant, paged AdamW 8-bit,
    LoRA on q/k/v/o projections, bf16 compute. The Gemma-4 special-case
    (load full MM checkpoint, keep only ``language_model``) is applied
    for ``base_model="gemma4"``.

    Runner-side dispatch
    --------------------
    Per plan §9, the SFT base model is picked from the post-hoc-selected
    ZS winner. :meth:`from_zs_winner` is the intended dispatch entrypoint:
    it takes a per-method dict of zero-shot scores (lower-is-better) and
    returns an instance with ``base_model`` set to the argmin.
    """

    def __init__(
        self,
        *,
        task: str,
        config: LLMFineTunedConfig | None = None,
        engine: Any = None,
        base_model: Literal[
            "llama_scout", "gemma4", "qwen35", None
        ] | None = None,
        dry_run: bool = False,
        **kwargs: Any,
    ) -> None:
        if task not in self.tasks:
            raise ValueError(
                f"LLMFineTuned: task={task!r} not in supported set "
                f"{sorted(self.tasks)}"
            )
        if config is None:
            config = LLMFineTunedConfig(**kwargs) if kwargs else LLMFineTunedConfig()
        elif kwargs:
            merged = {**config.model_dump(), **kwargs}
            config = LLMFineTunedConfig(**merged)
        if base_model is not None:
            mid = _BASE_MODEL_ID.get(base_model)
            if mid is None:
                raise ValueError(
                    f"base_model={base_model!r}; expected one of "
                    f"{sorted(_BASE_MODEL_ID)}"
                )
            config = LLMFineTunedConfig(
                **{**config.model_dump(), "model_id": mid},
            )
        self.task = task
        self.config = config
        # Honor either an explicit ``dry_run`` ctor kwarg OR ``config.dry_run``
        # (the smoke-test path sets the latter via ``cfg.model_copy(...)``).
        self.dry_run = bool(dry_run) or bool(getattr(config, "dry_run", False))
        # Adapter / tokenizer state (populated by fit / load).
        self._adapter_dir: pathlib.Path | None = None
        self._tokenizer_dir: pathlib.Path | None = None
        self._model: Any = None
        self._tokenizer: Any = None
        # OpenAIChatEngine injected by the runner for HTTP-served LoRA
        # inference. ``_dry_engine`` is the local fallback used when
        # ``dry_run=True`` AND no real engine was supplied.
        self.engine: Any = engine
        self._dry_engine: _DryRunFTEngine | None = (
            _DryRunFTEngine() if self.dry_run else None
        )
        # Per-task hints (mirrors :mod:`methods.llm_ts_reason`).
        self._t1_close_idx: int | None = None
        self._t1_horizon: int = 21
        # T3/T6 fitted-field tracking: predict-time prompts need to declare
        # the same field list the adapter was trained on. Populated by
        # ``fit`` and used by ``_predict_t3_t6``.
        self._fitted_fields_per_ticker: dict[str, list[str]] = {}
        self._fitted_fields_global: list[str] = []
        self.last_predict_meta: dict[str, Any] = {}

    # ── fit (LoRA SFT) ───────────────────────────────────────────────────

    @classmethod
    def default_config(cls) -> LLMFineTunedConfig:
        return LLMFineTunedConfig()

    @classmethod
    def from_zs_winner(
        cls,
        zs_results: dict[str, float],
        *,
        task: str,
        config: LLMFineTunedConfig | None = None,
        **kwargs: Any,
    ) -> "LLMFineTuned":
        """Construct an instance keyed to the zero-shot winner.

        Parameters
        ----------
        zs_results : dict[str, float]
            Per-method primary-metric scores, e.g.
            ``{"llama_scout": 0.5, "gemma4": 0.4, ...}``. Lower-is-better:
            the argmin is selected as the LoRA SFT base model.
        task : str
            Task this instance will be fitted for.
        config, **kwargs
            Forwarded to :class:`LLMFineTuned` along with the resolved
            ``base_model``.

        Returns
        -------
        LLMFineTuned
            An instance with ``base_model`` set to the argmin of
            ``zs_results`` (restricted to the four panel LLMs).

        Raises
        ------
        ValueError
            If ``zs_results`` is empty or contains no recognised panel
            short-names (``llama_scout``, ``gemma4``, ``qwen35``).
        """
        if not zs_results:
            raise ValueError(
                "from_zs_winner: zs_results is empty; cannot pick a winner."
            )
        valid = {
            k: float(v)
            for k, v in zs_results.items()
            if k in _BASE_MODEL_ID
        }
        if not valid:
            raise ValueError(
                f"from_zs_winner: zs_results keys {sorted(zs_results)} "
                f"contain no recognised panel short-name; expected any of "
                f"{sorted(_BASE_MODEL_ID)}."
            )
        winner = min(valid, key=lambda k: valid[k])
        return cls(
            task=task, config=config, base_model=winner, **kwargs,
        )

    def fit(self, X: Any, y: Any, *, seed: int = 42) -> "Method":
        """Run LoRA SFT on (X, y) framed as (instruction, response) pairs.

        In ``dry_run=True`` mode this is a no-op (no HF deps needed). In
        normal mode it loads the base model with bnb NF4, applies a LoRA
        adapter, runs SFT via TRL's ``SFTTrainer``, and stores the
        merged adapter dir on ``self._adapter_dir``.
        """
        _seed_from_env(seed)
        # Capture T1 horizon from y so ``predict`` emits matching length
        # trajectories. The default ``_t1_horizon = 21`` is wrong for the
        # canonical T1 task whose horizon is 252 trading days.
        if self.task == "T1" and isinstance(y, np.ndarray) and y.ndim == 2:
            self._t1_horizon = int(y.shape[1])
        # Capture the T3/T6 fitted-field set so predict-time prompts can
        # declare the same fields the adapter was trained on.
        if self.task in ("T3", "T6"):
            if isinstance(y, pd.DataFrame) and not y.empty and "field" in y.columns:
                self._fitted_fields_per_ticker = {
                    str(t): sorted(grp["field"].astype(str).unique().tolist())
                    for t, grp in y.groupby("ticker", sort=False)
                }
                self._fitted_fields_global = sorted(
                    y["field"].astype(str).unique().tolist()
                )
        if self.dry_run:
            return self

        # Build (instruction, response) pairs for the task.
        pairs = self._build_pairs(X, y)
        if not pairs:
            raise RuntimeError(
                f"LLMFineTuned.fit({self.task}): no training pairs constructed."
            )
        texts = [
            f"### Instruction:\n{instr}\n\n### Response:\n{resp}"
            for instr, resp in pairs
        ]

        try:
            import torch
            from transformers import (
                AutoModelForCausalLM, AutoTokenizer,
                BitsAndBytesConfig, TrainingArguments,
            )
            from peft import (
                LoraConfig, get_peft_model, prepare_model_for_kbit_training,
            )
            from trl import SFTTrainer
            from datasets import Dataset as HFDataset
        except ImportError as exc:
            raise RuntimeError(
                "LLMFineTuned.fit requires transformers + peft + trl + "
                f"bitsandbytes + datasets. Underlying error: {exc!r}"
            ) from exc

        quant_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_use_double_quant=True,
            bnb_4bit_compute_dtype=torch.bfloat16,
        )

        model_id = self.config.model_id
        # Gemma-4 special-case: full MM checkpoint → text-only language model.
        if "gemma-4" in model_id.lower():
            from transformers import (
                Gemma4ForCausalLM,
                Gemma4ForConditionalGeneration,
            )
            full_model = Gemma4ForConditionalGeneration.from_pretrained(
                model_id,
                quantization_config=quant_config,
                device_map="auto",
                trust_remote_code=True,
                torch_dtype=torch.bfloat16,
                attn_implementation="eager",
            )
            text_config = full_model.config.text_config
            model = Gemma4ForCausalLM(text_config)
            model.model = full_model.model.language_model
            if hasattr(full_model, "lm_head"):
                model.lm_head = full_model.lm_head
            model.config._name_or_path = model_id
            del full_model
        else:
            model = AutoModelForCausalLM.from_pretrained(
                model_id,
                quantization_config=quant_config,
                device_map="auto",
                trust_remote_code=True,
                torch_dtype=torch.bfloat16,
                attn_implementation="eager",
            )
        tokenizer = AutoTokenizer.from_pretrained(
            model_id, trust_remote_code=True,
        )
        if tokenizer.pad_token is None:
            tokenizer.pad_token = tokenizer.eos_token

        model = prepare_model_for_kbit_training(model)
        lora_cfg = LoraConfig(
            r=self.config.lora_r,
            lora_alpha=self.config.lora_alpha,
            target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
            lora_dropout=0.05,
            bias="none",
            task_type="CAUSAL_LM",
        )
        model = get_peft_model(model, lora_cfg)

        # Output dir under a process-local checkpoint root so multiple
        # (task, seed) fits don't collide.
        ckpt_root = pathlib.Path(
            os.environ.get(
                "MACROLENS_CHECKPOINT_ROOT",
                str(pathlib.Path.home() / ".cache" / "macrolens" / "llm_ft"),
            )
        )
        model_short = model_id.split("/")[-1].lower().replace("-", "_")
        output_dir = ckpt_root / f"{model_short}_{self.task}_seed{seed}"
        output_dir.mkdir(parents=True, exist_ok=True)

        train_dataset = HFDataset.from_dict({"text": texts})
        training_args = TrainingArguments(
            output_dir=str(output_dir),
            num_train_epochs=self.config.epochs,
            per_device_train_batch_size=4,
            gradient_accumulation_steps=8,
            learning_rate=self.config.learning_rate,
            weight_decay=0.01,
            warmup_ratio=0.1,
            logging_steps=50,
            save_strategy="epoch",
            save_total_limit=1,
            report_to="none",
            fp16=False,
            bf16=True,
            gradient_checkpointing=True,
            optim="paged_adamw_8bit",
            max_grad_norm=0.3,
            seed=seed,
        )
        trainer = SFTTrainer(
            model=model,
            args=training_args,
            train_dataset=train_dataset,
        )
        trainer.train()

        # Persist the adapter inline so ``predict`` can re-load it with
        # the same artifact ``save`` will expose downstream.
        adapter_dir = output_dir / "adapter"
        tokenizer_dir = output_dir / "tokenizer"
        model.save_pretrained(str(adapter_dir))
        tokenizer.save_pretrained(str(tokenizer_dir))

        self._model = model
        self._tokenizer = tokenizer
        self._adapter_dir = adapter_dir
        self._tokenizer_dir = tokenizer_dir
        return self

    def _build_pairs(self, X: Any, y: Any) -> list[tuple[str, str]]:
        """Dispatch to the per-task pair builder."""
        if self.task == "T1":
            X_arr = np.asarray(X, dtype=np.float32)
            close_idx = (
                self._t1_close_idx
                if self._t1_close_idx is not None
                else _find_close_idx_from_array(X_arr)
            )
            return _t1_pairs(X_arr, np.asarray(y, dtype=np.float32),
                             close_idx=close_idx)
        if self.task in ("T2", "T5"):
            return _t2_t5_pairs(X, np.asarray(y, dtype=np.float64),
                                task=self.task)
        if self.task in ("T3", "T6"):
            return _t3_t6_pairs(X, y, task=self.task)
        if self.task == "T4":
            return _t4_pairs(X, np.asarray(y, dtype=np.float32))
        if self.task == "T7":
            return _t7_pairs(X, y)
        raise ValueError(f"Unknown task: {self.task!r}")

    # ── predict (adapter inference) ──────────────────────────────────────

    def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
        if self.task == "T1":
            return self._predict_t1(X)
        if self.task == "T2":
            return self._predict_t2_t5(X, task="T2")
        if self.task == "T3":
            return self._predict_t3_t6(X, task="T3")
        if self.task == "T4":
            return self._predict_t4(X)
        if self.task == "T5":
            return self._predict_t2_t5(X, task="T5")
        if self.task == "T6":
            return self._predict_t3_t6(X, task="T6")
        if self.task == "T7":
            return self._predict_t7(X)
        raise ValueError(f"Unknown task: {self.task!r}")

    def _generate(self, prompt: str, *, max_new_tokens: int = 256) -> str:
        """Run a single-prompt generate.

        Resolution order:
        1. Injected ``self.engine`` (an
           :class:`methods._openai_engine.OpenAIChatEngine` against a
           vLLM ``--enable-lora`` endpoint serving the adapter as
           ``model_id``). Preferred path; HTTP, no GPUs in this process.
        2. In-process ``self._model`` / ``self._tokenizer`` (set by
           ``fit`` / ``load`` with peft + bnb). Legacy path kept for
           backwards compatibility when no HTTP endpoint is available.
        3. ``self._dry_engine`` (when ``dry_run=True``).
        """
        # Wrap instruction-tuned prompt envelope so the SFT-trained
        # adapter sees the same text shape at fit and predict time.
        full_prompt = f"### Instruction:\n{prompt}\n\n### Response:\n"

        # 1. Real OpenAI-compatible engine (preferred).
        if self.engine is not None and hasattr(self.engine, "chat_complete"):
            messages = [{"role": "user", "content": full_prompt}]
            return str(self.engine.chat_complete(
                messages, max_tokens=max_new_tokens, temperature=0.0,
            ))

        # 3. Dry-run fallback (smoke tests).
        if self.dry_run:
            assert self._dry_engine is not None
            return self._dry_engine.generate(prompt)

        # 2. In-process peft model fallback.
        if self._model is None or self._tokenizer is None:
            raise RuntimeError(
                "LLMFineTuned.predict: no engine injected, model/tokenizer "
                "not loaded, and dry_run=False. Either inject an "
                "OpenAIChatEngine via the engine= ctor kwarg, call "
                ".fit(...) / .load(...) first, or set dry_run=True."
            )
        import torch

        inputs = self._tokenizer(
            full_prompt, return_tensors="pt", truncation=True, max_length=2048,
        )
        dev = next(self._model.parameters()).device
        inputs = {k: v.to(dev) for k, v in inputs.items()}
        with torch.no_grad():
            outputs = self._model.generate(
                **inputs,
                max_new_tokens=max_new_tokens,
                do_sample=False,
                pad_token_id=self._tokenizer.eos_token_id,
            )
        return self._tokenizer.decode(
            outputs[0][inputs["input_ids"].shape[1]:],
            skip_special_tokens=True,
        )

    # ── Per-task predictors (mirror :mod:`methods.llm_ts_reason`) ──

    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)
        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)
        )
        preds = np.full((n, horizon), np.nan, dtype=np.float32)
        n_errors = 0
        # Trajectory output requires more tokens than a single scalar:
        # budget ~12 tokens per horizon step plus brackets/separators.
        max_new_tokens = max(64, 12 * horizon + 16)
        for i in range(n):
            history = X[i, :, close_idx]
            prompt = _t1_predict_prompt(history, lookback, horizon)
            response = self._generate(prompt, max_new_tokens=max_new_tokens)
            traj = _parse_horizon_list(response, horizon)
            if traj is None:
                n_errors += 1
                continue
            preds[i, :] = traj
        self.last_predict_meta = {
            "task": "T1", "n_attempted": int(n),
            "n_parse_errors": int(n_errors),
            "horizon": horizon, "close_idx": int(close_idx),
        }
        return preds

    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(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.float32)
        if task == "T2":
            instructions = []
            for _, row in X.iterrows():
                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))
                employees = row.get("fullTimeEmployees", "N/A")
                instructions.append(
                    f"You are a financial analyst. Estimate the total "
                    f"equity market capitalization of this company.\n\n"
                    f"Sector: {sector}\nRevenue: ${revenue:,.0f}\n"
                    f"Net Income: ${net_income:,.0f}\n"
                    f"Total Assets: ${total_assets:,.0f}\n"
                    f"Employees: {employees}"
                )
        else:
            # Match `_t2_t5_pairs` (T5 branch) exactly.
            stmt_cols = [c for c in X.columns if c.startswith("stmt_")]
            instructions = []
            for _, row in X.iterrows():
                sector = row.get("sector", "Unknown")
                industry = row.get("industry", "Unknown")
                items = []
                for c in stmt_cols:
                    val = row.get(c)
                    if pd.notna(val):
                        try:
                            items.append(f"{c}: ${float(val):,.0f}")
                        except (TypeError, ValueError):
                            continue
                block = (
                    "\n".join(items) if items
                    else "No financial statement data available"
                )
                instructions.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}\nIndustry: {industry}\n{block}"
                )
        preds = np.full(n, np.nan, dtype=np.float64)
        n_errors = 0
        for i, prompt in enumerate(instructions):
            response = self._generate(prompt, max_new_tokens=64)
            v = _parse_first_number(response)
            if v is None or v <= 0:
                n_errors += 1
                continue
            preds[i] = float(v)
        self.last_predict_meta = {
            "task": task, "n_attempted": int(n),
            "n_parse_errors": int(n_errors),
        }
        return preds

    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(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)
        )

        rows: list[dict[str, Any]] = []
        n_errors = 0
        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)
            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))
                # Match `_t3_pairs` exactly so the adapter sees the same
                # instruction text at predict time as it did during SFT.
                instr = (
                    f"You are a financial analyst. Given {ticker}'s known "
                    f"fundamentals (sector={sector}, revenue=${revenue:,.0f}, "
                    f"net_income=${net_income:,.0f}), predict these XBRL "
                    f"fields: [{fields_str}]"
                )
            else:
                description = row.get(
                    "company_description", f"A company with ticker {ticker}",
                )
                sector = row.get("sector", "Unknown")
                industry = row.get("industry", "Unknown")
                # Match `_t6_pairs` exactly.
                instr = (
                    f"Given this company description: '{description}', "
                    f"sector: '{sector}', industry: '{industry}', generate "
                    f"plausible financial statement values for these XBRL "
                    f"fields: [{fields_str}]"
                )
            response = self._generate(instr, max_new_tokens=512)
            parsed = _extract_json_object(response)
            if parsed is None:
                n_errors += 1
                continue
            for field, val in parsed.items():
                try:
                    rows.append({
                        "ticker": ticker, "fiscal_year": fy,
                        "field": str(field), "pred": float(val),
                    })
                except (TypeError, ValueError):
                    continue
        self.last_predict_meta = {
            "task": task, "n_attempted": int(n),
            "n_parse_errors": int(n_errors),
        }
        return pd.DataFrame(
            rows, columns=["ticker", "fiscal_year", "field", "pred"]
        )

    def _predict_t4(self, X: Any) -> np.ndarray:
        if isinstance(X, dict):
            event_type = np.asarray(X.get("event_type", []))
            event_desc = np.asarray(X.get("event_description", []))
        elif isinstance(X, pd.DataFrame):
            event_type = (
                X["event_type"].to_numpy()
                if "event_type" in X.columns else np.array([])
            )
            event_desc = (
                X["event_description"].to_numpy()
                if "event_description" in X.columns
                else np.array([""] * len(event_type))
            )
        else:
            raise ValueError(
                f"T4 X must be DataFrame or dict, got {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)
        preds = np.full(n, np.nan, dtype=np.float32)
        n_errors = 0
        for i in range(n):
            et_s = str(event_type[i]) if event_type[i] is not None else "unknown"
            ed_s = str(event_desc[i])[:200] if event_desc[i] is not None else ""
            instr = (
                f"You are a financial analyst. Given the scenario:\n"
                f"- Event type: {et_s}\n"
                + (f"- Description: {ed_s}\n" if ed_s else "")
                + "\nPredict the stock return (%) following this event."
            )
            response = self._generate(instr, max_new_tokens=64)
            v = _parse_first_number(response)
            if v is None:
                n_errors += 1
                continue
            preds[i] = float(v)
        self.last_predict_meta = {
            "task": "T4", "n_attempted": int(n),
            "n_parse_errors": int(n_errors),
        }
        return preds

    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(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"]
            )
        rows: list[dict[str, Any]] = []
        n_errors = 0
        for _, row in X.iterrows():
            addr = 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")
            instr = (
                f"Estimate AS OF 2026-04-11. Given this property: "
                f"location={city}, {state}, type={property_type}, "
                f"sqft={sqft}, beds={beds}, baths={baths}, "
                f"year_built={year_built}. Estimate the monthly rent and "
                f"sale price."
            )
            response = self._generate(instr, max_new_tokens=128)
            parsed = _extract_json_object(response)
            if parsed is None:
                n_errors += 1
                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", 0) or 0)
            except (TypeError, ValueError):
                rent_val = np.nan
            try:
                price_val = float(ci.get("price", 0) or 0)
            except (TypeError, ValueError):
                price_val = np.nan
            rows.append({"address": addr, "pred_rent": rent_val,
                         "pred_price": price_val})
        self.last_predict_meta = {
            "task": "T7", "n_attempted": int(n),
            "n_parse_errors": int(n_errors),
        }
        return pd.DataFrame(
            rows, columns=["address", "pred_rent", "pred_price"]
        )

    # ── HF save / load hooks ─────────────────────────────────────────────

    def _manifest(self) -> dict[str, Any]:
        m = super()._manifest()
        adapter_sha = ""
        if self._adapter_dir is not None and self._adapter_dir.exists():
            adapter_sha = _sha256_dir(self._adapter_dir)
        m["sha256s"] = {"adapter": adapter_sha}
        return m

    def _hf_save(self, path: pathlib.Path) -> None:
        """Persist the LoRA adapter + tokenizer to ``path``.

        Layout::

            path/manifest.json     # Method ABC
            path/adapter/          # peft.PeftModel.save_pretrained
            path/tokenizer/        # tokenizer.save_pretrained
            path/adapter.sha256    # plain-text hash recorded in manifest
        """
        if self.dry_run or self._adapter_dir is None:
            # Dry-run mode: write a placeholder so load() can detect mode.
            (path / "DRY_RUN").write_text("1\n")
            return

        import shutil

        target_adapter = path / "adapter"
        if target_adapter.exists():
            shutil.rmtree(target_adapter)
        shutil.copytree(self._adapter_dir, target_adapter)

        if self._tokenizer_dir is not None and self._tokenizer_dir.exists():
            target_tok = path / "tokenizer"
            if target_tok.exists():
                shutil.rmtree(target_tok)
            shutil.copytree(self._tokenizer_dir, target_tok)

        sha = _sha256_dir(target_adapter)
        (path / "adapter.sha256").write_text(sha + "\n")

    def _hf_load(self, path: pathlib.Path) -> None:
        """Reload adapter + tokenizer; rebuild a merged model in memory.

        In dry_run mode this short-circuits (the placeholder marker file
        is detected and ``self._dry_engine`` is re-established).
        """
        if (path / "DRY_RUN").exists():
            self.dry_run = True
            self._dry_engine = _DryRunFTEngine()
            return

        try:
            import torch
            from transformers import (
                AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,
            )
            from peft import PeftModel
        except ImportError as exc:
            raise RuntimeError(
                "LLMFineTuned.load requires transformers + peft + "
                f"bitsandbytes. Underlying error: {exc!r}"
            ) from exc

        adapter_dir = path / "adapter"
        tokenizer_dir = path / "tokenizer"
        if not adapter_dir.exists():
            raise FileNotFoundError(
                f"adapter directory missing at {adapter_dir}"
            )

        quant_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_use_double_quant=True,
            bnb_4bit_compute_dtype=torch.bfloat16,
        )
        model_id = self.config.model_id
        if "gemma-4" in model_id.lower():
            from transformers import Gemma4ForCausalLM
            base = Gemma4ForCausalLM.from_pretrained(
                model_id, quantization_config=quant_config,
                device_map="auto", trust_remote_code=True,
                torch_dtype=torch.bfloat16, attn_implementation="eager",
            )
        else:
            base = AutoModelForCausalLM.from_pretrained(
                model_id, quantization_config=quant_config,
                device_map="auto", trust_remote_code=True,
                torch_dtype=torch.bfloat16, attn_implementation="eager",
            )
        peft_model = PeftModel.from_pretrained(base, str(adapter_dir))
        tok_src = tokenizer_dir if tokenizer_dir.exists() else model_id
        tokenizer = AutoTokenizer.from_pretrained(
            str(tok_src), trust_remote_code=True,
        )
        if tokenizer.pad_token is None:
            tokenizer.pad_token = tokenizer.eos_token

        self._model = peft_model
        self._tokenizer = tokenizer
        self._adapter_dir = adapter_dir
        self._tokenizer_dir = tokenizer_dir if tokenizer_dir.exists() else None


__all__ = ["LLMFineTuned"]