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 tests/test_finance_benchmarks.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 tests/test_reference_causal_lm.py -q

docs:
name: docs build
Expand Down
3 changes: 2 additions & 1 deletion docs/causal-lm.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,5 @@ LM attacks, metrics, and incompatible defense combinations before loading a mode
The [Stack Overflow application](stackoverflow.md) adds user-partitioned Parquet data,
full-model training, and next-token evaluation. The [Medical application](medical.md)
adds micro-batched flashcard training and PubMedQA subset evaluation. Optional DoRA
and the reference LM backend remain follow-up work.
remains follow-up work. The [reference backend](reference-causal-lm.md) supports
sequential LM execution and comparisons against Flower.
5 changes: 5 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ A list of `{framework, name?, ...overrides}`. One entry per framework you want t
A run entry may also override any top-level knob and may carry its own `attacks`/`defenses`/
`metrics`. Frameworks: `reference`, `flwr`/`flower`, `nvflare`/`flare`.

For `task: causal_lm`, supported backends are `reference` and `flwr`/`flower`.
Reference runs sequentially on the local device; it accepts the same explicit
`client_resources` and sampling settings for [LM parity](reference-causal-lm.md),
without starting Ray or allocating clients across nodes.

### `testing:`
- `differential:` — see [Differential testing](differential-testing.md).
- `metamorphic:` — a list of relations; see [Metamorphic testing](metamorphic-testing.md).
Expand Down
9 changes: 7 additions & 2 deletions docs/differential-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ A single scalar metric from each run's `final` dict, selected by
`testing.differential.metric` (default `accuracy`). Typically the final-round global-model
test accuracy.

For causal LMs, cross-framework testing also compares that metric at round zero
and every trained round, after verifying initialization, data provenance and
client training evidence. See [reference LM parity](reference-causal-lm.md) for
the stricter grouping and evidence requirements.

## Mode 1: `cross_framework` (parity)

Same logical config, different FL framework ⇒ same final metric within tolerance. This
Expand Down Expand Up @@ -37,8 +42,8 @@ testing:
```

!!! note "Parity, not bit-identity"
Different frameworks use different RNG streams and execution paths, so exact equality is
impossible. The reference and Flower backends share FLTest's own weighted-mean
Different frameworks can use different RNG streams and execution paths, so exact equality is
not guaranteed. The reference and Flower backends share FLTest's own weighted-mean
aggregation, which keeps them close; the tolerance (default 0.05, as in the project
slides) absorbs the residual. Choose tolerance to match your metric's natural variance.

Expand Down
5 changes: 3 additions & 2 deletions docs/medical.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,6 @@ arithmetic rather than implementing cryptographic deployment protocols.

The deployment plan's full configuration is 20 IID clients with four selected per
round, effective batch 16, sequence length 512 and ten local optimizer steps.
Repeated seeds, the full grid, long clean learning checks, reference-backend parity,
and the remaining leaderboard benchmarks require further experiments.
Repeated seeds, the full grid, long clean learning checks and the remaining
leaderboard benchmarks require further experiments. Small backend comparisons
are available through [reference LM parity](reference-causal-lm.md).
54 changes: 54 additions & 0 deletions docs/reference-causal-lm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Reference causal-LM execution

`framework: reference` runs Finance, Stack Overflow and Medical LM tasks in a
sequential PyTorch loop. It supports LoRA and full-model updates, round-zero and
per-round evaluation, checkpoints, client sampling, schedules, micro-batching,
and the same supported attack/defense hooks as Flower.

The loop has no Flower or Ray execution dependency. It shares FLTest's data,
model, local-training, evaluation and aggregation helpers with Flower. This makes
it an oracle for orchestration and transport differences; it does not independently
validate those shared algorithms. Client hooks are reconstructed for every fit,
matching Flower worker RPC lifecycles. Updates are aggregated in client-ID order
in both LM backends, independent of RPC completion order.

Install the LM extra as described in [installation](installation.md). Reference
runs on the local CPU or GPU selected by `device`. `client_resources` remains
required for a common comparison configuration, but reference executes one client
at a time and does not allocate Ray resources or use other nodes.

## Run a small comparison

The supplied GPU configurations use SmolLM2-135M, two trained rounds and capped
evaluation data. Start the two-node Ray cluster for the Flower half as described
in [multi-node execution](multi-node.md), then run:

```bash
export FLTEST_RAY_ADDRESS=10.0.1.1:6379
fltest diff examples/configs/finance_reference_parity.yaml
fltest diff examples/configs/stackoverflow_reference_parity.yaml
fltest diff examples/configs/medical_reference_parity.yaml
```

Stack Overflow requires the local user-partitioned Parquet exports described in
its [application guide](stackoverflow.md). Each configuration executes reference
first and Flower second. These are integration comparisons, not full benchmark
or learning experiments. GPU loss tolerance is explicitly `0.02`; choose a
tolerance appropriate to the model, precision and metric for larger comparisons.

## What parity checks

LM comparison groups include training, tokenizer, precision, resources and
evaluation settings; checkpoint destinations are excluded. At least two distinct
backends must be present (`flower` and `flwr` count as one).

Before comparing the requested metric, the checker requires matching data
provenance, parameter manifests, an initialization SHA-256 fingerprint, and a
complete round history. Every trained round must show matching client IDs,
successful training-record IDs, sample weights, poisoning counts, user identities
and learning rates when present. It compares the requested finite metric at
round zero, every trained round and the final summary. Missing evidence fails
the comparison; legacy LM results without initialization fingerprints must be rerun.

This checks backend agreement within tolerance. GPU repeatability, long clean
learning runs and full attack/defense grids remain separate validation work.
62 changes: 62 additions & 0 deletions examples/configs/finance_reference_parity.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Small backend comparison; not a model-quality or determinism result.
name: finance_reference_parity
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: reference
name: reference
- framework: flwr
name: flower
testing:
differential:
enabled: true
mode: cross_framework
metric: loss
tolerance: 0.02
56 changes: 56 additions & 0 deletions examples/configs/medical_reference_parity.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Small backend comparison; not a model-quality or determinism result.
name: medical_reference_parity
task: causal_lm
dataset: hf:flwrlabs/medical-meadow-medical-flashcards
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: 4
client_lr: 5.0e-05
optimizer: AdamW
server_batch_size: 2
max_test_data_size: 8
client_resources:
num_cpus: 2
num_gpus: 1
lm:
model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
dataset_revision: bc33733afea65239aed2149aa79ea77742d28cc2
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
micro_batch_size: 1
grad_accum_steps: 4
medical:
pubmedqa_revision: 13a7d15476092370cbabb6475390e7e69b74d2f2
pubmedqa_max_samples: 8
pubmedqa_max_prompt_tokens: 1024
max_new_tokens: 32
metrics:
- pubmedqa_accuracy
- loss
runs:
- framework: reference
name: reference
- framework: flwr
name: flower
testing:
differential:
enabled: true
mode: cross_framework
metric: loss
tolerance: 0.02
52 changes: 52 additions & 0 deletions examples/configs/stackoverflow_reference_parity.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Small backend comparison; not a model-quality or determinism result.
name: stackoverflow_reference_parity
task: causal_lm
dataset: stackoverflow
data_distribution: by_user
model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct
device: cuda
total_cpus: 8
total_gpus: 2
num_clients: 4
dataset_partitions: 4
clients_per_round: 2
num_rounds: 2
client_batch_size: 2
client_lr: 0.001
optimizer: SGD
server_batch_size: 2
max_test_data_size: 16
client_resources:
num_cpus: 2
num_gpus: 1
lm:
model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
method: full
precision: fp16
quantization: null
seq_len: 128
local_steps: 2
gradient_checkpointing: true
max_train_samples_per_client: 32
checkpoint_dir: reports/models
stackoverflow:
train_path: data/stackoverflow/so_1k/train.parquet
heldout_path: data/stackoverflow/so_1k/heldout.parquet
partition_by: user_id
max_heldout_users: 4
metrics:
- next_token_accuracy
- perplexity
- loss
runs:
- framework: reference
name: reference
- framework: flwr
name: flower
testing:
differential:
enabled: true
mode: cross_framework
metric: loss
tolerance: 0.02
7 changes: 4 additions & 3 deletions fltest/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,8 @@ class RunSpec(BaseModel):
@model_validator(mode="after")
def validate_task(self):
uses_flower_resources = self.clients_per_round is not None or self.client_resources is not None
if uses_flower_resources and self.framework not in ("flwr", "flower"):
reference_lm = self.task == "causal_lm" and self.framework == "reference"
if uses_flower_resources and self.framework not in ("flwr", "flower") and not reference_lm:
raise ValueError("clients_per_round and client_resources currently support framework: flwr")
if self.clients_per_round is not None and self.clients_per_round > self.num_clients:
raise ValueError("clients_per_round must not exceed num_clients")
Expand All @@ -287,8 +288,8 @@ def validate_task(self):
return self
if self.lm is None:
raise ValueError("task: causal_lm requires an lm settings block")
if self.framework not in ("flwr", "flower"):
raise ValueError("causal_lm currently supports framework: flwr")
if self.framework not in ("flwr", "flower", "reference"):
raise ValueError("causal_lm supports framework: flwr or reference")
finance = self.dataset.removeprefix("hf:") == "flwrlabs/fingpt-sentiment-train"
medical = self.dataset.removeprefix("hf:") == "flwrlabs/medical-meadow-medical-flashcards"
stackoverflow = self.dataset == "stackoverflow"
Expand Down
9 changes: 9 additions & 0 deletions fltest/data/causal_lm.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,15 @@ def manifest_field(spec):
return "parameter_manifest" if spec.lm.method == "full" else "adapter_manifest"


def causal_parameter_digest(parameters):
"""Fingerprint the transported initialization without retaining a byte copy."""
digest = hashlib.sha256()
for array in parameters:
digest.update(json.dumps((array.dtype.str, array.shape)).encode())
digest.update(memoryview(np.ascontiguousarray(array)).cast('B'))
return digest.hexdigest()


def causal_parameters(model, spec):
if spec.lm.method == "lora":
return adapter_parameters(model)
Expand Down
5 changes: 5 additions & 0 deletions fltest/frameworks/flower/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR
)
driver_runner.run("on_data_distribute", ctx_data)
c2loader = ctx_data.dist_dict if ctx_data.dist_dict is not None else c2loader
if spec.task == 'causal_lm':
from fltest.data.causal_lm import causal_parameter_digest

state_holder['initial_parameters_sha256'] = causal_parameter_digest(init_params)

backend_config = ray_backend_config(
spec.total_cpus, spec.total_gpus, spec.num_clients, spec.client_resources
Expand Down Expand Up @@ -165,4 +169,5 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR
checkpoint=state_holder["checkpoint"],
)
result.extras[manifest_field(spec)] = state_holder[manifest_field(spec)]
result.extras['initial_parameters_sha256'] = state_holder['initial_parameters_sha256']
return result
2 changes: 2 additions & 0 deletions fltest/frameworks/flower/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ def aggregate_fit(self, server_round, results, failures):
if (failures or any(type(cid) is not int for cid in ids)
or len(ids) != len(self._selected_clients) or set(ids) != set(self._selected_clients)):
raise RuntimeError(f"Causal-LM round {server_round} has missing or failed clients")
# RPC completion order must not choose floating-point summation or tie order.
successful.sort(key=lambda result: result[1].metrics['cid'])
for _, response in successful:
if self._spec.lm.lr_schedule is not None:
from fltest.core.lm_protocol import validate_round_learning_rate
Expand Down
4 changes: 4 additions & 0 deletions fltest/frameworks/reference/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ def _new_model(self, spec: RunSpec):
).to(spec.device)

def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookRunner) -> RunResult:
if spec.task == "causal_lm":
from fltest.frameworks.reference.causal_lm import run_causal_simulation

return run_causal_simulation(spec, data, hook_runner)
seed_everything(spec.seed)
result = RunResult(run_id=spec.run_id, run_name=spec.run_name, framework=self.name)

Expand Down
Loading
Loading