| """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__) |
|
|
|
|
| |
|
|
|
|
| _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_T3_T6_FIELDS = ( |
| "Revenues", |
| "NetIncomeLoss", |
| "Assets", |
| "Liabilities", |
| "StockholdersEquity", |
| "OperatingIncomeLoss", |
| "CashAndCashEquivalents", |
| "PropertyPlantAndEquipmentNet", |
| "LongTermDebt", |
| "ResearchAndDevelopmentExpense", |
| ) |
|
|
|
|
| |
|
|
|
|
| _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 |
| |
| 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 |
| |
| 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): |
| 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 |
| 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() |
|
|
|
|
| |
|
|
|
|
| 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: |
| 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]] = [] |
| |
| 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) |
| |
| 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: |
| 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 |
|
|
|
|
| |
|
|
|
|
| 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]" |
| ) |
|
|
|
|
| |
|
|
|
|
| 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: |
| 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: |
| |
| 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: |
| |
| 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 |
| ] |
|
|
|
|
| |
|
|
|
|
| @register( |
| name="llm_finetuned", |
| family="llm_ft", |
| |
| |
| 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 |
| |
| |
| self.dry_run = bool(dry_run) or bool(getattr(config, "dry_run", False)) |
| |
| self._adapter_dir: pathlib.Path | None = None |
| self._tokenizer_dir: pathlib.Path | None = None |
| self._model: Any = None |
| self._tokenizer: Any = None |
| |
| |
| |
| self.engine: Any = engine |
| self._dry_engine: _DryRunFTEngine | None = ( |
| _DryRunFTEngine() if self.dry_run else None |
| ) |
| |
| self._t1_close_idx: int | None = None |
| self._t1_horizon: int = 21 |
| |
| |
| |
| self._fitted_fields_per_ticker: dict[str, list[str]] = {} |
| self._fitted_fields_global: list[str] = [] |
| self.last_predict_meta: dict[str, Any] = {} |
|
|
| |
|
|
| @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) |
| |
| |
| |
| if self.task == "T1" and isinstance(y, np.ndarray) and y.ndim == 2: |
| self._t1_horizon = int(y.shape[1]) |
| |
| |
| if self.task in ("T3", "T6"): |
| if isinstance(y, pd.DataFrame) and not y.empty and "field" in y.columns: |
| 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 |
|
|
| |
| 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 |
| |
| 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) |
|
|
| |
| |
| 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() |
|
|
| |
| |
| 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}") |
|
|
| |
|
|
| 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``). |
| """ |
| |
| |
| full_prompt = f"### Instruction:\n{prompt}\n\n### Response:\n" |
|
|
| |
| 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, |
| )) |
|
|
| |
| if self.dry_run: |
| assert self._dry_engine is not None |
| return self._dry_engine.generate(prompt) |
|
|
| |
| 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, |
| ) |
|
|
| |
|
|
| 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 |
| |
| |
| 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: |
| |
| 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"] |
| ) |
| |
| 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)) |
| |
| |
| 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") |
| |
| 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"] |
| ) |
|
|
| |
|
|
| 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: |
| |
| (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"] |
|
|