Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07069d36b9 | ||
|
|
22fcc4c188 | ||
|
|
ce61e18206 | ||
|
|
3dbc48156d | ||
|
|
b4864fdd59 |
No files matched your search
@@ -292,6 +292,9 @@ task = "piqa"
|
||||
# Task metric to use as the benchmark score.
|
||||
metric = "acc_norm,none"
|
||||
|
||||
# Number of input sequences to process in parallel (0 = auto).
|
||||
batch_size = 0 # auto
|
||||
|
||||
|
||||
[scorer.ResponseLength]
|
||||
# Whether to strip leading and trailing whitespace from responses before measuring their length.
|
||||
|
||||
@@ -230,3 +230,10 @@ class Evaluator:
|
||||
parse_study_direction(entry.config.optimization)
|
||||
for entry in self._objective_entries()
|
||||
]
|
||||
|
||||
def write_settings_to_config(self) -> None:
|
||||
"""
|
||||
Write the settings of all scorers to the global configuration.
|
||||
"""
|
||||
for entry in self._scorer_entries:
|
||||
entry.scorer.write_settings_to_config("scorer", entry.config.instance_name)
|
||||
+38
-10
@@ -661,6 +661,18 @@ def run():
|
||||
modifier = modifier_entry.modifier
|
||||
modifier_name = modifier_entry.name
|
||||
|
||||
def write_plugin_settings_to_config() -> None:
|
||||
# Plugins may mutate their settings at any time (e.g. pinning dataset
|
||||
# commits during initialization, or resolving values during scoring),
|
||||
# so the effective plugin settings are recorded immediately before
|
||||
# every serialization of the settings object, to ensure that the
|
||||
# serialized settings reflect the exact configuration that was used.
|
||||
evaluator.write_settings_to_config()
|
||||
modifier.write_settings_to_config(
|
||||
"modifier",
|
||||
modifier_entry.config.instance_name,
|
||||
)
|
||||
|
||||
# Clear cache before starting the optimization study.
|
||||
# This should free up memory from temporary objects created while initializing modifiers.
|
||||
empty_cache()
|
||||
@@ -739,6 +751,7 @@ def run():
|
||||
load_if_exists=True,
|
||||
)
|
||||
|
||||
write_plugin_settings_to_config()
|
||||
study.set_user_attr("settings", settings.model_dump_json())
|
||||
study.set_user_attr("finished", False)
|
||||
|
||||
@@ -891,6 +904,7 @@ def run():
|
||||
continue
|
||||
|
||||
settings.n_trials = len(study.trials) + n_additional_trials
|
||||
write_plugin_settings_to_config()
|
||||
study.set_user_attr("settings", settings.model_dump_json())
|
||||
study.set_user_attr("finished", False)
|
||||
|
||||
@@ -1005,7 +1019,6 @@ def run():
|
||||
save_directory,
|
||||
max_shard_size=settings.max_shard_size,
|
||||
)
|
||||
print(f"Model saved to [bold]{save_directory}[/].")
|
||||
else:
|
||||
print("Saving merged model...")
|
||||
merged_model = model.get_merged_model()
|
||||
@@ -1018,10 +1031,8 @@ def run():
|
||||
model.tokenizer.save_pretrained(save_directory)
|
||||
if model.processor is not None:
|
||||
model.processor.save_pretrained(save_directory)
|
||||
print(f"Model saved to [bold]{save_directory}[/].")
|
||||
# Merging replaced the trial's adapter in place.
|
||||
# Restore it only after the save has been reported.
|
||||
reset_trial_model()
|
||||
|
||||
print(f"Model saved to [bold]{save_directory}[/].")
|
||||
|
||||
if reproduction_mode:
|
||||
print("Verifying hashes of weight files...")
|
||||
@@ -1048,6 +1059,9 @@ def run():
|
||||
f"[bold]{filename}:[/] [red]File not found[/]"
|
||||
)
|
||||
|
||||
if strategy != ExportStrategy.ADAPTER:
|
||||
reset_trial_model()
|
||||
|
||||
case "upload":
|
||||
# We don't use huggingface_hub.login() because that stores the token on disk,
|
||||
# and since this program will often be run on rented or shared GPU servers,
|
||||
@@ -1175,7 +1189,6 @@ def run():
|
||||
max_shard_size=settings.max_shard_size,
|
||||
token=token,
|
||||
)
|
||||
print(f"Model uploaded to [bold]{repo_id}[/].")
|
||||
else:
|
||||
print("Uploading merged model...")
|
||||
merged_model = model.get_merged_model()
|
||||
@@ -1198,10 +1211,6 @@ def run():
|
||||
private=private,
|
||||
token=token,
|
||||
)
|
||||
print(f"Model uploaded to [bold]{repo_id}[/].")
|
||||
# Merging replaced the trial's adapter in place.
|
||||
# Restore it only after the upload has been reported.
|
||||
reset_trial_model()
|
||||
|
||||
if is_hf_path(settings.model):
|
||||
card = ModelCard.load(settings.model)
|
||||
@@ -1248,8 +1257,22 @@ def run():
|
||||
card.push_to_hub(repo_id, token=token)
|
||||
|
||||
if reproducibility_information != "none":
|
||||
# Record the final effective plugin settings so that the
|
||||
# exported config.toml and reproduce.json reflect the exact
|
||||
# configuration that was used.
|
||||
write_plugin_settings_to_config()
|
||||
# Refresh the settings stored in the study journal to allow
|
||||
# continuation with the current plugin state.
|
||||
study.set_user_attr(
|
||||
"settings",
|
||||
settings.model_dump_json(),
|
||||
)
|
||||
|
||||
# Set the number of trials to the number of actual completed trials
|
||||
# for the reproduction configuration.
|
||||
# These updates are deliberately *not* written to the journal,
|
||||
# because the purpose of the journal is continuing the study with
|
||||
# more trials, and potentially choosing a different export strategy.
|
||||
settings.n_trials = len(study.trials)
|
||||
current_export_strategy = settings.export_strategy
|
||||
settings.export_strategy = strategy
|
||||
@@ -1269,6 +1292,8 @@ def run():
|
||||
finally:
|
||||
settings.export_strategy = current_export_strategy
|
||||
|
||||
print(f"Model uploaded to [bold]{repo_id}[/].")
|
||||
|
||||
if reproduction_mode:
|
||||
print("Verifying hashes of weight files...")
|
||||
|
||||
@@ -1320,6 +1345,9 @@ def run():
|
||||
f"[bold]{filename}:[/] [red]File not found[/]"
|
||||
)
|
||||
|
||||
if strategy != ExportStrategy.ADAPTER:
|
||||
reset_trial_model()
|
||||
|
||||
case "chat":
|
||||
print()
|
||||
print(
|
||||
|
||||
@@ -235,6 +235,10 @@ class Model:
|
||||
)
|
||||
],
|
||||
max_new_tokens=1,
|
||||
# The KV cache is deliberately left enabled here so we can
|
||||
# catch dtype errors related to the cache, which we will need
|
||||
# for generating responses.
|
||||
# use_cache=False,
|
||||
)
|
||||
except Exception as error:
|
||||
self.model = None
|
||||
@@ -855,7 +859,11 @@ class Model:
|
||||
)
|
||||
)
|
||||
|
||||
self.generate(prompts, max_new_tokens=1)
|
||||
self.generate(
|
||||
prompts,
|
||||
max_new_tokens=1,
|
||||
use_cache=False,
|
||||
)
|
||||
|
||||
for hook_handle in hook_handles:
|
||||
hook_handle.remove()
|
||||
|
||||
+43
-3
@@ -8,7 +8,16 @@ import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Annotated, Any, TypeVar, Union, get_args, get_origin, get_type_hints
|
||||
from typing import (
|
||||
Annotated,
|
||||
Any,
|
||||
TypeVar,
|
||||
Union,
|
||||
cast,
|
||||
get_args,
|
||||
get_origin,
|
||||
get_type_hints,
|
||||
)
|
||||
|
||||
from pydantic import BaseModel
|
||||
from torch import Tensor
|
||||
@@ -202,14 +211,23 @@ class Plugin:
|
||||
"""
|
||||
Whether runs using this plugin can be reproduced bit-for-bit.
|
||||
|
||||
Set to False when the plugin's behavior is not deterministic or depends on
|
||||
Set to False if the plugin's behavior is not deterministic or depends on
|
||||
state outside the pinned config, for example:
|
||||
- It calls an external service (e.g. an LLM judge over the OpenAI API).
|
||||
- It reads credentials or config from the environment (env vars, files).
|
||||
- It is otherwise non-deterministic (network, wall-clock, unseeded RNG).
|
||||
|
||||
Defaults to False; override to True in your plugin class if any of the
|
||||
Defaults to False; override to True in your plugin class if the
|
||||
above DO NOT apply.
|
||||
|
||||
Note: The plugin can use non-deterministic/external state if the plugin
|
||||
evaluates the state during initialization and stores it in its settings
|
||||
object in such a way that re-running the plugin with the modified settings
|
||||
guarantees identical state. A plugin may also do this after initialization
|
||||
(i.e., during execution), but only if setting that state at initialization
|
||||
time during a later run results in identical plugin behavior. This can be
|
||||
used to perform tasks such as pinning dataset commits, or automatically
|
||||
determining batch sizes.
|
||||
"""
|
||||
return False
|
||||
|
||||
@@ -338,6 +356,28 @@ class Plugin:
|
||||
return None
|
||||
return settings_model.model_validate(raw_namespace or {})
|
||||
|
||||
def write_settings_to_config(
|
||||
self,
|
||||
top_namespace: str,
|
||||
instance_name: str | None,
|
||||
) -> None:
|
||||
"""
|
||||
Write the plugin's effective (validated) settings back into
|
||||
`heretic_settings.model_extra`, under the same namespace from which
|
||||
the raw settings were read.
|
||||
"""
|
||||
if self.settings is None:
|
||||
return
|
||||
|
||||
class_name = self.__class__.__name__
|
||||
key = class_name if not instance_name else f"{class_name}_{instance_name}"
|
||||
|
||||
# Settings uses extra="allow", so model_extra is always a dictionary.
|
||||
extra = cast(dict[str, Any], self.heretic_settings.model_extra)
|
||||
namespace: dict[str, Any] = extra.setdefault(top_namespace, {})
|
||||
|
||||
namespace[key] = self.settings.model_dump()
|
||||
|
||||
def get_dataset_specifications(self) -> list[DatasetSpecification]:
|
||||
"""
|
||||
Collect the dataset specifications declared in the settings
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import lm_eval
|
||||
from lm_eval.models.huggingface import HFLM
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, NonNegativeInt
|
||||
|
||||
from heretic.scorer import Context, Score, Scorer
|
||||
|
||||
@@ -24,6 +24,11 @@ class Settings(BaseModel):
|
||||
description="Task metric to use as the benchmark score.",
|
||||
)
|
||||
|
||||
batch_size: NonNegativeInt = Field(
|
||||
default=0, # auto
|
||||
description="Number of input sequences to process in parallel (0 = auto).",
|
||||
)
|
||||
|
||||
|
||||
class BenchmarkScore(Scorer):
|
||||
"""
|
||||
@@ -40,29 +45,27 @@ class BenchmarkScore(Scorer):
|
||||
def score_name(self) -> str:
|
||||
return self.settings.score_name
|
||||
|
||||
def init(self, ctx: Context) -> None:
|
||||
model = ctx.get_model()
|
||||
|
||||
self.hflm = HFLM(
|
||||
pretrained=model.model,
|
||||
tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type]
|
||||
batch_size="auto",
|
||||
)
|
||||
|
||||
def get_score(self, ctx: Context) -> Score:
|
||||
# The purpose of this hack, where we initialize the HFLM object once,
|
||||
# then update its internal model every time we calculate the score,
|
||||
# is to get the benefits of batch size caching while allowing for
|
||||
# model reloads, e.g. when using --evaluate-model.
|
||||
model = ctx.get_model()
|
||||
self.hflm.pretrained = model.model
|
||||
self.hflm._model = model.model
|
||||
|
||||
hflm = HFLM(
|
||||
pretrained=model.model,
|
||||
tokenizer=model.tokenizer, # ty: ignore[invalid-argument-type]
|
||||
batch_size="auto"
|
||||
if self.settings.batch_size == 0
|
||||
else self.settings.batch_size,
|
||||
)
|
||||
|
||||
results = lm_eval.simple_evaluate(
|
||||
model=self.hflm,
|
||||
model=hflm,
|
||||
tasks=[self.settings.task],
|
||||
)
|
||||
|
||||
if self.settings.batch_size == 0 and hflm.batch_sizes:
|
||||
# Cache automatically determined batch size to avoid re-determining
|
||||
# the batch size on every future run.
|
||||
self.settings.batch_size = min(hflm.batch_sizes.values())
|
||||
|
||||
benchmark_score = float(
|
||||
results["results"][self.settings.task][self.settings.metric]
|
||||
)
|
||||
|
||||
+17
-1
@@ -372,10 +372,26 @@ def get_readme_intro(
|
||||
"""
|
||||
|
||||
|
||||
def _strip_none_values(data: Any) -> Any:
|
||||
"""Return a copy of the data with all None values removed (TOML has no null value)."""
|
||||
if isinstance(data, dict):
|
||||
return {
|
||||
key: _strip_none_values(value)
|
||||
for key, value in data.items()
|
||||
if value is not None
|
||||
}
|
||||
if isinstance(data, list):
|
||||
return [_strip_none_values(value) for value in data]
|
||||
return data
|
||||
|
||||
|
||||
def generate_config_toml(settings: Settings) -> str:
|
||||
"""Serializes the full Settings object to TOML."""
|
||||
|
||||
return tomli_w.dumps(settings.model_dump(exclude_none=True))
|
||||
# The `exclude_none` option can't be used here because it only applies
|
||||
# to model fields, and does not remove None values contained in extra
|
||||
# (plugin settings) dictionaries.
|
||||
return tomli_w.dumps(_strip_none_values(settings.model_dump()))
|
||||
|
||||
|
||||
def generate_requirements_txt() -> str:
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from heretic.config import Settings
|
||||
from heretic.plugin import Plugin
|
||||
from heretic.utils import generate_config_toml
|
||||
|
||||
|
||||
class DummyNestedSettings(BaseModel):
|
||||
commit: str | None = None
|
||||
name: str = "default"
|
||||
|
||||
|
||||
class DummySettings(BaseModel):
|
||||
value: int = 0
|
||||
optional: str | None = None
|
||||
nested: DummyNestedSettings = DummyNestedSettings()
|
||||
|
||||
|
||||
FULL_SETTINGS = {
|
||||
"value": 42,
|
||||
"optional": None,
|
||||
"nested": {"commit": None, "name": "default"},
|
||||
}
|
||||
|
||||
|
||||
class DummyPlugin(Plugin):
|
||||
settings: DummySettings
|
||||
|
||||
|
||||
class WriteSettingsToConfigTests(unittest.TestCase):
|
||||
def make_settings(self) -> Settings:
|
||||
# Ensure no config.toml or HERETIC_* environment variables
|
||||
# from the surrounding environment leak into the test.
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
environment = {
|
||||
key: value
|
||||
for key, value in os.environ.items()
|
||||
if not key.startswith("HERETIC_")
|
||||
}
|
||||
previous_directory = os.getcwd()
|
||||
os.chdir(directory)
|
||||
try:
|
||||
with (
|
||||
patch.dict(os.environ, environment, clear=True),
|
||||
patch.object(sys, "argv", ["heretic"]),
|
||||
):
|
||||
return Settings(model="dummy")
|
||||
finally:
|
||||
os.chdir(previous_directory)
|
||||
|
||||
def make_plugin(self, heretic_settings: Settings) -> DummyPlugin:
|
||||
return DummyPlugin(
|
||||
heretic_settings=heretic_settings,
|
||||
settings=DummySettings(value=42),
|
||||
)
|
||||
|
||||
def test_records_effective_settings_without_config_file(self) -> None:
|
||||
# Without a configuration file, model_extra starts out empty,
|
||||
# and the plugin's settings must still be recorded.
|
||||
heretic_settings = self.make_settings()
|
||||
self.assertEqual(heretic_settings.model_extra, {})
|
||||
|
||||
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
|
||||
|
||||
self.assertEqual(
|
||||
heretic_settings.model_extra,
|
||||
{"scorer": {"DummyPlugin": FULL_SETTINGS}},
|
||||
)
|
||||
|
||||
def test_records_instance_settings_under_instance_key(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
|
||||
self.make_plugin(heretic_settings).write_settings_to_config("scorer", "small")
|
||||
|
||||
self.assertEqual(
|
||||
heretic_settings.model_extra,
|
||||
{"scorer": {"DummyPlugin_small": FULL_SETTINGS}},
|
||||
)
|
||||
|
||||
def test_captures_runtime_mutations(self) -> None:
|
||||
# Plugins resolve settings values at runtime (e.g. pinned dataset
|
||||
# commits); the recorded settings must reflect those mutations.
|
||||
heretic_settings = self.make_settings()
|
||||
plugin = self.make_plugin(heretic_settings)
|
||||
|
||||
plugin.settings.value = 7
|
||||
plugin.settings.optional = "resolved"
|
||||
plugin.settings.nested.commit = "abc"
|
||||
|
||||
plugin.write_settings_to_config("modifier", None)
|
||||
|
||||
self.assertEqual(
|
||||
heretic_settings.model_extra,
|
||||
{
|
||||
"modifier": {
|
||||
"DummyPlugin": {
|
||||
"value": 7,
|
||||
"optional": "resolved",
|
||||
"nested": {"commit": "abc", "name": "default"},
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
def test_recorded_settings_survive_serialization_roundtrip(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
|
||||
|
||||
# This is how settings are stored in study journal files and
|
||||
# reproduce.json, and how they are restored when resuming
|
||||
# a study or reproducing a model.
|
||||
restored = Settings.model_validate_init_only(
|
||||
json.loads(heretic_settings.model_dump_json()), heretic_settings
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
restored.model_extra,
|
||||
{"scorer": {"DummyPlugin": FULL_SETTINGS}},
|
||||
)
|
||||
|
||||
def test_recorded_settings_appear_in_generated_config_toml(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
|
||||
|
||||
exported = generate_config_toml(heretic_settings)
|
||||
|
||||
# None values are omitted (TOML has no null value); they fall back
|
||||
# to their defaults when the settings are validated.
|
||||
self.assertIn("[scorer.DummyPlugin]", exported)
|
||||
self.assertIn("value = 42", exported)
|
||||
self.assertNotIn("optional", exported)
|
||||
self.assertIn("[scorer.DummyPlugin.nested]", exported)
|
||||
self.assertIn('name = "default"', exported)
|
||||
self.assertNotIn("commit", exported)
|
||||
|
||||
def test_none_values_are_omitted_from_config_toml(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
plugin = self.make_plugin(heretic_settings)
|
||||
plugin.settings.nested.commit = "abc"
|
||||
plugin.write_settings_to_config("scorer", None)
|
||||
|
||||
exported = generate_config_toml(heretic_settings)
|
||||
|
||||
self.assertNotIn("optional", exported)
|
||||
self.assertIn("[scorer.DummyPlugin.nested]", exported)
|
||||
self.assertIn('commit = "abc"', exported)
|
||||
self.assertIn('name = "default"', exported)
|
||||
|
||||
def test_recorded_settings_feed_back_into_plugin_validation(self) -> None:
|
||||
# The recorded settings must be readable by the same mechanism
|
||||
# that reads raw settings from the configuration file, so that
|
||||
# resuming a study or reproducing a model restores them exactly.
|
||||
heretic_settings = self.make_settings()
|
||||
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
|
||||
|
||||
raw_settings = DummyPlugin.get_settings_raw(
|
||||
heretic_settings.model_extra, "scorer", None
|
||||
)
|
||||
validated = DummyPlugin.validate_settings(raw_settings)
|
||||
|
||||
self.assertEqual(validated, DummySettings(value=42))
|
||||
|
||||
def test_records_multiple_instances_independently(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
extra = heretic_settings.model_extra
|
||||
assert extra is not None
|
||||
|
||||
first = self.make_plugin(heretic_settings)
|
||||
second = self.make_plugin(heretic_settings)
|
||||
|
||||
# Different values ensure that neither instance overwrites the other.
|
||||
first.settings.value = 10
|
||||
second.settings.value = 20
|
||||
|
||||
first.write_settings_to_config("scorer", "small")
|
||||
second.write_settings_to_config("scorer", "large")
|
||||
|
||||
self.assertEqual(
|
||||
extra["scorer"],
|
||||
{
|
||||
"DummyPlugin_small": {**FULL_SETTINGS, "value": 10},
|
||||
"DummyPlugin_large": {**FULL_SETTINGS, "value": 20},
|
||||
},
|
||||
)
|
||||
|
||||
def test_repeated_writes_update_recorded_settings(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
extra = heretic_settings.model_extra
|
||||
assert extra is not None
|
||||
|
||||
plugin = self.make_plugin(heretic_settings)
|
||||
|
||||
plugin.write_settings_to_config("scorer", None)
|
||||
|
||||
# Subsequent writes must capture settings mutations made at runtime.
|
||||
plugin.settings.value = 123
|
||||
plugin.write_settings_to_config("scorer", None)
|
||||
|
||||
self.assertEqual(
|
||||
extra["scorer"]["DummyPlugin"]["value"],
|
||||
123,
|
||||
)
|
||||
|
||||
def test_nested_none_values_fail_toml_serialization(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
extra = heretic_settings.model_extra
|
||||
assert extra is not None
|
||||
|
||||
# None values inside lists cannot be represented in TOML and must
|
||||
# cause serialization to fail rather than be silently removed.
|
||||
extra["scorer"] = {
|
||||
"DummyPlugin": {
|
||||
"values": [1, None, 3],
|
||||
}
|
||||
}
|
||||
|
||||
with self.assertRaises((TypeError, ValueError)):
|
||||
generate_config_toml(heretic_settings)
|
||||
|
||||
def test_plugins_without_settings_do_not_create_config_entries(self) -> None:
|
||||
heretic_settings = self.make_settings()
|
||||
|
||||
plugin = DummyPluginWithoutSettings(
|
||||
heretic_settings=heretic_settings,
|
||||
)
|
||||
plugin.write_settings_to_config("scorer", None)
|
||||
|
||||
self.assertEqual(heretic_settings.model_extra, {})
|
||||
|
||||
|
||||
class DummyPluginWithoutSettings(Plugin):
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user