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
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
"""Llama-4 Scout multi-task QLoRA SFT (Family-7 / Phase 3.1).

Hyperparameters mirror Meta's official torchtune recipe
``recipes/configs/llama4/scout_17B_16E_lora.yaml`` (rev 4415449e) verbatim
where applicable; the only deviations are forced by our hardware
(4xA100-40GB vs Meta's 8xA100 reference):

* **Quantisation.** Meta's recipe is bf16 full-precision; Scout in bf16 is
  ~218GB of weights + matching optimiser state and does not fit on 4x40GB.
  We replace the bf16 load with bnb NF4 4-bit (~55GB of weights, split
  across the 4 GPUs) so the model fits. RESEARCH_PLAN.md §5.1 documents
  this as the "MoE-on-bitsandbytes complexity" path; the explicit
  ``max_memory`` map below avoids the CPU/disk-offload failure mode that
  ``device_map="auto"`` triggers on Scout-MoE.
* **Distributed.** Meta uses FSDP via torchtune (which the venv does not
  carry on this torch version); we use bnb-4bit + HF ``device_map="auto"``
  with explicit per-GPU caps and let peft handle the LoRA-side gradient
  flow. No DeepSpeed or torchtune dependency.
* **Routed-expert LoRA.** Meta's recipe sets ``apply_lora_to_mlp: True``
  which adapts every Llama4 expert MLP. HF transformers 5.8.0 packs the
  16 routed experts of each layer into a single ``Llama4TextExperts``
  custom module (one tensor per expert axis), which peft 0.19.1 cannot
  target via the default suffix-matching path. We therefore LoRA-adapt
  ``q_proj``, ``k_proj``, ``v_proj``, ``o_proj`` (attention) plus
  ``gate_proj``, ``up_proj``, ``down_proj`` (the shared / always-on
  expert MLP). Routed experts stay frozen — a known limitation; the
  shared expert + attention LoRA still gives substantial adaptation
  capacity per the SciTS / EDINET-Bench precedent.

All four Meta-recipe LoRA hyperparameters (``r=16, alpha=32,
dropout=0.0``, lr=2e-5, 1 epoch, ``clip_grad_norm: null``) are preserved
verbatim per `feedback_use_library_defaults`.

Data format follows TRL 1.3's ``completion_only_loss=True`` schema:
each training row is ``{"prompt": ..., "completion": ...}`` so loss is
computed only on the completion tokens. The pair builders in
:mod:`methods.llm_finetune` are reused unchanged for T1..T7; the
``### Instruction: ... ### Response:`` envelope is preserved so the
inference-side prompt format matches.

This is a multi-GPU-day run on 4xA100-40GB (GPUs 4..7 per project
memory). The user must authorise the launch explicitly.
"""

from __future__ import annotations

import argparse
import json
import logging
import os
import sys
import time
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)

# Per project memory: MacroLens GPUs are 4-7. The caller must set
# CUDA_VISIBLE_DEVICES=4,5,6,7 before launching this script; we read it
# for logging and to size the ``max_memory`` map below.


def _t3_t6_pairs_fixed(
    X: Any, y: Any, *, task: str, fitted_fields: list[str],
) -> list[tuple[str, str]]:
    """T3/T6 pair builder using a FIXED field list.

    Replaces :func:`methods.llm_finetune._t3_t6_pairs` so the training
    instruction matches the prediction-time prompt exactly. The original
    per-row variant lists only the fields that appear in THIS row's
    ground truth; the eval path's ``_predict_t3_t6`` falls back to a
    fitted-field list (or the buggy 10-field ``_DEFAULT_T3_T6_FIELDS``).
    The mismatch causes the adapter to learn one schema and be queried
    on another at test time.

    Here every (ticker, fiscal_year) row is wrapped in a prompt that
    lists ``fitted_fields`` verbatim. The response JSON includes every
    field in ``fitted_fields``; values not present in the row's ground
    truth get ``null`` (which the eval-side parser
    :func:`_extract_json_object` skips, contributing fillna(0) → APE
    100% on the eval side per ``feedback_penalize_incomplete``).
    """
    import json as _json

    import pandas as _pd

    from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
        _safe_float,
    )

    if y is None or not hasattr(y, "empty") or y.empty:
        return []
    y_grouped = (
        y.groupby(["ticker", "fiscal_year"])
        .apply(lambda g: dict(zip(g["field"], g["value"])))
        .to_dict()
    )
    fields_str = ", ".join(fitted_fields)
    pairs: list[tuple[str, str]] = []
    for _, row in X.iterrows():
        ticker = str(row.get("ticker", "?"))
        fy = row.get("fiscal_year", None)
        key = (ticker, fy)
        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
        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_dict: dict[str, Any] = {}
        for f in fitted_fields:
            v = gt_fields.get(f, None)
            if v is None or (isinstance(v, float) and _pd.isna(v)):
                resp_dict[f] = None
            else:
                try:
                    resp_dict[f] = round(float(v), 2)
                except (TypeError, ValueError):
                    resp_dict[f] = None
        resp = _json.dumps(resp_dict)
        pairs.append((instr, resp))
    return pairs


def _build_pooled_pairs(granularity: str) -> tuple[
    list[dict[str, str]], dict[str, int], dict[str, Any]
]:
    """Build the pooled SFT corpus across T1..T7 train splits.

    Each task's training set is rendered into ``(instruction, response)``
    pairs by the task-specific builders in :mod:`methods.llm_finetune`,
    except T3 and T6 which use :func:`_t3_t6_pairs_fixed` (this file)
    with a globally-fitted field list pooled from T3 + T6 train data;
    that fixes the documented train/predict prompt-field-list mismatch.

    Returns ``(rows, pair_counts_by_task, fitted_fields_meta)`` where
    ``fitted_fields_meta`` is the sidecar dict written next to the
    adapter for the eval path to load.
    """
    import numpy as np

    from projects.agent_builder.scripts.whatif_bench import macrolens as ml
    from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
        _t1_pairs, _t2_t5_pairs, _t4_pairs, _t7_pairs,
        _find_close_idx_from_array,
    )

    # ── Pre-load T3 + T6 train y to fit the global + per-ticker field lists ──
    t3_train = ml.load("T3", "train", granularity=granularity)
    t6_train = ml.load("T6", "train", granularity=granularity)

    import pandas as pd
    union_y = pd.concat(
        [df for df in (t3_train.y, t6_train.y)
         if df is not None and hasattr(df, "empty") and not df.empty],
        ignore_index=True,
    )
    if union_y.empty or "field" not in union_y.columns:
        raise RuntimeError("T3 + T6 train y is empty / lacks a 'field' column.")
    fitted_fields_global: list[str] = sorted(
        str(f) for f in union_y["field"].astype(str).unique()
    )
    fitted_fields_per_ticker: dict[str, list[str]] = {}
    for t, grp in union_y.groupby("ticker", sort=False):
        fitted_fields_per_ticker[str(t)] = sorted(
            str(f) for f in grp["field"].astype(str).unique()
        )
    logger.info(
        "T3+T6 fitted_fields_global has %d fields: %s",
        len(fitted_fields_global), fitted_fields_global,
    )

    rows: list[dict[str, str]] = []
    counts: dict[str, int] = {}
    for task in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"):
        if task == "T3":
            train = t3_train
        elif task == "T6":
            train = t6_train
        else:
            train = ml.load(task, "train", granularity=granularity)
        X, y = train.X, train.y
        if task == "T1":
            X_arr = np.asarray(X, dtype=np.float32)
            close_idx = _find_close_idx_from_array(X_arr)
            pairs = _t1_pairs(
                X_arr, np.asarray(y, dtype=np.float32), close_idx=close_idx,
            )
        elif task in ("T2", "T5"):
            pairs = _t2_t5_pairs(X, np.asarray(y, dtype=np.float64), task=task)
        elif task in ("T3", "T6"):
            # CORRECTNESS FIX: use the globally-fitted field list (not per-row
            # available fields) so training prompts match the eval-time
            # prompt format produced by ``_predict_t3_t6`` after we populate
            # ``_fitted_fields_global`` from our sidecar.
            pairs = _t3_t6_pairs_fixed(
                X, y, task=task, fitted_fields=fitted_fields_global,
            )
        elif task == "T4":
            pairs = _t4_pairs(X, np.asarray(y, dtype=np.float32))
        else:
            pairs = _t7_pairs(X, y)
        for instr, resp in pairs:
            rows.append({
                "prompt": f"### Instruction:\n{instr}\n\n### Response:\n",
                "completion": resp,
            })
        counts[task] = len(pairs)
        logger.info("built %d pairs for %s", len(pairs), task)

    fitted_fields_meta = {
        "fitted_fields_global": fitted_fields_global,
        "fitted_fields_per_ticker": fitted_fields_per_ticker,
        "granularity": granularity,
        "source": "T3 + T6 train y union",
    }
    return rows, counts, fitted_fields_meta


def _build_model_and_tokenizer(
    *, model_id: str, per_gpu_gib: int,
) -> tuple[Any, Any]:
    """Load the base LLM under bnb-NF4.

    Standard dense-Transformer path: ``AutoModelForCausalLM`` +
    ``device_map="auto"``. The naïve auto-dispatcher works correctly
    because bnb-NF4 quantises every ``nn.Linear`` in a vanilla dense
    decoder (no MoE-experts-stay-bf16 trap, no multimodal wrapper,
    no hybrid attention modules to special-case).
    """
    import torch
    from transformers import (
        AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,
    )

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

    n_vis = torch.cuda.device_count() if torch.cuda.is_available() else 0
    if n_vis < 1:
        raise RuntimeError("no CUDA devices visible to PyTorch.")
    max_memory = {i: f"{per_gpu_gib}GiB" for i in range(n_vis)}
    logger.info(
        "loading %s as AutoModelForCausalLM with bnb-NF4 (max_memory=%s)",
        model_id, max_memory,
    )

    model = AutoModelForCausalLM.from_pretrained(
        model_id,
        quantization_config=quant_config,
        device_map="auto",
        max_memory=max_memory,
        torch_dtype=torch.bfloat16,
        attn_implementation="eager",
    )
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    return model, tokenizer


def run(
    *,
    base_hf_id: str = "Qwen/Qwen2.5-7B-Instruct",
    granularity: str = "daily",
    seed: int = 42,
    output_dir: Path,
    per_gpu_gib: int = 36,
    max_length: int = 4096,
    smoke_only: bool = False,
) -> dict[str, Any]:
    """Train one Scout multi-task QLoRA adapter across T1..T7 pooled.

    Parameters
    ----------
    smoke_only
        When True, run ``max_steps=2`` instead of one full epoch, so the
        smoke pass verifies the load + LoRA-wrap + forward+backward +
        optimiser step path before committing to the full training
        wall-clock (~ 6-12 GPU-hours).
    """
    import torch
    from datasets import Dataset
    from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
    from trl import SFTConfig, SFTTrainer

    output_dir.mkdir(parents=True, exist_ok=True)

    # 1. Pool data
    t0 = time.perf_counter()
    rows, counts, fitted_fields_meta = _build_pooled_pairs(
        granularity=granularity,
    )
    if not rows:
        raise RuntimeError("empty pooled corpus.")
    pool_sec = time.perf_counter() - t0
    logger.info(
        "pooled %d pairs total (%s); pool build took %.1fs",
        len(rows), counts, pool_sec,
    )
    # Write the fitted-fields sidecar BEFORE training so the eval path
    # can populate ``_fitted_fields_per_ticker`` / ``_fitted_fields_global``
    # on the loaded :class:`methods.LLMFineTuned` instance (matching the
    # training prompts the adapter was tuned on).
    sidecar_path = output_dir / "fitted_fields.json"
    sidecar_path.write_text(json.dumps(fitted_fields_meta, indent=2))
    logger.info("wrote T3/T6 fitted-fields sidecar to %s", sidecar_path)

    # 2. Load model
    model, tokenizer = _build_model_and_tokenizer(
        model_id=base_hf_id, per_gpu_gib=per_gpu_gib,
    )

    # 3. Prepare for k-bit + apply LoRA
    model = prepare_model_for_kbit_training(
        model, use_gradient_checkpointing=True,
    )
    lora_cfg = LoraConfig(
        r=16,                                       # Meta's recipe
        lora_alpha=32,                              # Meta's recipe
        lora_dropout=0.0,                           # Meta's recipe
        target_modules=[
            "q_proj", "k_proj", "v_proj", "o_proj",
            "gate_proj", "up_proj", "down_proj",
        ],
        bias="none",
        task_type="CAUSAL_LM",
    )
    model = get_peft_model(model, lora_cfg)
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    total = sum(p.numel() for p in model.parameters())
    logger.info(
        "LoRA-adapted: %d trainable / %d total params (%.4f%%)",
        trainable, total, 100.0 * trainable / max(1, total),
    )

    # 4. Format dataset for completion_only_loss
    train_dataset = Dataset.from_list(rows)
    if seed is not None:
        train_dataset = train_dataset.shuffle(seed=seed)

    # 5. SFTConfig — Meta's hyperparameters verbatim
    sft_cfg = SFTConfig(
        output_dir=str(output_dir),
        num_train_epochs=1,                # Meta's recipe
        per_device_train_batch_size=2,     # Meta's recipe
        gradient_accumulation_steps=1,     # Meta's recipe
        learning_rate=2e-5,                # Meta's recipe
        lr_scheduler_type="cosine",
        warmup_steps=100,                  # Meta's recipe
        optim="adamw_torch",               # Meta uses AdamW (not paged_adamw_8bit)
        weight_decay=0.0,
        max_grad_norm=0.0,                 # Meta: clip_grad_norm: null -> disabled
        bf16=True,
        fp16=False,
        gradient_checkpointing=True,
        completion_only_loss=True,         # TRL 1.3 response-only loss
        max_length=max_length,             # T1 trajectories ~ 2000 tokens
        dataset_text_field=None,
        packing=False,
        save_strategy="epoch",
        save_total_limit=1,
        save_only_model=True,              # adapter checkpoints only
        logging_steps=10,
        report_to="none",
        seed=seed,
        max_steps=2 if smoke_only else -1,
    )

    trainer = SFTTrainer(
        model=model,
        args=sft_cfg,
        train_dataset=train_dataset,
        processing_class=tokenizer,
    )

    t1 = time.perf_counter()
    trainer.train()
    fit_sec = time.perf_counter() - t1
    logger.info("training done in %.1fs (smoke=%s)", fit_sec, smoke_only)

    # 6. Save adapter
    adapter_dir = output_dir / "adapter"
    tokenizer_dir = output_dir / "tokenizer"
    model.save_pretrained(str(adapter_dir))
    tokenizer.save_pretrained(str(tokenizer_dir))
    logger.info("adapter saved to %s", adapter_dir)

    return {
        "probe": "scout_qlora_multitask",
        "base_hf_id": base_hf_id,
        "granularity": granularity,
        "seed": seed,
        "pair_counts": counts,
        "pool_sec": pool_sec,
        "fit_sec": fit_sec,
        "smoke_only": smoke_only,
        "adapter_dir": str(adapter_dir),
        "tokenizer_dir": str(tokenizer_dir),
        "max_length": max_length,
        "fitted_fields_sidecar": str(sidecar_path),
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--base-hf-id",
        default="Qwen/Qwen2.5-7B-Instruct",
        help="HF model id of the base.",
    )
    parser.add_argument("--granularity", default="daily")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument(
        "--output-dir", type=Path,
        default=Path(__file__).resolve().parents[1] / "adapters" / "qwen25_7b_qlora_multitask",
    )
    parser.add_argument("--per-gpu-gib", type=int, default=36)
    parser.add_argument("--max-length", type=int, default=4096)
    parser.add_argument(
        "--smoke-only", action="store_true",
        help="Run max_steps=2 instead of a full epoch (verifies load + "
             "forward + backward + optimiser step in ~minutes).",
    )
    parser.add_argument(
        "--report-path", type=Path, default=None,
        help="JSON report path (default: <output_dir>/training_report.json).",
    )
    args = parser.parse_args()

    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s",
    )

    report = run(
        base_hf_id=args.base_hf_id,
        granularity=args.granularity,
        seed=args.seed,
        output_dir=args.output_dir,
        per_gpu_gib=args.per_gpu_gib,
        max_length=args.max_length,
        smoke_only=args.smoke_only,
    )
    report_path = args.report_path or (args.output_dir / "training_report.json")
    report_path.parent.mkdir(parents=True, exist_ok=True)
    report_path.write_text(json.dumps(report, indent=2, default=str))
    logger.info("report -> %s", report_path)
    return 0


if __name__ == "__main__":
    sys.exit(main())