This commit is contained in:
akushonkamen 2026-11-28 15:24:24 +00:00 committed by GitHub
commit f6086d5a97
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 462 additions and 2 deletions

View File

@ -93,6 +93,12 @@ n_trials = 100
# Number of trials that use random sampling for the purpose of exploration.
n_startup_trials = 30
# Number of top trials for which scores are measured again on the merged
# (exported) model after optimization, since merged models behave slightly
# differently than the live LoRA the trials were selected by.
# Set to 0 to skip this check.
n_merged_score_trials = 3
# Directory to save and load study progress to/from.
study_checkpoint_dir = "checkpoints"

View File

@ -423,6 +423,16 @@ class Settings(BaseSettings):
description="Number of trials that use random sampling for the purpose of exploration.",
)
n_merged_score_trials: NonNegativeInt = Field(
default=3,
description=(
"Number of top trials for which scores are measured again on the merged "
"(exported) model after optimization, since merged models behave slightly "
"differently than the live LoRA the trials were selected by. "
"Set to 0 to skip this check."
),
)
seed: int | None = Field(
default=None,
description=(

View File

@ -89,7 +89,7 @@ from .config import (
)
from .evaluator import Evaluator
from .model import Model, get_model_class
from .modifier import load_and_init_modifiers
from .modifier import Modifier, load_and_init_modifiers
from .plugin import Context, is_builtin_plugin
from .reproduce import (
check_environment,
@ -194,6 +194,140 @@ def obtain_export_strategy(
)
def rescore_top_trials_on_merged_models(
study: optuna.study.Study,
sorted_trials: list[FrozenTrial],
settings: Settings,
model: Model,
evaluator: Evaluator,
modifier: Modifier,
objective_names: list[str],
) -> dict[int, list[dict[str, Any]]]:
"""
Re-scores the top trials on their merged (exported) models.
The scores recorded during the study come from PEFT's live-LoRA operator,
which applies the base matrix and the adapter separately, rounding
intermediate results to the model dtype. The merged operator of the
exported model applies `W + BA` in a single step, and the two rounding
orders are not mutually reproducible, so the exported model can score
systematically differently than the trial it was selected from
(see https://github.com/p-e-w/heretic/issues/490).
For each top trial, this function restores the trial's live-LoRA state,
merges it via `Model.get_merged_model()`, and runs the regular evaluation.
Memory use stays bounded: at most one merged model exists at a time.
Runtime stays bounded: at most `settings.n_merged_score_trials` additional
evaluations with the configured scorers.
Returns a mapping from trial number to merged score records (in the same
format as `Evaluator.get_paired_score_records()`). Trials whose merged
evaluation fails are omitted from the mapping.
"""
merged_scores_by_trial: dict[int, list[dict[str, Any]]] = {}
n_rescored = min(settings.n_merged_score_trials, len(sorted_trials))
if n_rescored == 0:
return merged_scores_by_trial
print()
print(
f"Re-scoring the top [bold]{n_rescored}[/] trial(s) on merged models. "
"Merged (exported) models can score differently than the live LoRA "
"the trials were selected by."
)
if settings.quantization == QuantizationMethod.BNB_4BIT:
print(
"[yellow]WARNING: Merging a quantized model requires dequantizing "
"the entire model to system RAM, once per trial.[/]"
)
for rescored_trial in sorted_trials[:n_rescored]:
print()
print(
f"* [Trial {rescored_trial.user_attrs['index']:>3}] "
"Merging and evaluating..."
)
try:
# Restore this trial's live-LoRA state, mirroring what happens
# when a trial is selected after the optimization.
ctx = Context(settings=settings, model=model)
modifier.reset_model(ctx)
parameters = modifier.parameters_class.from_dict(
rescored_trial.user_attrs["parameters"]
)
modifier.modify_model(ctx, parameters)
merged_model = model.get_merged_model()
# Route all inference through the merged operator while scoring.
# For non-quantized models, merge_and_unload() has already replaced
# model.model in place (Model marks it for a full reload); for
# quantized models, this swaps in the merged CPU copy and restores
# the untouched live model afterwards.
live_model = model.model
model.model = merged_model
try:
merged_scores = evaluator.get_scores()
finally:
model.model = live_model
del merged_model
empty_cache()
merged_scores_by_trial[rescored_trial.number] = (
evaluator.get_paired_score_records(merged_scores)
)
except Exception as exception:
# A failed merged evaluation must not lose the optimization
# results, mirroring the error handling of the post-optimization
# actions.
print(
f" [yellow]Merged-model evaluation failed "
f"({format_exception(exception)}). Only the live-LoRA scores "
"are available for this trial.[/]"
)
continue
live_values = {
record["name"]: record["score"]["value"]
for record in rescored_trial.user_attrs["scores"]
}
for record in merged_scores_by_trial[rescored_trial.number]:
name = record["name"]
merged_value = record["score"]["value"]
if name in live_values:
print(
f" * [bold]{name}:[/] live {live_values[name]:.4g} → "
f"merged {merged_value:.4g} "
f"(Δ {merged_value - live_values[name]:+.4g})"
)
else:
print(f" * [bold]{name}:[/] merged {merged_value:.4g}")
if merged_scores_by_trial:
study.set_user_attr("merged_scores", merged_scores_by_trial)
# If every candidate has merged scores, rank by them, since the merged
# operator is what the exported model actually runs. Trials without
# merged scores keep their live-score ordering.
if all(trial.number in merged_scores_by_trial for trial in sorted_trials):
merged_values = {
trial.number: {
record["name"]: record["score"]["value"]
for record in merged_scores_by_trial[trial.number]
}
for trial in sorted_trials
}
sorted_trials.sort(
key=lambda trial: tuple(
merged_values[trial.number][name] for name in objective_names
),
)
return merged_scores_by_trial
def run():
# Modified "Pagga" font from https://budavariam.github.io/asciiart-text/
print(f"[cyan]█░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀[/] v{version('heretic-llm')}")
@ -804,16 +938,48 @@ def run():
),
)
# The trial scores recorded during the optimization come from the
# live-LoRA operator, which the exported (merged) model does not
# numerically reproduce. Re-score the top trials on their merged
# models and show both scores, so the selection below is based on
# the behavior of the exported model.
merged_scores_by_trial = rescore_top_trials_on_merged_models(
study=study,
sorted_trials=sorted_trials,
settings=settings,
model=model,
evaluator=evaluator,
modifier=modifier,
objective_names=objective_names,
)
def format_trial_title(trial: FrozenTrial) -> str:
prefix = f"[Trial {trial.user_attrs['index']:>3}]"
merged_records = merged_scores_by_trial.get(trial.number)
merged_displays = (
{
record["name"]: record["score"]["rich_display"]
for record in merged_records
}
if merged_records is not None
else {}
)
# We don't directly use the trial.values here since we need to show the
# CLI-formatted versions, which are stored in the trial's user attributes.
# When a trial was re-scored on its merged model, the live score is
# followed by the merged-model score.
score_parts: list[str] = []
for score in trial.user_attrs["scores"]:
name = score["name"]
value = Text.from_markup(score["score"]["rich_display"]).plain
score_parts.append(f"{name}: {value}")
merged_display = merged_displays.get(name)
if merged_display is None:
score_parts.append(f"{name}: {value}")
else:
merged_value = Text.from_markup(merged_display).plain
score_parts.append(f"{name}: {value} → {merged_value}")
return f"{prefix} " + ", ".join(score_parts)
@ -855,6 +1021,12 @@ def run():
"chat with it to test how well it works, or run standard benchmarks on it. "
"You can return to this menu later to select a different trial. "
)
if merged_scores_by_trial:
print(
"Scores shown as `live → merged` were measured on the live LoRA "
"during the optimization and again on the merged (exported) "
"model; the merged value is what the exported model achieves."
)
while trial_loop_active:
# Ensure a predefined trial is only processed once.

View File

@ -0,0 +1,272 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import unittest
from typing import Any, cast
from unittest import mock
import optuna
from heretic.config import Settings
from heretic.evaluator import Evaluator
from heretic.main import rescore_top_trials_on_merged_models
from heretic.model import Model
from heretic.modifier import Modifier
from heretic.plugin import Context
from heretic.scorer import Score
# Matches the order in which the scorers are evaluated below.
OBJECTIVE_NAMES = ["KL divergence", "Refusal rate"]
# Live (trial-time) scores. The values are mutually non-dominating, so every
# trial lands on the Pareto front, sorted ascending by score tuple.
LIVE_SCORES = [(1.0, 4.0), (2.0, 3.0), (3.0, 2.0), (4.0, 1.0)]
# Scores returned by the fake evaluator, in call order (the function re-scores
# the front trials in live-sorted order). Deliberately ordered so that ranking
# by merged scores flips the first two trials relative to the live ranking.
MERGED_SCORES = [(101.0, 50.0), (100.0, 49.0), (103.0, 52.0), (104.0, 51.0)]
def make_score_records(kld: float, refusals: float) -> list[dict[str, Any]]:
return [
{
"name": "KL divergence",
"score": {
"value": kld,
"rich_display": f"{kld:.4f}",
"md_display": f"{kld:.4f}",
},
"baseline": {},
},
{
"name": "Refusal rate",
"score": {
"value": refusals,
"rich_display": f"{refusals:.1f}",
"md_display": f"{refusals:.1f}",
},
"baseline": {},
},
]
def make_scores(values: tuple[float, float]) -> list[tuple[str, Score]]:
return [
("KL divergence", Score(value=values[0], rich_display="", md_display="")),
("Refusal rate", Score(value=values[1], rich_display="", md_display="")),
]
class FakeParameters:
def __init__(self, data: dict[str, Any]):
self.data = data
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "FakeParameters":
return cls(data)
class FakeModel:
def __init__(self):
self.model = object() # The live model, as Model.model would be.
self.merge_calls = 0
def get_merged_model(self):
self.merge_calls += 1
return object() # A distinct merged model on every call.
class FakeModifier:
parameters_class = FakeParameters
def __init__(self):
self.reset_calls = 0
self.modified_parameters = []
def reset_model(self, ctx: Context) -> None:
self.reset_calls += 1
def modify_model(self, ctx: Context, parameters: Any) -> None:
self.modified_parameters.append(parameters)
class FakeEvaluator:
def __init__(self, results: list[Any]):
# `results[i]` is returned by the i-th `get_scores()` call;
# an Exception instance is raised instead of returned.
self.results = list(results)
self.get_scores_calls = 0
def get_scores(self) -> list[tuple[str, Score]]:
result = self.results.pop(0)
self.get_scores_calls += 1
if isinstance(result, Exception):
raise result
return make_scores(result)
def get_paired_score_records(
self, scores: list[tuple[str, Score]]
) -> list[dict[str, Any]]:
return [
{"name": name, "score": dict(score.__dict__), "baseline": {}}
for name, score in scores
]
def build_study() -> optuna.study.Study:
study = optuna.create_study(directions=["minimize", "minimize"])
def objective(trial: optuna.Trial) -> tuple[float, float]:
kld, refusals = LIVE_SCORES[trial.number]
trial.set_user_attr("index", trial.number + 1)
trial.set_user_attr("parameters", {"strength": 0.1 * (trial.number + 1)})
trial.set_user_attr("scores", make_score_records(kld, refusals))
return kld, refusals
study.optimize(objective, n_trials=len(LIVE_SCORES))
return study
def sorted_pareto_trials(study: optuna.study.Study) -> list[optuna.trial.FrozenTrial]:
# Mirrors the live-score ordering used in main.run().
return sorted(
study.best_trials,
key=lambda trial: tuple(
next(
(
score["score"]["value"]
for score in trial.user_attrs["scores"]
if score["name"] == name
),
None,
)
for name in OBJECTIVE_NAMES
),
)
class RescoreTopTrialsOnMergedModelsTests(unittest.TestCase):
def run_rescoring(
self,
evaluator: FakeEvaluator,
n_merged_score_trials: int,
) -> tuple[
optuna.study.Study,
FakeModel,
FakeModifier,
list[optuna.trial.FrozenTrial],
dict[int, list[dict[str, Any]]],
]:
study = build_study()
sorted_trials = sorted_pareto_trials(study)
self.assertEqual(
[trial.number for trial in sorted_trials],
[0, 1, 2, 3],
"test setup broken: front is not in expected live order",
)
# Settings parses CLI arguments on instantiation (cli_parse_args),
# which would choke on pytest's own argv, so neutralize it here.
with mock.patch("sys.argv", ["heretic"]):
settings = Settings(
model="dummy-model", n_merged_score_trials=n_merged_score_trials
)
model = FakeModel()
modifier = FakeModifier()
# The fakes duck-type the real interfaces; `cast` keeps the type
# checker happy without dragging the heavyweight classes into it.
merged_scores_by_trial = rescore_top_trials_on_merged_models(
study=study,
sorted_trials=sorted_trials,
settings=settings,
model=cast(Model, model),
evaluator=cast(Evaluator, evaluator),
modifier=cast(Modifier, modifier),
objective_names=OBJECTIVE_NAMES,
)
return study, model, modifier, sorted_trials, merged_scores_by_trial
def test_top_trials_are_rescored_on_merged_models(self) -> None:
evaluator = FakeEvaluator(MERGED_SCORES)
study, model, modifier, sorted_trials, merged_scores_by_trial = (
self.run_rescoring(evaluator, n_merged_score_trials=2)
)
# Exactly the top-K trials were re-scored, with the model restored
# to the live state afterwards.
self.assertEqual(model.merge_calls, 2)
self.assertEqual(evaluator.get_scores_calls, 2)
self.assertEqual(sorted(merged_scores_by_trial), [0, 1])
self.assertIsInstance(model.model, object)
self.assertEqual(modifier.reset_calls, 2)
self.assertEqual(
[parameters.data for parameters in modifier.modified_parameters],
[{"strength": 0.1}, {"strength": 0.2}],
)
# The merged score records were persisted to the study.
self.assertEqual(sorted(study.user_attrs["merged_scores"]), [0, 1])
self.assertEqual(merged_scores_by_trial[0][0]["score"]["value"], 101.0)
# Only part of the front has merged scores, so trials keep their
# live-score ranking (merging live and merged values into one
# ranking would compare incommensurable numbers).
self.assertEqual(
[trial.number for trial in sorted_trials],
[0, 1, 2, 3],
)
def test_failed_merged_evaluation_skips_trial(self) -> None:
evaluator = FakeEvaluator([RuntimeError("merge failed"), MERGED_SCORES[1]])
study, model, _modifier, sorted_trials, merged_scores_by_trial = (
self.run_rescoring(evaluator, n_merged_score_trials=2)
)
# The failing trial was skipped, the second one was still re-scored,
# and the failure did not propagate.
self.assertEqual(model.merge_calls, 2)
self.assertEqual(sorted(merged_scores_by_trial), [1])
self.assertEqual(sorted(study.user_attrs["merged_scores"]), [1])
# Not every trial has merged scores, so the live ranking is kept.
self.assertEqual(
[trial.number for trial in sorted_trials],
[0, 1, 2, 3],
)
def test_zero_disables_rescoring(self) -> None:
evaluator = FakeEvaluator(MERGED_SCORES)
study, model, _, sorted_trials, merged_scores_by_trial = self.run_rescoring(
evaluator, n_merged_score_trials=0
)
self.assertEqual(merged_scores_by_trial, {})
self.assertEqual(model.merge_calls, 0)
self.assertNotIn("merged_scores", study.user_attrs)
self.assertEqual(
[trial.number for trial in sorted_trials],
[0, 1, 2, 3],
)
def test_front_smaller_than_k_rescores_entire_front(self) -> None:
evaluator = FakeEvaluator(MERGED_SCORES)
study, model, _, sorted_trials, merged_scores_by_trial = self.run_rescoring(
evaluator, n_merged_score_trials=10
)
self.assertEqual(model.merge_calls, 4)
self.assertEqual(sorted(merged_scores_by_trial), [0, 1, 2, 3])
# Every trial on the front has merged scores, so the front is
# re-ranked by them: trial 1 now comes first.
self.assertEqual(
[trial.number for trial in sorted_trials],
[1, 0, 2, 3],
)
self.assertEqual(sorted(study.user_attrs["merged_scores"]), [0, 1, 2, 3])
if __name__ == "__main__":
unittest.main()