MacroLens / code /experiments /probes /llm_finetune_qwen.py
itouchz's picture
Duplicate from macrolens/MacroLens
ff4becd
Raw
History Blame Contribute Delete
17.1 kB
"""Qwen-3.5-27B QLoRA fine-tune driver for the deferred Family-7 slot.
Plan reference: Phase 3.1 (R1 Q1.3, R2 Q2.4, R3 W3.4 saturation, R5 W5.1;
author A2). T3 and T6 saturate near 100% MAPE for every zero-shot LLM
in the panel; they are the cleanest demonstration target for whether
MacroLens supports supervised LLM training. This driver populates the
single deferred Family-7 column in Tables 6-10.
Design choices (orthodox interpretation of the existing
:mod:`methods.llm_finetune` infrastructure):
* **Per-task adapters.** :class:`methods.LLMFineTuned` fixes ``self.task``
at construction and dispatches on it; we therefore train TWO adapters,
one for T3 and one for T6, rather than one bundled multi-task adapter.
Both tasks share the same JSON output schema (11 canonical XBRL
fields); the per-task split keeps the prompt format precisely matched
to each task. This is the simplest configuration that uses the
existing class as-is.
* **Cross-task transfer.** The T3 adapter is evaluated zero-shot on
T1 / T2 / T4 / T5 / T7 as a catastrophic-forgetting check: if a single
task's QLoRA pass leaves the model's competence on other tasks intact,
the result-table column can be populated end-to-end; otherwise the
cross-task entries become Family-7 / not-applicable.
* **Library defaults.** ``LLMFineTunedConfig`` ships with
``lora_r=16, lora_alpha=32, epochs=3, learning_rate=2e-4`` -- this
is what the panel-FT recipe was originally pre-registered to use. We
do not vary any of those four numbers in this driver, per the
no-tuning rule.
* **Single seed.** ``panel.PRIMARY_SEED = 42`` end-to-end.
Per-launch authorisation: this is a multi-hour GPU run (4 x A100-40GB,
GPU IDs 4-7 per project memory). The user must authorise the launch.
"""
from __future__ import annotations
import argparse
import json
import logging
import pickle
import time
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
import numpy as np
logger = logging.getLogger(__name__)
# Tasks evaluated by the trained adapters. Native-task targets are
# the rows that directly populate the Family-7 column; cross-task
# targets test for catastrophic forgetting.
_NATIVE_TASKS: tuple[str, ...] = ("T3", "T6")
_CROSS_TASKS: tuple[str, ...] = ("T1", "T2", "T4", "T5", "T7")
# Primary metric per task (mirrors gen_tables.py conventions).
_PRIMARY_METRIC: dict[str, str] = {
"T1": "mse",
"T2": "medape",
"T3": "mape",
"T4": "mae",
"T5": "medape",
"T6": "mape",
"T7": "mape",
}
_CLUSTER_KEY: dict[str, str] = {
"T1": "ticker",
"T2": "ticker",
"T3": "ticker",
"T4": "scenario_id",
"T5": "ticker",
"T6": "ticker",
"T7": "address",
}
@dataclass
class _EvalCell:
adapter_task: str
eval_task: str
is_native: bool
seed: int
n_test: int
primary_metric: str
value: float
ci_lo: float
ci_hi: float
fit_sec: float | None
predict_sec: float
def _cluster_keys(task: str, meta_test: Any) -> Any:
key = _CLUSTER_KEY[task]
if hasattr(meta_test, "columns") and key in meta_test.columns:
return meta_test[key].values
if hasattr(meta_test, "get"):
keys = meta_test.get(key)
if keys is not None:
return np.asarray(keys)
return None
def _save_predictions(
*,
pred_dir: Path,
method_id: str,
task: str,
seed: int,
granularity: str,
y_pred: Any,
y_test: Any,
meta_test: Any,
extra_tag: str | None = None,
) -> Path:
pred_dir.mkdir(parents=True, exist_ok=True)
tag = f"{method_id}_{task}_seed{seed}"
if extra_tag:
tag += f"_{extra_tag}"
out_path = pred_dir / f"{tag}.pkl"
tmp = out_path.with_suffix(".pkl.tmp")
with open(tmp, "wb") as f:
pickle.dump({
"method_id": method_id,
"task": task,
"seed": seed,
"granularity": granularity,
"y_pred": y_pred,
"y_test": y_test,
"meta_test": meta_test,
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
}, f)
tmp.replace(out_path)
return out_path
def _engine_for_adapter(
*, base_hf_id: str, adapter_path: Path, base_url: str, api_key: str,
) -> Any:
"""Build an OpenAI-compatible engine targeting the vLLM-served adapter.
The runner exposes the adapter as a LoRA module via:
vllm serve <base_hf_id> --enable-lora \\
--lora-modules adapter_qwen35_t3=<adapter_path>
so ``model_id`` resolves to the LoRA name, not the base HF id.
"""
from projects.agent_builder.scripts.whatif_bench.methods._openai_engine import (
OpenAIEngine,
)
return OpenAIEngine(
base_url=base_url, api_key=api_key,
model_id=str(adapter_path.name), # vLLM LoRA module id is the dir name
)
def train_adapter(
*,
task: str,
base_model: str = "qwen35",
granularity: str = "daily",
seed: int = 42,
adapter_dir: Path,
) -> tuple[Path, float]:
"""Train a single-task QLoRA adapter using :class:`LLMFineTuned`.
Returns ``(adapter_path, fit_sec)``.
"""
from projects.agent_builder.scripts.whatif_bench import macrolens as ml
from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
LLMFineTuned,
)
from projects.agent_builder.scripts.whatif_bench.methods._config import (
LLMFineTunedConfig,
)
train = ml.load(task, "train", granularity=granularity)
cfg = LLMFineTunedConfig() # library-default lora_r / lora_alpha / epochs / lr
model = LLMFineTuned(task=task, config=cfg, base_model=base_model)
t0 = time.perf_counter()
model.fit(train.X, train.y, seed=seed)
fit_sec = time.perf_counter() - t0
adapter_dir.mkdir(parents=True, exist_ok=True)
out_path = adapter_dir / f"qwen35_qlora_{task.lower()}"
model.save(out_path)
logger.info("trained %s adapter -> %s (fit %.1fs)", task, out_path, fit_sec)
return out_path, fit_sec
# [REVERTED 2026-05-19] An earlier in-session draft of
# ``train_multitask_adapter`` was inserted here but used
# ``device_map="auto"`` + bnb-4bit on Llama-4 Scout MoE, which
# RESEARCH_PLAN.md §5.1 + IMPLEMENTATION_PLAN.md §F7 explicitly call
# out as the documented "MoE-on-bitsandbytes complexity" failure mode
# (Scout needs ZeRO-2 across 4 GPUs, not naive auto-placement). The
# draft was reverted so the canonical sources (Llama-4 Scout HF card,
# Meta torchtune SFT example, HF PEFT MoE docs, TRL response-only-loss
# docs, DeepSpeed ZeRO-2 config) can be read end-to-end first and a
# verified recipe written rather than improvised.
def evaluate_with_adapter(
*,
adapter_path: Path,
adapter_task: str,
eval_task: str,
base_hf_id: str,
base_url: str,
api_key: str,
granularity: str,
seed: int,
pred_dir: Path,
fit_sec: float | None,
) -> _EvalCell:
"""Evaluate an adapter on ``eval_task``.
For native eval (``eval_task == adapter_task``) the predict path is
the task-native predict path on :class:`LLMFineTuned`. For cross-task
eval we still use :class:`LLMFineTuned` so the prompt formatting is
consistent with the panel's other LLM-FT cells; the adapter is
loaded fresh, then ``model.task`` is overridden to ``eval_task`` so
the right per-task predict path runs.
"""
from projects.agent_builder.scripts.whatif_bench import macrolens as ml
from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
LLMFineTuned,
)
engine = _engine_for_adapter(
base_hf_id=base_hf_id, adapter_path=adapter_path,
base_url=base_url, api_key=api_key,
)
test = ml.load(eval_task, "test", granularity=granularity)
model = LLMFineTuned.load(adapter_path)
# ``LLMFineTuned.load`` reconstructs at the trained-task. Force the
# task for cross-eval; the trained QLoRA adapter is unchanged.
model.task = eval_task
model.engine = engine
t1 = time.perf_counter()
y_pred = model.predict(test.X)
predict_sec = time.perf_counter() - t1
_save_predictions(
pred_dir=pred_dir,
method_id="llm_finetuned_qwen35",
task=eval_task,
seed=seed,
granularity=granularity,
y_pred=y_pred,
y_test=test.y,
meta_test=test.meta,
extra_tag=(
None if eval_task == adapter_task
else f"transfer_from_{adapter_task}"
),
)
metrics = ml.score(
eval_task, test.y, y_pred,
cluster_keys=_cluster_keys(eval_task, test.meta),
resample="cluster", n_boot="adaptive", seed=seed,
)
primary = _PRIMARY_METRIC[eval_task]
mv = metrics[primary]
value = float("nan") if mv.value is None else float(mv.value)
ci_lo = float("nan") if mv.ci_lo is None else float(mv.ci_lo)
ci_hi = float("nan") if mv.ci_hi is None else float(mv.ci_hi)
return _EvalCell(
adapter_task=adapter_task,
eval_task=eval_task,
is_native=(eval_task == adapter_task),
seed=seed,
n_test=int(len(test.y)) if hasattr(test.y, "__len__") else -1,
primary_metric=primary,
value=value,
ci_lo=ci_lo,
ci_hi=ci_hi,
fit_sec=fit_sec if eval_task == adapter_task else None,
predict_sec=predict_sec,
)
def run_pipeline(
*,
base_url: str | None,
api_key: str = "EMPTY",
base_model: str = "qwen35",
granularity: str = "daily",
seed: int | None = None,
adapter_dir: Path | None = None,
pred_dir: Path | None = None,
eval_native_only: bool = False,
train_only: bool = False,
multitask: bool = False,
) -> dict[str, Any]:
"""End-to-end pipeline: train (T3, T6) adapters then evaluate.
Two-pass: (i) train each native-task adapter; (ii) evaluate each
adapter on its native task plus the cross-task panel (T3 adapter
only, to keep the GPU budget bounded).
"""
from projects.agent_builder.scripts.whatif_bench.experiments import panel
from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
_BASE_MODEL_ID,
)
seed = seed if seed is not None else panel.PRIMARY_SEED
adapter_dir = adapter_dir or Path(__file__).resolve().parents[1] / "adapters"
pred_dir = pred_dir or Path(__file__).resolve().parents[1] / "predictions"
base_hf_id = _BASE_MODEL_ID.get(base_model)
if base_hf_id is None:
raise ValueError(f"unknown base_model {base_model!r}; "
f"expected one of {sorted(_BASE_MODEL_ID)}")
if multitask:
raise NotImplementedError(
"multitask=True was reverted on 2026-05-19 pending re-read of "
"Llama-4 Scout / DeepSpeed ZeRO-2 / PEFT-MoE primary sources. "
"See header comment near the reverted train_multitask_adapter "
"block."
)
# (i) Train adapters.
adapters: dict[str, tuple[Path, float]] = {}
multitask_pair_counts: dict[str, int] = {}
for task in _NATIVE_TASKS:
adapter_path, fit_sec = train_adapter(
task=task, base_model=base_model, granularity=granularity,
seed=seed, adapter_dir=adapter_dir,
)
adapters[task] = (adapter_path, fit_sec)
# Train-only short-circuit: skip the eval phase entirely. Used to
# separate the long-running QLoRA training step from the eval step,
# which requires a separately-orchestrated vLLM serve endpoint.
if train_only:
return {
"probe": "llm_finetune_scout_multitask" if multitask else "llm_finetune_qwen35",
"base_model": base_model,
"base_hf_id": base_hf_id,
"granularity": granularity,
"seed": seed,
"multitask": multitask,
"multitask_pair_counts": multitask_pair_counts,
"adapters": {
task: {"path": str(path), "fit_sec": fs}
for task, (path, fs) in adapters.items()
},
"cells": [],
"train_only": True,
}
if base_url is None:
raise ValueError(
"run_pipeline: --base-url required when --train-only is not set "
"(eval needs a vLLM serve endpoint serving the trained adapters)."
)
# (ii) Evaluate. Native-task eval per adapter; cross-task eval uses
# the T3 adapter only (T3 train is ~7x the size of T6 train and
# produces the more general checkpoint).
cells: list[_EvalCell] = []
for adapter_task, (adapter_path, fit_sec) in adapters.items():
cell = evaluate_with_adapter(
adapter_path=adapter_path, adapter_task=adapter_task,
eval_task=adapter_task, base_hf_id=base_hf_id,
base_url=base_url, api_key=api_key, granularity=granularity,
seed=seed, pred_dir=pred_dir, fit_sec=fit_sec,
)
cells.append(cell)
if not eval_native_only:
t3_path, _ = adapters["T3"]
for cross in _CROSS_TASKS:
try:
cell = evaluate_with_adapter(
adapter_path=t3_path, adapter_task="T3",
eval_task=cross, base_hf_id=base_hf_id,
base_url=base_url, api_key=api_key,
granularity=granularity, seed=seed,
pred_dir=pred_dir, fit_sec=None,
)
cells.append(cell)
except Exception as exc:
logger.exception("cross-task eval %s failed: %s", cross, exc)
cells.append(_EvalCell(
adapter_task="T3", eval_task=cross, is_native=False,
seed=seed, n_test=-1,
primary_metric=_PRIMARY_METRIC[cross],
value=float("nan"), ci_lo=float("nan"), ci_hi=float("nan"),
fit_sec=None, predict_sec=float("nan"),
))
return {
"probe": "llm_finetune_qwen35",
"base_model": base_model,
"base_hf_id": base_hf_id,
"base_url": base_url,
"granularity": granularity,
"seed": seed,
"adapters": {
task: {
"path": str(path),
"fit_sec": fs,
}
for task, (path, fs) in adapters.items()
},
"cells": [asdict(c) for c in cells],
}
def _default_probe_dir() -> Path:
# Probe outputs live under experiments/ (experiment artifacts),
# never under data_small_caps/ (raw + derived benchmark data).
return Path(__file__).resolve().parents[1] / "probes_output"
def main() -> int:
parser = argparse.ArgumentParser(
description="Qwen-3.5-27B QLoRA fine-tune driver (Phase 3.1).",
)
parser.add_argument("--base-url", default=None,
help="vLLM OpenAI-compatible endpoint (e.g., http://localhost:8004/v1). "
"Required unless --train-only is set.")
parser.add_argument("--api-key", default="EMPTY")
parser.add_argument("--base-model", default="qwen35",
choices=["llama_scout", "gemma4", "qwen35"])
parser.add_argument("--granularity", default="daily")
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--adapter-dir", type=Path, default=None)
parser.add_argument("--pred-dir", type=Path, default=None)
parser.add_argument("--eval-native-only", action="store_true",
help="Skip cross-task transfer eval (T1/T2/T4/T5/T7).")
parser.add_argument("--train-only", action="store_true",
help="Train adapters and exit; skip the eval phase "
"(which requires a vLLM serve endpoint).")
parser.add_argument("--multitask", action="store_true",
help="Train ONE adapter on a pooled corpus over all "
"7 task train splits (T1..T7). Default is the "
"per-task design (T3+T6 only with cross-task "
"eval). Recommended for Phase 3.1 Family-7.")
parser.add_argument("--output", type=Path, default=None,
help="Path to the summary JSON report.")
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
)
report = run_pipeline(
base_url=args.base_url, api_key=args.api_key,
base_model=args.base_model, granularity=args.granularity,
seed=args.seed, adapter_dir=args.adapter_dir,
pred_dir=args.pred_dir, eval_native_only=args.eval_native_only,
train_only=args.train_only, multitask=args.multitask,
)
out_path = args.output or _default_probe_dir() / "llm_finetune_qwen35.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(report, indent=2, default=str))
logger.info("fine-tune report written to %s", out_path)
return 0
if __name__ == "__main__":
raise SystemExit(main())