diff --git a/src/heretic/evaluator.py b/src/heretic/evaluator.py index 4c06b01..35fc57a 100644 --- a/src/heretic/evaluator.py +++ b/src/heretic/evaluator.py @@ -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) diff --git a/src/heretic/main.py b/src/heretic/main.py index ec3b4ce..aa950d7 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -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) @@ -1243,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 diff --git a/src/heretic/plugin.py b/src/heretic/plugin.py index cbff3d6..75546f6 100644 --- a/src/heretic/plugin.py +++ b/src/heretic/plugin.py @@ -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 diff --git a/src/heretic/utils.py b/src/heretic/utils.py index 6b65a91..85f1454 100644 --- a/src/heretic/utils.py +++ b/src/heretic/utils.py @@ -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: diff --git a/tests/test_plugin.py b/tests/test_plugin.py new file mode 100644 index 0000000..9afe1d8 --- /dev/null +++ b/tests/test_plugin.py @@ -0,0 +1,246 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2025-2026 Philipp Emanuel Weidmann + 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()