From 4dee24f1770f853209874a6803faf82453ee69ab Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Soomro Date: Sun, 29 Nov 2026 17:21:58 -0500 Subject: [PATCH] feat: evaluate Finance benchmarks with pinned data and overlap exclusions --- .github/workflows/ci.yml | 2 +- README.md | 2 + docs/causal-lm.md | 7 +- docs/finance-benchmarks.md | 110 ++++++++ docs/installation.md | 2 +- docs/metrics.md | 8 + docs/pitfalls.md | 3 +- .../configs/finance_benchmarks_clean.yaml | 52 ++++ .../finance_benchmarks_mistral_smoke.yaml | 54 ++++ .../configs/finance_benchmarks_smoke.yaml | 54 ++++ fltest/core/config.py | 36 ++- fltest/data/causal_lm.py | 32 ++- fltest/data/finance_benchmarks.py | 181 +++++++++++++ fltest/frameworks/flower/server.py | 9 +- fltest/metrics/__init__.py | 4 + fltest/metrics/causal_lm.py | 8 + fltest/pitfalls/checker.py | 2 +- fltest/testing/report.py | 21 ++ mkdocs.yml | 1 + tests/test_finance_benchmarks.py | 244 ++++++++++++++++++ 20 files changed, 821 insertions(+), 11 deletions(-) create mode 100644 docs/finance-benchmarks.md create mode 100644 examples/configs/finance_benchmarks_clean.yaml create mode 100644 examples/configs/finance_benchmarks_mistral_smoke.yaml create mode 100644 examples/configs/finance_benchmarks_smoke.yaml create mode 100644 fltest/data/finance_benchmarks.py create mode 100644 tests/test_finance_benchmarks.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 92d7c68..df2cbaa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,7 +57,7 @@ jobs: cache: pip # Exercise real adapter and full-model training without Hub downloads or GPUs. - run: pip install -e ".[lm,dev]" - - run: pytest tests/test_causal_lm.py tests/test_stackoverflow.py tests/test_medical.py tests/test_lm_protocol.py -q + - run: pytest tests/test_causal_lm.py tests/test_stackoverflow.py tests/test_medical.py tests/test_lm_protocol.py tests/test_finance_benchmarks.py -q docs: name: docs build diff --git a/README.md b/README.md index e307197..74dc3bb 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,8 @@ makes a rigorous setup the default and *checks* for the common pitfalls. - **Finance causal LMs:** pretrained models with 4-bit LoRA training on Flower, response-only loss, text poisoning, membership probes, and adapter defenses. See the [causal-LM guide](docs/causal-lm.md) for supported combinations and GPU setup. + Optional [Finance benchmarks](docs/finance-benchmarks.md) evaluate FPB, FIQA and + TFNS with pinned sources, training-overlap exclusions and scoring diagnostics. - **Stack Overflow next-token models:** full-model fine-tuning on user-partitioned Parquet data, held-out-user accuracy and perplexity, target-word backdoors, and user-level membership probes. See the [Stack Overflow guide](docs/stackoverflow.md). diff --git a/docs/causal-lm.md b/docs/causal-lm.md index 9b3908f..39f961b 100644 --- a/docs/causal-lm.md +++ b/docs/causal-lm.md @@ -76,6 +76,10 @@ local optimizer steps is controlled by `lm.local_steps`. ## Round learning rates and learning signal +For FPB, FIQA and TFNS evaluation, opt into `lm.finance_benchmarks` as described in +the [Finance benchmark guide](finance-benchmarks.md). Their metrics supplement the +FinGPT holdout, and benchmark-overlapping training records are excluded explicitly. + `client_lr` remains constant unless `lm.lr_schedule` is set. The optional `cosine_over_rounds` schedule uses `client_lr` as its maximum and `min_lr` as its minimum. Round 1 uses the maximum; the last training round uses the minimum, with @@ -102,7 +106,8 @@ warn when the absolute gain is below two percentage points. Findings appear in `extras.pitfalls` and terminal output; they do not mark training as failed. Set `lm.learning_gap.metric: loss` to check an absolute response/next-token loss reduction, adjust `min_improvement` for the evaluation, or set `enabled: false` to -disable this check. Runs with attacks or defenses are excluded. Medical accuracy +disable this check. With Finance benchmarks enabled, `metric: finance_benchmark_accuracy` +checks their unweighted mean instead. Runs with attacks or defenses are excluded. Medical accuracy uses PubMedQA while its loss uses held-out flashcards. See the [pitfall guide](pitfalls.md) for rechecking saved reports. A short smoke run and this heuristic cannot establish benchmark quality or statistical significance. diff --git a/docs/finance-benchmarks.md b/docs/finance-benchmarks.md new file mode 100644 index 0000000..41a763d --- /dev/null +++ b/docs/finance-benchmarks.md @@ -0,0 +1,110 @@ +# Finance benchmark evaluation + +Set `lm.finance_benchmarks` on a Finance causal-LM run to evaluate FPB, FIQA and +TFNS at round 0 and after each training round. This supplements the existing +FinGPT holdout: `accuracy` and `loss` keep their original meanings. Existing +configurations without the new block retain their training data and run identities. + +Start with `finance_benchmarks_smoke.yaml` on SmolLM2-135M-Instruct, then +`finance_benchmarks_mistral_smoke.yaml` on Mistral-7B-Instruct-v0.3. Each uses two +clients, two rounds, four examples per benchmark and a 16-new-token cap. These are +integration checks. `finance_benchmarks_clean.yaml` provides the planned 50-client, +10-participant, 15-round Mistral baseline with ten local steps, batch 16, sequence +limit 512, a cosine learning-rate schedule, and complete benchmark evaluation. +It must be timed against the available reservation before running the full baseline. + +```bash +FLTEST_RAY_ADDRESS=10.0.1.1:6379 fltest run examples/configs/finance_benchmarks_smoke.yaml +``` + +Use the environment and two-node Ray instructions in the [causal-LM guide](causal-lm.md). +Models must be cached on each worker; benchmark files are needed only on the driver. + +## Source and split protocol + +The implementation follows the dataset selection, prompts and three-class scorer +in [FlowerTune's Finance evaluation code](https://github.com/flwrlabs/flower/tree/5d659b1bd0f805c76fe180e7ed5ef43242b7fa9f/benchmarks/flowertune-llm/evaluation/finance). +The source commit is recorded in each benchmark's metadata. The loader downloads +data files directly and executes no remote dataset script. + +| Benchmark | Pinned source | Evaluation selection | Full evaluation rows | +|---|---|---|---| +| FPB | `takala/financial_phrasebank`, `sentences_50agree` from the original ZIP | `train_test_split(test_size=0.25, seed=42)['test']` | 1,212 | +| FIQA | `pauri32/fiqa-2018` CSV files | concatenate train, validation, test in that order; take the same seeded 25% test split | 304 | +| TFNS | `zeroshot/twitter-financial-news-sentiment` | original validation file, unchanged order | 2,388 | + +FPB uses negative/neutral/positive labels. TFNS's numeric mapping differs: 0 is +negative, 1 positive and 2 neutral. FIQA scores below -0.1 are negative, scores +from -0.1 up to but excluding 0.1 are neutral, and scores at least 0.1 are positive. +FIQA `post` records request tweet sentiment; other records request news sentiment. +The evaluation seed is fixed at 42 independently of the FL training seed. + +Metadata records source commit revisions, file SHA256 hashes, source/evaluation +counts, stable row IDs, selected-content hashes and the full evaluation-ID digest. +FPB row IDs refer to line indices in the named Latin-1 ZIP member. FIQA IDs include +their original split and row index. TFNS IDs refer to validation row indices. +FPB's source license is CC BY-NC-SA 3.0; retain its attribution and license when +redistributing source data. Cached datasets stay under the ignored data directory. + +## Training overlap + +The pinned benchmark sets contain normalized exact text matches in the FinGPT +source. When enabled, the loader removes every matching group from the candidate +training pool before capping and IID sharding. All copies of a matching +input are removed, retaining original source-row IDs for all remaining records. +Seeded shuffling precedes filtering so the FinGPT holdout split, ordering and cap +remain unchanged when enabling benchmark evaluation. Reports include excluded training +row IDs, the pre-exclusion count and the exclusion definition. + +Exclusions use the full evaluation sets even for capped smokes, so increasing an +evaluation cap does not change the training pool. Normalization uses NFKC, case +folding and collapsed whitespace. This protects the current fine-tuning data from +these exact overlaps; it does not establish independence from model pretraining +or detect paraphrases. Excluding overlaps is a recorded difference from the +reference training corpus and should be reported in benchmark comparisons. + +## Generation and scoring + +Prompts have the literal form `Instruction: ...`, `Input: ...`, `Answer: ` rather +than the FinGPT chat template. Default generation is single-example greedy decoding +with a total prompt-plus-output budget of 512 tokens. It uses the existing pad/EOS +token and cache, without resizing the model vocabulary. Overlong prompts fail with +their benchmark ID rather than being silently truncated. Setting `max_new_tokens` +adds an optional output cap within the total budget. + +For comparability, the reference score decodes the complete sequence, extracts +text after the first `Answer: ` marker, and looks for `positive` or `Positive` +first, then `negative` or `Negative`, otherwise choosing neutral. Thus malformed +answers can receive neutral credit, and an answer mentioning both positive and +negative can receive positive credit. Reports retain the extracted response, +actual generated completion, permissive prediction and strict parsed polarity. + +`fpb_accuracy`, `fiqa_accuracy` and `tfns_accuracy` use that reference scorer. +`finance_benchmark_accuracy` is their unweighted mean, not a pooled per-record +accuracy. Each benchmark additionally reports strict accuracy, label parse rate, +evaluation count and its gap from round 0. Raw benchmark predictions are stored +separately under each history entry's `finance_benchmark_predictions`. + +The metadata lists deviations: single-example greedy decoding, avoiding the +reference evaluator's new padding embedding, training-overlap exclusions, any +subset/output cap, and any total-token budget differing from 512. These diagnostics +do not replace the reference score or certify leaderboard parity. Full benchmark +scores and strict diagnostics should be reviewed together. + +```yaml +lm: + finance_benchmarks: + max_samples_per_benchmark: null # full evaluation sets + max_total_tokens: 512 + max_new_tokens: null # use the remaining total-token budget + learning_gap: + metric: finance_benchmark_accuracy + min_improvement: 0.02 +metrics: [accuracy, loss, fpb_accuracy, fiqa_accuracy, tfns_accuracy, finance_benchmark_accuracy] +``` + +Merge this into the existing `lm` block. Omitting `finance_benchmarks` disables the +extra datasets. Raising `max_test_data_size` changes only the FinGPT holdout cap; +`max_samples_per_benchmark` controls each separate benchmark. Full sets are the +default, while the smoke examples cap them explicitly. Short smokes do not establish +model quality, learning significance or attack/defense effectiveness. diff --git a/docs/installation.md b/docs/installation.md index da5eccc..b2d6091 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -56,7 +56,7 @@ fltest list # Frameworks: ['flare', 'flower', 'flwr', 'nvflare', 'reference'] # Attacks: ['backdoor', 'dlg', 'gaussian', 'label_flip', 'membership_inference', 'model_replacement', 'sign_flip'] # Defenses: ['fldetector', 'gradient_noise', 'krum', 'median', 'mpc_aggregation', 'norm_clip', 'secure_aggregation', 'trimmed_mean'] -# Metrics: ['accuracy', 'detection', 'loss', 'next_token_accuracy', 'per_client', 'perplexity', 'pubmedqa_accuracy'] +# Metrics: ['accuracy', 'detection', 'finance_benchmark_accuracy', 'fiqa_accuracy', 'fpb_accuracy', 'loss', 'next_token_accuracy', 'per_client', 'perplexity', 'pubmedqa_accuracy', 'tfns_accuracy'] pytest tests/ -q # 110 passing ``` diff --git a/docs/metrics.md b/docs/metrics.md index 0b83360..0083436 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -15,6 +15,14 @@ instead measures token-weighted response-only cross-entropy on held-out flashcar Both datasets remain fixed through round 0 and all trained rounds. Reports include the accuracy gap and loss reduction relative to the zero-shot baseline. +The optional [Finance benchmarks](finance-benchmarks.md) add `fpb_accuracy`, +`fiqa_accuracy`, and `tfns_accuracy`, with `finance_benchmark_accuracy` as their +unweighted mean. These preserve FlowerTune's permissive substring scorer and +neutral fallback. Each benchmark also records `*_strict_accuracy`, +`*_label_parse_rate`, `*_evaluation_samples`, and `*_zero_shot_gap` to make +invalid outputs, subset sizes and changes from round 0 visible. Finance `accuracy` +and `loss` continue to use the separate FinGPT holdout. + ## Always measured (every backend, every round) Computed by evaluating the **global model on the central test set** after each round: diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 8fa6856..19e567f 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -34,7 +34,8 @@ runs and missing/nonfinite evidence do not produce a small-gap finding. Defaults use `accuracy` and a minimum absolute improvement of `0.02` (two percentage points). Configure `lm.learning_gap` with `enabled`, `metric` (`accuracy` or `loss`), -and `min_improvement`. Accuracy is higher-is-better; loss is lower-is-better, with +and `min_improvement`. With Finance benchmarks enabled, `finance_benchmark_accuracy` +can check their mean. Accuracy is higher-is-better; loss is lower-is-better, with the threshold expressed in absolute cross-entropy units. This heuristic is not a statistical significance test. To check an existing report without retraining: diff --git a/examples/configs/finance_benchmarks_clean.yaml b/examples/configs/finance_benchmarks_clean.yaml new file mode 100644 index 0000000..c387d3d --- /dev/null +++ b/examples/configs/finance_benchmarks_clean.yaml @@ -0,0 +1,52 @@ +# Full clean baseline: time before launching. +name: finance_benchmarks_clean +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:mistralai/Mistral-7B-Instruct-v0.3 +seed: 786 +device: cuda +total_cpus: 12 +total_gpus: 2 +num_clients: 50 +dataset_partitions: 50 +clients_per_round: 10 +num_rounds: 15 +client_batch_size: 16 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 1 +max_test_data_size: 512 +client_resources: + num_cpus: 6 + num_gpus: 1 +lm: + model_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + tokenizer_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 512 + local_steps: 10 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: null + checkpoint_dir: reports/adapters + lr_schedule: + name: cosine_over_rounds + min_lr: 1.0e-06 + learning_gap: + metric: finance_benchmark_accuracy + min_improvement: 0.02 + finance_benchmarks: {} +metrics: +- accuracy +- loss +- fpb_accuracy +- fiqa_accuracy +- tfns_accuracy +- finance_benchmark_accuracy +runs: +- framework: flwr + name: clean diff --git a/examples/configs/finance_benchmarks_mistral_smoke.yaml b/examples/configs/finance_benchmarks_mistral_smoke.yaml new file mode 100644 index 0000000..31a6be3 --- /dev/null +++ b/examples/configs/finance_benchmarks_mistral_smoke.yaml @@ -0,0 +1,54 @@ +# Benchmark integration smoke, not a model-quality result. +name: finance_benchmarks_mistral_smoke +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:mistralai/Mistral-7B-Instruct-v0.3 +seed: 786 +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 2 +dataset_partitions: 2 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 16 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 1 +max_test_data_size: 4 +client_resources: + num_cpus: 2 + num_gpus: 1 +lm: + model_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + tokenizer_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 512 + local_steps: 2 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters + lr_schedule: + name: cosine_over_rounds + min_lr: 1.0e-06 + learning_gap: + metric: finance_benchmark_accuracy + min_improvement: 0.02 + finance_benchmarks: + max_samples_per_benchmark: 4 + max_new_tokens: 16 +metrics: +- accuracy +- loss +- fpb_accuracy +- fiqa_accuracy +- tfns_accuracy +- finance_benchmark_accuracy +runs: +- framework: flwr + name: clean diff --git a/examples/configs/finance_benchmarks_smoke.yaml b/examples/configs/finance_benchmarks_smoke.yaml new file mode 100644 index 0000000..cf5eedf --- /dev/null +++ b/examples/configs/finance_benchmarks_smoke.yaml @@ -0,0 +1,54 @@ +# Benchmark integration smoke, not a model-quality result. +name: finance_benchmarks_smoke +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +seed: 786 +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 2 +dataset_partitions: 2 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 2 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 4 +max_test_data_size: 4 +client_resources: + num_cpus: 2 + num_gpus: 1 +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 256 + local_steps: 2 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters + lr_schedule: + name: cosine_over_rounds + min_lr: 1.0e-06 + learning_gap: + metric: finance_benchmark_accuracy + min_improvement: 0.02 + finance_benchmarks: + max_samples_per_benchmark: 4 + max_new_tokens: 16 +metrics: +- accuracy +- loss +- fpb_accuracy +- fiqa_accuracy +- tfns_accuracy +- finance_benchmark_accuracy +runs: +- framework: flwr + name: clean diff --git a/fltest/core/config.py b/fltest/core/config.py index 8e9572e..1bbbd6e 100644 --- a/fltest/core/config.py +++ b/fltest/core/config.py @@ -51,6 +51,25 @@ class MedicalConfig(BaseModel): model_config = {"extra": "forbid"} +class FinanceBenchmarkConfig(BaseModel): + fpb_revision: str = "8d3fe0c36d5feec6b3cc5e455b0fcb4820fb9964" + fiqa_revision: str = "74b7dd5d4fc61e0fa5d979bef2c53111ea69c58a" + tfns_revision: str = "ccbe24de388e287beb92dd393a335c376b350ac3" + max_samples_per_benchmark: Optional[int] = Field(default=None, gt=0) + max_total_tokens: int = Field(default=512, ge=16) + max_new_tokens: Optional[int] = Field(default=None, gt=0) + + model_config = {"extra": "forbid"} + + @model_validator(mode="after") + def validate_generation(self): + if self.max_new_tokens is not None and self.max_new_tokens >= self.max_total_tokens: + raise ValueError("max_new_tokens must leave room for the benchmark prompt") + if any(not value.strip() for value in (self.fpb_revision, self.fiqa_revision, self.tfns_revision)): + raise ValueError("Finance benchmark revisions must be nonempty") + return self + + class CosineRoundSchedule(BaseModel): name: Literal["cosine_over_rounds"] = "cosine_over_rounds" min_lr: float = Field(default=1e-6, ge=0, allow_inf_nan=False) @@ -60,14 +79,14 @@ class CosineRoundSchedule(BaseModel): class LearningGapConfig(BaseModel): enabled: bool = True - metric: Literal["accuracy", "loss"] = "accuracy" + metric: Literal["accuracy", "loss", "finance_benchmark_accuracy"] = "accuracy" min_improvement: float = Field(default=0.02, ge=0, allow_inf_nan=False) model_config = {"extra": "forbid"} @model_validator(mode="after") def validate_threshold(self): - if self.metric == "accuracy" and self.min_improvement > 1: + if self.metric != "loss" and self.min_improvement > 1: raise ValueError("Accuracy min_improvement must be a fraction in [0, 1]") return self @@ -96,6 +115,7 @@ class CausalLMConfig(BaseModel): attn_implementation: Literal["eager", "sdpa"] = "eager" lr_schedule: Optional[CosineRoundSchedule] = None learning_gap: LearningGapConfig = Field(default_factory=LearningGapConfig) + finance_benchmarks: Optional[FinanceBenchmarkConfig] = None model_config = {"extra": "forbid"} @@ -118,6 +138,8 @@ def run_settings(self): values.pop("lr_schedule") if self.learning_gap == LearningGapConfig(): values.pop("learning_gap") + if self.finance_benchmarks is None: + values.pop("finance_benchmarks") return values @@ -259,7 +281,8 @@ def validate_task(self): if self.task != "causal_lm": if self.lm is not None: raise ValueError("lm settings require task: causal_lm") - if set(self.metrics) & {"next_token_accuracy", "perplexity", "pubmedqa_accuracy"}: + if set(self.metrics) & {"next_token_accuracy", "perplexity", "pubmedqa_accuracy", "fpb_accuracy", + "fiqa_accuracy", "tfns_accuracy", "finance_benchmark_accuracy"}: raise ValueError("LM task metrics require their corresponding causal_lm application") return self if self.lm is None: @@ -273,6 +296,11 @@ def validate_task(self): raise ValueError("causal_lm supports flwrlabs/fingpt-sentiment-train, medical flashcards, or stackoverflow") if not self.model_name.startswith("hf:"): raise ValueError("causal_lm requires a pretrained model_name starting with hf:") + if self.lm.finance_benchmarks is not None and not finance: + raise ValueError("lm.finance_benchmarks requires the Finance dataset") + if (self.lm.learning_gap.metric == "finance_benchmark_accuracy" + and self.lm.finance_benchmarks is None): + raise ValueError("finance_benchmark_accuracy learning gaps require lm.finance_benchmarks") if finance or medical: application = "Medical" if medical else "Finance" if self.data_distribution != "iid" or self.dataset_partitions != self.num_clients: @@ -327,6 +355,8 @@ def _validate_lm_plugins(self): allowed_metrics |= {"next_token_accuracy", "perplexity"} if medical: allowed_metrics.add("pubmedqa_accuracy") + if self.lm.finance_benchmarks is not None: + allowed_metrics |= {"fpb_accuracy", "fiqa_accuracy", "tfns_accuracy", "finance_benchmark_accuracy"} if set(self.metrics) - allowed_metrics: raise ValueError(f"Unsupported causal_lm metrics; choose from {sorted(allowed_metrics)}") allowed = { diff --git a/fltest/data/causal_lm.py b/fltest/data/causal_lm.py index 3287b5a..3519219 100644 --- a/fltest/data/causal_lm.py +++ b/fltest/data/causal_lm.py @@ -151,12 +151,23 @@ def prepare_finance_data(spec): (dict(row, source_id=i) for i, row in enumerate(raw)), spec.lm.holdout_fraction, spec.seed, ) + # Preserve the original holdout order/cap when benchmark exclusions are enabled. rng = random.Random(spec.seed) rng.shuffle(train) rng.shuffle(heldout) + benchmark_data, benchmark_metadata, tokenizer = None, None, None + excluded, train_before_exclusion = [], len(train) + if spec.lm.finance_benchmarks is not None: + from fltest.data.finance_benchmarks import prepare_finance_benchmarks + + tokenizer = load_tokenizer(spec) + benchmark_data, benchmark_metadata, groups = prepare_finance_benchmarks(spec, tokenizer) + benchmark_inputs = set().union(*groups.values()) + excluded = sorted(row['source_id'] for row in train if normalize_text(row['input']) in benchmark_inputs) + train = [row for row in train if normalize_text(row['input']) not in benchmark_inputs] if len(train) < spec.num_clients: raise ValueError("Finance training split has fewer examples than clients") - tokenizer = load_tokenizer(spec) + tokenizer = tokenizer or load_tokenizer(spec) collator = LMCollator(tokenizer.pad_token_id) loaders = {} for cid in range(spec.num_clients): @@ -176,7 +187,7 @@ def prepare_finance_data(spec): split_digest = hashlib.sha256( json.dumps(sorted({normalize_text(row["input"]) for row in heldout})).encode() ).hexdigest() - return { + result = { "c2loader": loaders, "test_loader": test_loader, "metadata": { "model_revision": spec.lm.model_revision, @@ -193,6 +204,15 @@ def prepare_finance_data(spec): "sample_id_definition": "row index in the pinned source dataset train split", }, } + if benchmark_data is not None: + test_loader.finance_benchmarks = benchmark_data + result['metadata'].update( + finance_benchmarks=benchmark_metadata, + train_rows_before_benchmark_exclusion=train_before_exclusion, + excluded_benchmark_train_row_ids=excluded, + benchmark_training_exclusion='NFKC/casefold/whitespace-normalized exact input groups from all full benchmark evaluation sets', + ) + return result def get_causal_model(spec): @@ -459,6 +479,14 @@ def evaluate_causal_model(model, loader, spec, details=None): metrics={"exact_match": exact_matches / examples, "label_parse_rate": parsed / examples}, predictions=predictions, ) + if spec.lm.finance_benchmarks is not None and details is not None: + from fltest.data.finance_benchmarks import evaluate_finance_benchmarks + + metrics, benchmark_predictions = evaluate_finance_benchmarks( + model, tokenizer, loader.finance_benchmarks, spec, + ) + details['metrics'].update(metrics) + details['benchmark_predictions'] = benchmark_predictions return total_loss / total_tokens, correct / examples diff --git a/fltest/data/finance_benchmarks.py b/fltest/data/finance_benchmarks.py new file mode 100644 index 0000000..ba3dc69 --- /dev/null +++ b/fltest/data/finance_benchmarks.py @@ -0,0 +1,181 @@ +"""Pinned FlowerTune Finance datasets, evaluation splits, prompts and diagnostics.""" + +import csv +import hashlib +import json +import math +from pathlib import Path +import re +import zipfile + +import torch + +from fltest.data.causal_lm import _autocast, finance_response_label, normalize_text + +FLOWERTUNE_REVISION = "5d659b1bd0f805c76fe180e7ed5ef43242b7fa9f" +SOURCES = { + "fpb": ("takala/financial_phrasebank", ["data/FinancialPhraseBank-v1.0.zip"]), + "fiqa": ("pauri32/fiqa-2018", ["train.csv", "validation.csv", "test.csv"]), + "tfns": ("zeroshot/twitter-financial-news-sentiment", ["sent_valid.csv"]), +} + + +def benchmark_instruction(kind): + return f"What is the sentiment of this {kind}? Please choose an answer from {{negative/neutral/positive}}." + + +def benchmark_prompt(row): + return f"Instruction: {row['instruction']}\nInput: {row['input']}\nAnswer: " + + +def fiqa_label(score): + value = float(score) + if not math.isfinite(value): + raise ValueError("FIQA sentiment scores must be finite") + return "negative" if value < -.1 else "neutral" if value < .1 else "positive" + + +def benchmark_label(response): + # Preserve upstream's positive-first, case-sensitive matching and neutral fallback. + if "positive" in response or "Positive" in response: + return "positive" + if "negative" in response or "Negative" in response: + return "negative" + return "neutral" + + +def strict_polarity(response): + label = finance_response_label(response) + if label is None: + return None + return "positive" if label.endswith("positive") else "negative" if label.endswith("negative") else "neutral" + + +def read_benchmark_source(name, paths): + rows = [] + if name == "fpb": + with zipfile.ZipFile(paths[0]) as archive: + # Read a named member in memory; do not extract executable archive contents. + text = archive.read("FinancialPhraseBank-v1.0/Sentences_50Agree.txt").decode("iso-8859-1") + for index, line in enumerate(text.splitlines()): + sentence, label = line.rsplit("@", 1) + rows.append({"id": f"train:{index}", "input": sentence, "target": label.strip(), + "instruction": benchmark_instruction("news")}) + elif name == "fiqa": + for split, path in zip(("train", "validation", "test"), paths): + with open(path, encoding="utf-8-sig", newline="") as stream: + for index, row in enumerate(csv.DictReader(stream)): + rows.append({"id": f"{split}:{index}", "input": row["sentence"], + "target": fiqa_label(row["sentiment_score"]), + "instruction": benchmark_instruction("tweet" if row["format"] == "post" else "news")}) + elif name == "tfns": + labels = {0: "negative", 1: "positive", 2: "neutral"} + with open(paths[0], encoding="utf-8-sig", newline="") as stream: + for index, row in enumerate(csv.DictReader(stream)): + rows.append({"id": f"validation:{index}", "input": row["text"], + "target": labels[int(row["label"])], "instruction": benchmark_instruction("tweet")}) + else: + raise ValueError(f"Unknown Finance benchmark: {name}") + if not rows or any(not row["input"].strip() or row["target"] not in ("negative", "neutral", "positive") for row in rows): + raise ValueError(f"Invalid or empty {name} benchmark records") + return rows + + +def official_evaluation_rows(name, rows): + if name == "tfns": + return list(rows) + from datasets import Dataset + + return Dataset.from_list(rows).train_test_split(test_size=.25, seed=42)["test"].to_list() + + +def prepare_finance_benchmarks(spec, tokenizer): + from huggingface_hub import HfApi, hf_hub_download + + opts = spec.lm.finance_benchmarks + prepared, metadata, groups = {}, {}, {} + for name, (repo, files) in SOURCES.items(): + revision = getattr(opts, name + "_revision") + if not re.fullmatch(r"[0-9a-f]{40}", revision): + revision = HfApi().dataset_info(repo, revision=revision).sha + setattr(opts, name + "_revision", revision) + paths = [hf_hub_download(repo, file, repo_type="dataset", revision=revision, + cache_dir=spec.dataset_cache_path) for file in files] + source = read_benchmark_source(name, paths) + evaluation = official_evaluation_rows(name, source) + # Exclude the full evaluation group set even when the smoke scores only a subset. + groups[name] = {normalize_text(row["input"]) for row in evaluation} + selected = evaluation[:opts.max_samples_per_benchmark] if opts.max_samples_per_benchmark else evaluation + encoded = [] + for row in selected: + prompt = benchmark_prompt(row) + tokens = tokenizer.encode(prompt, add_special_tokens=True) + if not tokens or len(tokens) >= opts.max_total_tokens: + raise ValueError(f"{name} {row['id']}: benchmark prompt must fit below max_total_tokens; prompts are not silently truncated") + budget = opts.max_total_tokens - len(tokens) + if opts.max_new_tokens is not None: + budget = min(budget, opts.max_new_tokens) + encoded.append({"id": row["id"], "target": row["target"], "prompt_ids": tokens, + "max_new_tokens": budget}) + prepared[name] = encoded + deviations = ["single-example greedy generation", "existing pad token without vocabulary resizing", + "exact normalized benchmark groups excluded from the training pool"] + if len(selected) != len(evaluation): + deviations.append("capped evaluation subset") + if opts.max_new_tokens is not None: + deviations.append("explicit new-token generation cap") + if opts.max_total_tokens != 512: + deviations.append("total-token budget differs from upstream 512") + metadata[name] = { + "dataset": repo, "revision": revision, "source_files": files, + "source_files_sha256": {file: hashlib.sha256(Path(path).read_bytes()).hexdigest() + for file, path in zip(files, paths)}, + "source_rows": len(source), "full_evaluation_rows": len(evaluation), "evaluation_rows": len(encoded), + "evaluation_ids": [row["id"] for row in encoded], + "full_evaluation_ids_sha256": hashlib.sha256(json.dumps([row['id'] for row in evaluation]).encode()).hexdigest(), + "evaluation_content_sha256": hashlib.sha256(json.dumps(selected, sort_keys=True).encode()).hexdigest(), + "split": "validation" if name == "tfns" else "test_size=0.25, seed=42", + "source_split_order": ["validation"] if name == "tfns" else ["train"] if name == "fpb" else ["train", "validation", "test"], + "max_total_tokens": opts.max_total_tokens, "max_new_tokens": opts.max_new_tokens, + "prompt_source": f"flwrlabs/flower@{FLOWERTUNE_REVISION}:benchmarks/flowertune-llm/evaluation/finance", + "scoring": "upstream positive-first substring matching, otherwise negative, otherwise neutral", + "deviations": deviations, + } + return prepared, metadata, groups + + +@torch.no_grad() +def evaluate_finance_benchmarks(model, tokenizer, prepared, spec): + if set(prepared) != set(SOURCES): + raise ValueError("The Finance benchmark mean requires FPB, FIQA and TFNS") + model.eval() + metrics, predictions = {}, {} + for name, rows in prepared.items(): + records = [] + for row in rows: + inputs = torch.tensor([row["prompt_ids"]], device=spec.device) + with _autocast(spec): + generated = model.generate( + input_ids=inputs, attention_mask=torch.ones_like(inputs), + max_new_tokens=row["max_new_tokens"], do_sample=False, num_beams=1, + use_cache=True, + pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, + ) + # Reproduce the reference evaluator's first 'Answer: ' extraction. + decoded = tokenizer.decode(generated[0], skip_special_tokens=True) + pieces = decoded.split("Answer: ") + response = pieces[1] if len(pieces) > 1 else "None" + completion = tokenizer.decode(generated[0, len(row["prompt_ids"]):], skip_special_tokens=True) + records.append({"id": row["id"], "target": row["target"], "response": response, + "generated_completion": completion, "predicted_label": benchmark_label(response), + "strict_predicted_label": strict_polarity(completion), + "generation_budget": row["max_new_tokens"]}) + if not records: + raise ValueError(f"Empty {name} evaluation") + metrics[name + "_accuracy"] = sum(r['predicted_label'] == r['target'] for r in records) / len(records) + metrics[name + "_strict_accuracy"] = sum(r['strict_predicted_label'] == r['target'] for r in records) / len(records) + metrics[name + "_label_parse_rate"] = sum(r['strict_predicted_label'] is not None for r in records) / len(records) + metrics[name + "_evaluation_samples"] = len(records) + predictions[name] = records + metrics["finance_benchmark_accuracy"] = sum(metrics[name + "_accuracy"] for name in SOURCES) / 3 + return metrics, predictions diff --git a/fltest/frameworks/flower/server.py b/fltest/frameworks/flower/server.py index 19a160e..3e6370b 100644 --- a/fltest/frameworks/flower/server.py +++ b/fltest/frameworks/flower/server.py @@ -224,8 +224,13 @@ def evaluate_fn(server_round, parameters, config): metrics.update(strategy._last_fit_metrics) metrics.update(strategy._last_server_metrics) metrics["zero_shot_gap"] = acc - history[0]["accuracy"] - if spec.dataset == "stackoverflow" or spec.lm.medical is not None: + if (spec.dataset == "stackoverflow" or spec.lm.medical is not None + or spec.lm.finance_benchmarks is not None): metrics["zero_shot_loss_reduction"] = history[0]["loss"] - loss + if spec.lm.finance_benchmarks is not None: + for name in ('fpb', 'fiqa', 'tfns', 'finance_benchmark'): + key = name + '_accuracy' + metrics[name + '_zero_shot_gap'] = metrics[key] - history[0][key] ctx = HookContext( cfg=spec, framework="flwr", run_name=spec.run_name, round=server_round, global_state=parameters, model=net, test_data=test_loader, @@ -236,6 +241,8 @@ def evaluate_fn(server_round, parameters, config): history[server_round]["predictions"] = details["predictions"] if "user_metrics" in details: history[server_round]["heldout_user_metrics"] = details["user_metrics"] + if "benchmark_predictions" in details: + history[server_round]['finance_benchmark_predictions'] = details['benchmark_predictions'] if server_round == spec.num_rounds: state_holder["checkpoint"] = save_adapter_checkpoint( net, spec, state_holder["data_metadata"] diff --git a/fltest/metrics/__init__.py b/fltest/metrics/__init__.py index c9fcc4e..38c794b 100644 --- a/fltest/metrics/__init__.py +++ b/fltest/metrics/__init__.py @@ -18,6 +18,10 @@ "next_token_accuracy": "fltest.metrics.causal_lm", "perplexity": "fltest.metrics.causal_lm", "pubmedqa_accuracy": "fltest.metrics.causal_lm", + "fpb_accuracy": "fltest.metrics.causal_lm", + "fiqa_accuracy": "fltest.metrics.causal_lm", + "tfns_accuracy": "fltest.metrics.causal_lm", + "finance_benchmark_accuracy": "fltest.metrics.causal_lm", } for _name, _module in BUILTIN_METRICS.items(): diff --git a/fltest/metrics/causal_lm.py b/fltest/metrics/causal_lm.py index d9aa9ba..e31c1ef 100644 --- a/fltest/metrics/causal_lm.py +++ b/fltest/metrics/causal_lm.py @@ -17,3 +17,11 @@ class PerplexityListener(MetricListenerBaseClass): @register_metric("pubmedqa_accuracy") class PubMedQAAccuracyListener(MetricListenerBaseClass): HOOKS = () + + +@register_metric("fpb_accuracy") +@register_metric("fiqa_accuracy") +@register_metric("tfns_accuracy") +@register_metric("finance_benchmark_accuracy") +class FinanceBenchmarkAccuracyListener(MetricListenerBaseClass): + HOOKS = () diff --git a/fltest/pitfalls/checker.py b/fltest/pitfalls/checker.py index c64c0cc..412313d 100644 --- a/fltest/pitfalls/checker.py +++ b/fltest/pitfalls/checker.py @@ -52,7 +52,7 @@ def check_learning_gap(result: Dict[str, Any]) -> List[Finding]: final = result.get("final", {}).get(settings.metric) if any(isinstance(v, bool) or not isinstance(v, Real) or not math.isfinite(v) for v in (baseline, final)): return [] - improvement = final - baseline if settings.metric == "accuracy" else baseline - final + improvement = baseline - final if settings.metric == "loss" else final - baseline if improvement >= settings.min_improvement: return [] name = result.get("run_name", result.get("run_id", "run")) diff --git a/fltest/testing/report.py b/fltest/testing/report.py index ca7a078..f3db898 100644 --- a/fltest/testing/report.py +++ b/fltest/testing/report.py @@ -112,6 +112,23 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: "perplexity": "ppl", "pubmedqa_accuracy": "pmqa-acc", "learning_rate": "lr", + "fpb_accuracy": "fpb-acc", + "fiqa_accuracy": "fiqa-acc", + "tfns_accuracy": "tfns-acc", + "finance_benchmark_accuracy": "fin-bench", + "fpb_strict_accuracy": "fpb-strict", + "fiqa_strict_accuracy": "fiqa-strict", + "tfns_strict_accuracy": "tfns-strict", + "fpb_label_parse_rate": "fpb-parse", + "fiqa_label_parse_rate": "fiqa-parse", + "tfns_label_parse_rate": "tfns-parse", + "fpb_evaluation_samples": "fpb-n", + "fiqa_evaluation_samples": "fiqa-n", + "tfns_evaluation_samples": "tfns-n", + "fpb_zero_shot_gap": "fpb-gap", + "fiqa_zero_shot_gap": "fiqa-gap", + "tfns_zero_shot_gap": "tfns-gap", + "finance_benchmark_zero_shot_gap": "fin-gap", "attack_success_rate": "asr", "model_replacement_scale": "mr-scale", "per_client_acc_mean": "pc-mean", @@ -146,6 +163,10 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: "perplexity": "exponential of token-weighted held-out next-token cross-entropy", "pubmedqa_accuracy": "generated yes/no/maybe accuracy on the pinned PubMedQA test subset; Medical loss uses separate held-out flashcards", "learning_rate": "client optimizer learning rate for this training round", + "fpb_accuracy": "FPB accuracy using FlowerTune's three-class scorer, including its neutral fallback", + "fiqa_accuracy": "FIQA accuracy using FlowerTune's three-class scorer, including its neutral fallback", + "tfns_accuracy": "TFNS accuracy using FlowerTune's three-class scorer, including its neutral fallback", + "finance_benchmark_accuracy": "unweighted mean of FPB, FIQA and TFNS accuracies; distinct from FinGPT held-out accuracy", "accuracy": "top-1 accuracy of the global model on the held-out test set", "loss": "mean cross-entropy on the same test set", "attack_success_rate": "attack success rate, the share of triggered inputs predicted as the attacker's target label", diff --git a/mkdocs.yml b/mkdocs.yml index e123b08..0e5ceb3 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -50,6 +50,7 @@ nav: - Config fuzzing: fuzzing.md - Multi-node clusters: multi-node.md - Causal language models: causal-lm.md + - Finance benchmarks: finance-benchmarks.md - Stack Overflow: stackoverflow.md - Medical: medical.md - Components: diff --git a/tests/test_finance_benchmarks.py b/tests/test_finance_benchmarks.py new file mode 100644 index 0000000..b5c4755 --- /dev/null +++ b/tests/test_finance_benchmarks.py @@ -0,0 +1,244 @@ +"""Finance benchmark protocols, provenance, training exclusion and generation scoring.""" + +import csv +import hashlib +import json +from pathlib import Path +from types import SimpleNamespace +import zipfile + +import numpy as np +import pytest +import torch + +from fltest.core.config import TestConfig, load_config +from fltest.core.orchestrator import expand_run_specs +from fltest.data.causal_lm import normalize_text, prepare_finance_data +from fltest.data.finance_benchmarks import ( + SOURCES, benchmark_instruction, benchmark_label, benchmark_prompt, + evaluate_finance_benchmarks, fiqa_label, official_evaluation_rows, + prepare_finance_benchmarks, read_benchmark_source, strict_polarity, +) +from fltest.pitfalls import check_learning_gap + + +def benchmark_spec(**overrides): + config = dict(task='causal_lm', dataset='hf:flwrlabs/fingpt-sentiment-train', + model_name='hf:example/model', device='cpu', num_clients=2, dataset_partitions=2, + num_rounds=2, client_batch_size=2, server_batch_size=2, + client_resources={'num_cpus': 1, 'num_gpus': 0}, + lm={'precision':'fp32','quantization':None,'seq_len':256, + 'finance_benchmarks':{'max_samples_per_benchmark':2}}, + metrics=['accuracy','loss','fpb_accuracy','fiqa_accuracy','tfns_accuracy','finance_benchmark_accuracy'], + runs=[{'framework':'flwr'}]) + config.update(overrides) + return expand_run_specs(TestConfig(**config))[0] + + +class CharacterTokenizer: + eos_token_id = pad_token_id = 2 + + def encode(self, text, **kwargs): + return [ord(c) + 3 for c in text] + + def decode(self, ids, **kwargs): + return ''.join(chr(int(c)-3) for c in ids if int(c)>2) + + def apply_chat_template(self, messages, **kwargs): + return self.encode(messages[0]['content']) + + +def write_csv(path, rows): + with path.open('w', newline='') as stream: + writer=csv.DictWriter(stream, fieldnames=list(rows[0])); writer.writeheader(); writer.writerows(rows) + + +def source_fixtures(tmp_path): + paths={} + fpb=tmp_path/'fpb.zip' + with zipfile.ZipFile(fpb,'w') as archive: + archive.writestr('FinancialPhraseBank-v1.0/Sentences_50Agree.txt', + ''.join(f'News {i} @ mail@{("negative","neutral","positive")[i%3]}\n' for i in range(12)).encode('iso-8859-1')) + archive.writestr('../unwanted.txt','never extract this') + paths['fpb']=[fpb] + paths['fiqa']=[] + for split in ('train','validation','test'): + path=tmp_path/(split+'.csv') + write_csv(path,[{'sentence':f'{split} record {i}','sentiment_score':str((i-2)/10), + 'format':'post' if i%2 else 'headline'} for i in range(4)]) + paths['fiqa'].append(path) + tfns=tmp_path/'valid.csv' + write_csv(tfns,[{'text':f'Tweet {i}','label':str(i%3)} for i in range(6)]) + paths['tfns']=[tfns] + return paths + + +def patch_downloads(monkeypatch, paths): + lookup={(repo,filename):str(path) for name,(repo,files) in SOURCES.items() + for filename,path in zip(files,paths[name])} + calls=[] + def download(repo, filename, **kwargs): + calls.append((repo,filename,kwargs)) + return lookup[repo,filename] + monkeypatch.setattr('huggingface_hub.hf_hub_download',download) + return calls + + +def test_source_readers_preserve_the_three_distinct_label_conventions(tmp_path): + paths=source_fixtures(tmp_path) + fpb=read_benchmark_source('fpb',paths['fpb']) + fiqa=read_benchmark_source('fiqa',paths['fiqa']) + tfns=read_benchmark_source('tfns',paths['tfns']) + assert fpb[0]['input']=='News 0 @ mail' and fpb[0]['target']=='negative' + assert [row['target'] for row in tfns[:3]]==['negative','positive','neutral'] + assert [row['id'] for row in fiqa[::4]]==['train:0','validation:0','test:0'] + assert 'tweet' in fiqa[1]['instruction'] and 'news' in fiqa[0]['instruction'] + assert not (tmp_path.parent/'unwanted.txt').exists() + + +@pytest.mark.parametrize('score,expected',[(-.10001,'negative'),(-.1,'neutral'),(.09999,'neutral'),(.1,'positive')]) +def test_fiqa_score_boundaries_match_the_reference(score,expected): + assert fiqa_label(score)==expected + + +@pytest.mark.parametrize('score',[float('nan'),float('inf')]) +def test_fiqa_nonfinite_scores_are_rejected(score): + with pytest.raises(ValueError,match='finite'):fiqa_label(score) + + +def test_evaluation_indices_match_numpy_seed42_not_the_training_seed(): + rows=[{'id':str(i)} for i in range(20)] + expected=np.random.default_rng(42).permutation(20)[:5].tolist() + assert [int(r['id']) for r in official_evaluation_rows('fpb',rows)]==expected + assert official_evaluation_rows('fiqa',rows)==official_evaluation_rows('fpb',rows) + assert official_evaluation_rows('tfns',rows)==rows + + +def test_preparation_pins_file_hashes_and_excludes_all_eval_groups_even_when_capped(tmp_path,monkeypatch): + paths=source_fixtures(tmp_path); calls=patch_downloads(monkeypatch,paths) + spec=benchmark_spec() + prepared,metadata,groups=prepare_finance_benchmarks(spec,CharacterTokenizer()) + assert {k:len(v) for k,v in prepared.items()}=={'fpb':2,'fiqa':2,'tfns':2} + assert len(groups['tfns'])==6 and len(groups['fpb'])==3 + assert all(len(call[2]['revision'])==40 for call in calls) + assert all('trust_remote_code' not in call[2] for call in calls) + assert metadata['fpb']['source_rows']==12 and metadata['fpb']['full_evaluation_rows']==3 + assert metadata['fpb']['source_files_sha256']['data/FinancialPhraseBank-v1.0.zip']==hashlib.sha256(paths['fpb'][0].read_bytes()).hexdigest() + assert metadata['tfns']['evaluation_ids']==['validation:0','validation:1'] + assert prepare_finance_benchmarks(spec,CharacterTokenizer())==(prepared,metadata,groups) + assert benchmark_prompt({'instruction':'Choose','input':'News'})=='Instruction: Choose\nInput: News\nAnswer: ' + + +def test_long_prompts_fail_instead_of_silently_changing_the_benchmark(tmp_path,monkeypatch): + paths=source_fixtures(tmp_path);patch_downloads(monkeypatch,paths) + opts=benchmark_spec().lm.model_dump();opts['finance_benchmarks']['max_total_tokens']=16 + with pytest.raises(ValueError,match='not silently truncated'): + prepare_finance_benchmarks(benchmark_spec(lm=opts),CharacterTokenizer()) + + +def test_benchmark_overlap_is_removed_before_iid_sharding_with_source_ids_preserved(tmp_path,monkeypatch): + from datasets import Dataset + + paths=source_fixtures(tmp_path);patch_downloads(monkeypatch,paths) + benchmark_text=next(row['input'] for row in read_benchmark_source('tfns',paths['tfns'])[2:] + if int(hashlib.sha256(f"786:{normalize_text(row['input'])}".encode()).hexdigest(),16)/2**256 >= .1) + rows=[{'instruction':'Choose','input':f'Unique {i}','output':'positive'} for i in range(100)] + rows.extend([{'instruction':'Choose','input':benchmark_text,'output':'negative'}, + {'instruction':'Choose','input':' '+benchmark_text.upper()+' ','output':'neutral'}]) + raw=Dataset.from_list(rows) + monkeypatch.setattr('datasets.load_dataset',lambda *a,**kw:raw) + monkeypatch.setattr('huggingface_hub.HfApi',lambda:SimpleNamespace( + dataset_info=lambda *a,**kw:SimpleNamespace(sha='training-sha'))) + monkeypatch.setattr('fltest.data.causal_lm.resolve_model_revisions',lambda *a:None) + monkeypatch.setattr('fltest.data.causal_lm.load_tokenizer',lambda spec:CharacterTokenizer()) + data=prepare_finance_data(benchmark_spec(max_test_data_size=1000)) + used=[r for loader in data['c2loader'].values() for r in loader.dataset] + assert all(normalize_text(r['finance_row']['input'])!=normalize_text(benchmark_text) for r in used) + assert data['metadata']['excluded_benchmark_train_row_ids']==[100,101] + assert not {100,101} & {r['sample_id'] for r in used} + assert data['metadata']['train_rows']+data['metadata']['holdout_rows']+2==len(raw) + assert hasattr(data['test_loader'],'finance_benchmarks') + options=benchmark_spec().lm.model_dump();options['finance_benchmarks']=None + legacy=prepare_finance_data(benchmark_spec(lm=options,metrics=['accuracy','loss'],max_test_data_size=1000)) + assert [r['sample_id'] for r in data['test_loader'].dataset]==[r['sample_id'] for r in legacy['test_loader'].dataset] + + +@pytest.mark.parametrize('response,expected,strict',[ + ('positive','positive','positive'),('Negative.','negative','negative'), + ('negative but positive','positive',None),('POSITIVE','neutral','positive'), + ('unrecognized text','neutral',None),('The sentiment is mildly negative.','negative','negative'), +]) +def test_reference_scoring_quirks_are_retained_and_diagnosed(response,expected,strict): + assert benchmark_label(response)==expected + assert strict_polarity(response)==strict + + +def test_generation_scores_each_dataset_separately_and_averages_datasets_equally(): + tokenizer=CharacterTokenizer() + replies=iter(['nonsense','positive','negative','The sentiment is negative.']) + class Model: + def eval(self):pass + def generate(self,input_ids,**kwargs): + assert kwargs['do_sample'] is False and kwargs['use_cache'] is True + return torch.cat([input_ids,torch.tensor([tokenizer.encode(next(replies))])],dim=1) + def row(sid,target):return {'id':sid,'target':target,'prompt_ids':tokenizer.encode('Instruction: x\nInput: x\nAnswer: '),'max_new_tokens':32} + data={'fpb':[row('f1','neutral'),row('f2','positive')], + 'fiqa':[row('q1','positive')],'tfns':[row('t1','negative')]} + metrics,predictions=evaluate_finance_benchmarks(Model(),tokenizer,data,benchmark_spec()) + assert metrics['fpb_accuracy']==1 and metrics['fpb_strict_accuracy']==.5 + assert metrics['fpb_label_parse_rate']==.5 and metrics['fpb_evaluation_samples']==2 + assert metrics['fiqa_accuracy']==0 and metrics['tfns_accuracy']==1 + assert metrics['finance_benchmark_accuracy']==pytest.approx(2/3) + assert predictions['fpb'][0]['response']=='nonsense' + + +@pytest.mark.parametrize('changes,message',[ + ({'max_samples_per_benchmark':0},'greater than 0'), + ({'max_new_tokens':512},'leave room'),({'max_total_tokens':0},'greater than or equal'), + ({'fpb_revision':' '},'nonempty'), +]) +def test_benchmark_configuration_guards(changes,message): + opts=benchmark_spec().lm.model_dump();opts['finance_benchmarks'].update(changes) + with pytest.raises(ValueError,match=message):benchmark_spec(lm=opts) + + +def test_finance_benchmark_settings_are_opt_in_and_change_run_ids(): + root=Path(__file__).resolve().parents[1] + legacy=expand_run_specs(load_config(root/'examples/configs/finance_learning_check.yaml'))[0] + assert legacy.run_id=='48abed612c' and 'finance_benchmarks' not in legacy.lm.run_settings() + opts=benchmark_spec().lm.model_dump();opts['finance_benchmarks']['max_samples_per_benchmark']=3 + assert benchmark_spec().run_id!=benchmark_spec(lm=opts).run_id + opts['finance_benchmarks']=None + with pytest.raises(ValueError,match='Unsupported causal_lm metrics'):benchmark_spec(lm=opts) + with pytest.raises(ValueError,match='requires the Finance dataset'): + benchmark_spec(dataset='hf:flwrlabs/medical-meadow-medical-flashcards') + + +def test_learning_gap_can_use_the_benchmark_mean_and_checks_metric_availability(): + opts=benchmark_spec().lm.model_dump();opts['learning_gap']={'metric':'finance_benchmark_accuracy'} + spec=benchmark_spec(lm=opts) + result={'status':'success','params':spec.summary(),'history':{'0':{'finance_benchmark_accuracy':.5}}, + 'final':{'finance_benchmark_accuracy':.51}} + assert check_learning_gap(result)[0].evidence['improvement']==pytest.approx(.01) + result['final']['finance_benchmark_accuracy']=.6 + assert not check_learning_gap(result) + opts['finance_benchmarks']=None + with pytest.raises(ValueError,match='require lm.finance_benchmarks'):benchmark_spec(lm=opts,metrics=['accuracy','loss']) + + +def test_triggered_finance_asr_does_not_require_or_rescore_benchmarks(monkeypatch): + from fltest.data.causal_lm import LMCollator, evaluate_causal_model + + tokenizer=CharacterTokenizer() + monkeypatch.setattr('fltest.data.causal_lm.load_tokenizer',lambda spec:tokenizer) + def forbidden(*args,**kwargs):raise AssertionError('ASR must not score clean benchmarks') + monkeypatch.setattr('fltest.data.finance_benchmarks.evaluate_finance_benchmarks',forbidden) + class Model: + def eval(self):pass + def __call__(self,**kwargs):return SimpleNamespace(loss=torch.tensor(1.)) + def generate(self,input_ids,**kwargs): + return torch.cat([input_ids,torch.tensor([tokenizer.encode('positive')])],dim=1) + batch=LMCollator(2)([{'input_ids':[3,4,2],'labels':[-100,4,2], + 'prompt_ids':[3],'response':'positive','sample_id':0}]) + loss,accuracy=evaluate_causal_model(Model(),[batch],benchmark_spec()) + assert loss==1 and accuracy==1