Compare commits

..
19 changed files with 42 additions and 666 deletions

No files matched your search

-3
View File
@@ -15,9 +15,6 @@ wheels/
# Editors
/.vscode/
# ripgrep/fd-specific ignore file
/.ignore
# Configuration file (root only, not ignored in test directories)
/config.toml
+1 -3
View File
@@ -85,9 +85,7 @@ Replace `Qwen/Qwen3-4B-Instruct-2507` with whatever model you want to process.
**By default, Heretic performs censorship removal (refusal suppression).**
If you want to do something else, choose one of the configuration files linked
above, or write your own. See [`config.default.toml`](/config.default.toml)
for available configuration options. Heretic loads the configuration from
`config.toml` in the working directory by default, or from the file path in the
`HERETIC_CONFIG_FILE` environment variable.
for available configuration options.
> [!IMPORTANT]
>
+1 -25
View File
@@ -163,7 +163,7 @@ column = "text"
# Name that describes what the configured keyword rate measures.
score_name = "Refusals"
# Whether to print prompt/response pairs.
# Whether to print prompt/response pairs when counting keyword matches.
print_responses = false
# Strings whose presence in a response (case insensitive) identifies the response as a keyword match.
@@ -292,30 +292,6 @@ 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.
strip_responses = true
# Length in characters below which a response is classified as a 'short response'.
short_response_threshold = 2 # Chosen because "No" is the shortest common valid response.
# Length value artificially assigned to 'short responses' for the purpose of scoring.
# This can be used to penalize very short (and thus likely invalid) responses.
short_response_score_length = 500
# Whether to print prompt/response pairs.
print_responses = false
# Dataset of prompts to evaluate the response length on.
[scorer.ResponseLength.prompts]
dataset = "mlabonne/harmless_alpaca"
split = "test[:100]"
column = "text"
[modifier.ARA]
# Whether to renormalize the rows of the modified matrices to preserve
-51
View File
@@ -1,51 +0,0 @@
# Rename this file to config.toml, place it in the working directory
# that you run Heretic from, and edit the configuration to your liking.
scorers = [
{ plugin = "heretic.scorers.response_length.ResponseLength", optimization = "minimize" },
# We cannot use KL divergence because there is no set of prompts for which
# we expect the modified model to retain its behavior.
{ plugin = "heretic.scorers.benchmark_score.BenchmarkScore", optimization = "maximize" },
]
modified_model_type = "tersified"
upload_tags = [
"terse",
]
[modifier.ARA.good_prompts]
dataset = "mlabonne/harmless_alpaca"
split = "train[:400]"
column = "text"
system_prompt = """You are a hyper-terse assistant. You respond with the minimum amount of text that satisfies the prompt.
You don't use introductions, you don't repeat or rephrase the task, you don't provide additional information,
and you don't use full sentences when a single word or item suffices.
Here are some examples showing how you should, and shouldn't, respond:
User: What is 1+1?
Good response: 2
Bad response: 1 + 1 = 2! This is a simple addition operation.
User: What is the largest land animal?
Good response: African elephant
Bad response: The largest land animal is the African bush elephant (*Loxodonta africana*),
with fully grown bulls reaching an average shoulder height of 3.3 meters, and a body mass of 6 tons.
User: Describe a grocery shopping trip.
Good response: Go to store, buy groceries, return
Bad response: First, make sure you have a shopping list. Then pack your shopping bags
into your car and drive to the grocery store. Make sure you park as closely as possible
to the entrance of the store. Once inside, pick up a cart and check the aisles for the items you need.
Collect all items in your cart and proceed to the register. Pay for the items and take the cart
to your car. Move the items from the cart into the trunk of your car. Then return the cart to the store,
return to your car, and drive home."""
[modifier.ARA.bad_prompts]
dataset = "mlabonne/harmless_alpaca"
split = "train[:400]"
column = "text"
system_prompt = """You are a loquacious personal assistant. You give elaborate, highly detailed responses to every prompt.
Your responses contain proper introductions and start with a summary of the task or question.
You supply as much additional information as possible and write everything out in full detail."""
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "heretic-llm"
version = "2.1.0.dev0"
version = "2.0.0"
description = "Training-free language model modification"
readme = "README.md"
license = "AGPL-3.0-or-later"
+1 -11
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import os
from enum import Enum
from typing import Any, Literal, TypeAlias
@@ -191,15 +190,6 @@ class BenchmarkSpecification(BaseModel):
)
def _config_path() -> str:
path = os.environ.get("HERETIC_CONFIG_FILE", "config.toml")
if "HERETIC_CONFIG_FILE" in os.environ and not os.path.isfile(path):
raise SystemExit(f"heretic: configuration file {path} does not exist")
return path
class Settings(BaseSettings):
model: str = Field(description="Hugging Face model ID, or path to model on disk.")
@@ -600,7 +590,7 @@ class Settings(BaseSettings):
EnvSettingsSource(settings_cls, env_prefix="HERETIC_"),
dotenv_settings,
file_secret_settings,
TomlConfigSettingsSource(settings_cls, toml_file=_config_path()),
TomlConfigSettingsSource(settings_cls, toml_file="config.toml"),
)
@classmethod
+1 -10
View File
@@ -174,9 +174,7 @@ class Evaluator:
"""
records: list[dict[str, Any]] = []
for (name, score), (baseline_name, baseline) in zip(
scores,
self.baseline_scores,
strict=True,
scores, self.baseline_scores
):
assert name == baseline_name, (
f"Score/baseline order mismatch: {name!r} != {baseline_name!r}"
@@ -230,10 +228,3 @@ 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)
+10 -38
View File
@@ -661,18 +661,6 @@ 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()
@@ -751,7 +739,6 @@ 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)
@@ -904,7 +891,6 @@ 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)
@@ -1019,6 +1005,7 @@ 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()
@@ -1031,8 +1018,10 @@ 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}[/].")
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()
if reproduction_mode:
print("Verifying hashes of weight files...")
@@ -1059,9 +1048,6 @@ 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,
@@ -1189,6 +1175,7 @@ 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()
@@ -1211,6 +1198,10 @@ 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)
@@ -1257,22 +1248,8 @@ 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
@@ -1292,8 +1269,6 @@ 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...")
@@ -1345,9 +1320,6 @@ def run():
f"[bold]{filename}:[/] [red]File not found[/]"
)
if strategy != ExportStrategy.ADAPTER:
reset_trial_model()
case "chat":
print()
print(
+1 -36
View File
@@ -44,29 +44,6 @@ def get_model_class(
return AutoModelForCausalLM
def check_model_resident(model: PreTrainedModel | PeftModel) -> None:
"""
Ensure that all of the model's weights are resident in memory.
"""
offloaded = [name for name, param in model.named_parameters() if param.is_meta]
if not offloaded:
return
raise Exception(
"The model does not fit into the available device memory: "
f"{len(offloaded)} weights (such as {', '.join(offloaded[:3])}) had to "
"be offloaded to CPU or disk. Heretic cannot process offloaded models "
"because it requires direct, persistent access to all weights, whereas "
"offloaded weights only exist temporarily during forward passes.\n"
"Possible remedies:\n"
"* Free up memory, e.g. by closing other applications.\n"
"* Change the device map (device_map/max_memory settings) so that all "
"weights fit into device memory.\n"
'* Enable 4-bit quantization (quantization = "bnb_4bit").'
)
def _collapse_flattened_residual_streams(
hidden_states: tuple[FloatTensor, ...],
config: Any,
@@ -235,10 +212,6 @@ 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
@@ -260,8 +233,6 @@ class Model:
if self.model is None:
raise Exception("Failed to load model with all configured dtypes.")
check_model_resident(self.model)
print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers")
all_components = {}
@@ -448,8 +419,6 @@ class Model:
**extra_kwargs,
)
check_model_resident(self.model)
self.needs_reload = False
return False
@@ -859,11 +828,7 @@ class Model:
)
)
self.generate(
prompts,
max_new_tokens=1,
use_cache=False,
)
self.generate(prompts, max_new_tokens=1)
for hook_handle in hook_handles:
hook_handle.remove()
+3 -43
View File
@@ -8,16 +8,7 @@ import sys
import types
from pathlib import Path
from types import ModuleType
from typing import (
Annotated,
Any,
TypeVar,
Union,
cast,
get_args,
get_origin,
get_type_hints,
)
from typing import Annotated, Any, TypeVar, Union, get_args, get_origin, get_type_hints
from pydantic import BaseModel
from torch import Tensor
@@ -211,23 +202,14 @@ class Plugin:
"""
Whether runs using this plugin can be reproduced bit-for-bit.
Set to False if the plugin's behavior is not deterministic or depends on
Set to False when 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 the
Defaults to False; override to True in your plugin class if any of 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
@@ -356,28 +338,6 @@ 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
+2
View File
@@ -53,6 +53,8 @@ class Scorer(Plugin, ABC):
def get_score(self, ctx: Context) -> Score:
"""
Return a `Score` given the evaluation context.
The `value` of the `Score` must be of the order of magnitude 1
to ensure that all scores are comparable during co-optimization.
"""
def get_baseline_score(self, ctx: Context) -> Score:
+15 -18
View File
@@ -3,7 +3,7 @@
import lm_eval
from lm_eval.models.huggingface import HFLM
from pydantic import BaseModel, Field, NonNegativeInt
from pydantic import BaseModel, Field
from heretic.scorer import Context, Score, Scorer
@@ -24,11 +24,6 @@ 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):
"""
@@ -45,27 +40,29 @@ class BenchmarkScore(Scorer):
def score_name(self) -> str:
return self.settings.score_name
def get_score(self, ctx: Context) -> Score:
def init(self, ctx: Context) -> None:
model = ctx.get_model()
hflm = HFLM(
self.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,
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
results = lm_eval.simple_evaluate(
model=hflm,
model=self.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]
)
+2 -7
View File
@@ -215,12 +215,7 @@ class BERTClassifier(Scorer):
predicted_labels = self._classify(responses)
match_count = 0
for prompt, response, label in zip(
self.prompts,
responses,
predicted_labels,
strict=True,
):
for prompt, response, label in zip(self.prompts, responses, predicted_labels):
# Evaluate matches based on the classifier's predicted label only.
is_match = label in self.settings.match_labels
match_count += int(is_match)
@@ -258,7 +253,7 @@ class BERTClassifier(Scorer):
"text": prompt.user,
"text_pair": response,
}
for prompt, response in zip(self.prompts, responses, strict=True)
for prompt, response in zip(self.prompts, responses)
]
else:
# Fallback for single-sequence text-classification models
+2 -3
View File
@@ -78,7 +78,7 @@ class Settings(BaseModel):
print_responses: bool = Field(
default=False,
description="Whether to print prompt/response pairs.",
description="Whether to print prompt/response pairs when counting keyword matches.",
)
@@ -110,8 +110,7 @@ class KeywordRate(Scorer):
def get_score(self, ctx: Context) -> Score:
match_count = 0
responses = ctx.get_responses(self.prompts)
for prompt, response in zip(self.prompts, responses, strict=True):
for prompt, response in zip(self.prompts, responses):
is_match = self._is_match(response)
if is_match:
match_count += 1
-101
View File
@@ -1,101 +0,0 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from pydantic import BaseModel, Field, NonNegativeInt
from rich.markup import escape
from heretic.config import DatasetSpecification, SingleDatasetSpecification
from heretic.scorer import Context, Score, Scorer
from heretic.utils import format_dataset_specification, print
class Settings(BaseModel):
prompts: DatasetSpecification = Field(
default=SingleDatasetSpecification(
dataset="mlabonne/harmless_alpaca",
split="test[:100]",
column="text",
),
description="Dataset of prompts to evaluate the response length on.",
)
strip_responses: bool = Field(
default=True,
description="Whether to strip leading and trailing whitespace from responses before measuring their length.",
)
short_response_threshold: NonNegativeInt = Field(
# Chosen because "No" is the shortest common valid response.
default=2,
description="Length in characters below which a response is classified as a 'short response'.",
)
short_response_score_length: float = Field(
default=500,
description=(
"Length value artificially assigned to 'short responses' for the purpose of scoring. "
"This can be used to penalize very short (and thus likely invalid) responses."
),
)
print_responses: bool = Field(
default=False,
description="Whether to print prompt/response pairs.",
)
class ResponseLength(Scorer):
"""
Measures the mean length of responses.
"""
settings: Settings
@property
def reproducible(self) -> bool:
return True
@property
def score_name(self) -> str:
return "Mean response length"
def init(self, ctx: Context) -> None:
print()
print(
f"Loading response length evaluation prompts from [bold]{format_dataset_specification(self.settings.prompts)}[/]..."
)
self.prompts = ctx.load_prompts(self.settings.prompts)
print(f"* [bold]{len(self.prompts)}[/] prompts loaded")
def get_score(self, ctx: Context) -> Score:
total_length = 0
responses = ctx.get_responses(self.prompts)
for prompt, response in zip(self.prompts, responses, strict=True):
response_length = len(
response.strip() if self.settings.strip_responses else response
)
if response_length < self.settings.short_response_threshold:
response_length = self.settings.short_response_score_length
total_length += response_length
if self.settings.print_responses:
print()
print(f"[bold]System prompt:[/] {escape(prompt.system)}")
print(f"[bold]Prompt:[/] {escape(prompt.user)}")
if not response.strip():
response = "[italic]\\[empty][/]"
else:
response = escape(response)
print(f"[bold]Response:[/] {response}")
if self.settings.print_responses:
print()
mean_length = float(total_length / len(self.prompts))
return Score(
value=mean_length,
rich_display=f"[bold]{mean_length:.1f}[/]",
md_display=f"{mean_length:.1f}",
)
+1 -17
View File
@@ -372,26 +372,10 @@ 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."""
# 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()))
return tomli_w.dumps(settings.model_dump(exclude_none=True))
def generate_requirements_txt() -> str:
-52
View File
@@ -134,58 +134,6 @@ class ModelValidateInitOnlyTests(unittest.TestCase):
self.assertEqual(settings.max_memory, {"0": "20GiB"})
class ConfigFileSelectionTests(unittest.TestCase):
def settings(
self, config_files: dict[str, str], heretic_config: str | None = None
) -> Settings:
with tempfile.TemporaryDirectory() as directory:
for name, content in config_files.items():
Path(directory, name).write_text(content)
environment = {
key: value
for key, value in os.environ.items()
if not key.startswith("HERETIC_")
}
if heretic_config is not None:
environment["HERETIC_CONFIG_FILE"] = heretic_config
previous_directory = os.getcwd()
os.chdir(directory)
try:
with (
patch.dict(os.environ, environment, clear=True),
patch("sys.argv", ["heretic"]),
):
return Settings(model="dummy")
finally:
os.chdir(previous_directory)
def test_environment_variable_selects_file(self) -> None:
settings = self.settings({"custom.toml": "n_trials = 42\n"}, "custom.toml")
self.assertEqual(settings.n_trials, 42)
def test_default_config_toml_still_loaded(self) -> None:
settings = self.settings({"config.toml": "n_trials = 42\n"})
self.assertEqual(settings.n_trials, 42)
def test_missing_default_config_file_is_silent(self) -> None:
settings = self.settings({})
self.assertEqual(settings.n_trials, Settings.model_fields["n_trials"].default)
def test_missing_configured_file_aborts(self) -> None:
with self.assertRaisesRegex(SystemExit, "does not exist"):
self.settings({}, "missing.toml")
def test_configured_default_file_missing_aborts(self) -> None:
# Unlike a missing implicit default, this counts as a configuration error.
with self.assertRaisesRegex(SystemExit, "does not exist"):
self.settings({}, "config.toml")
class SettingsUploadTagsTests(unittest.TestCase):
def test_default_upload_tags(self) -> None:
with patch("sys.argv", ["heretic"]):
-246
View File
@@ -1,246 +0,0 @@
# 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()
Generated
+1 -1
View File
@@ -1082,7 +1082,7 @@ wheels = [
[[package]]
name = "heretic-llm"
version = "2.1.0.dev0"
version = "2.0.0"
source = { editable = "." }
dependencies = [
{ name = "accelerate" },