"""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: /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())