Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
7 changes: 6 additions & 1 deletion docs/causal-lm.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
110 changes: 110 additions & 0 deletions docs/finance-benchmarks.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand Down
8 changes: 8 additions & 0 deletions docs/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion docs/pitfalls.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
52 changes: 52 additions & 0 deletions examples/configs/finance_benchmarks_clean.yaml
Original file line number Diff line number Diff line change
@@ -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
54 changes: 54 additions & 0 deletions examples/configs/finance_benchmarks_mistral_smoke.yaml
Original file line number Diff line number Diff line change
@@ -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
54 changes: 54 additions & 0 deletions examples/configs/finance_benchmarks_smoke.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading