Compare commits

..
Author SHA1 Message Date
Philipp Emanuel Weidmann 81e0b984dd docs: prepare for 2.1 release 2026-11-08 12:09:17 +05:30
Philipp Emanuel WeidmannandVinay Umrethe 75a640b7eb fix: export plugin settings correctly (#570)
* fix: export plugin settings correctly

* test: add four more tests (#571)

---------

Co-authored-by: Vinay Umrethe <175500353+Vinay-Umrethe@users.noreply.github.com>
2026-11-07 22:12:32 +05:30
Philipp Emanuel Weidmann ce61e18206 fix: make batch size caching in benchmark scorer actually work (#567) 2026-11-06 15:07:18 +05:30
Philipp Emanuel Weidmann 3dbc48156d perf: disable KV cache when obtaining module I/O (#566) 2026-11-05 18:07:14 +05:30
10 changed files with 376 additions and 31 deletions

No files matched your search

+10 -8
View File
@@ -44,6 +44,7 @@ Heretic can, depending on the configuration:
* Reduce humor ([`config.nohumor.toml`](/config.nohumor.toml))
* Reduce sycophancy ([`config.nosyco.toml`](/config.nosyco.toml))
* Alter emotional alignment ([`config.emotions.toml`](/config.emotions.toml))
* Shorten response length ([`config.terse.toml`](/config.terse.toml))
and many, many other things.
@@ -61,8 +62,8 @@ Heretic models have been independently benchmarked using standard metrics
like MMLU and GSM8K, and have been found to compare favorably against models
produced with competing abliteration tools.[^2][^3]
[^2]: https://old.reddit.com/r/LocalLLaMA/comments/1sojjoc/abliterlitics_benchmark_and_tensor_analysis/
[^3]: https://old.reddit.com/r/LocalLLaMA/comments/1sy18lx/abliterlitics_benchmarks_and_tensor_comparison/
[^2]: [Qwen2.5-7B: Three-Way Abliteration Comparison](https://huggingface.co/DreamFast/Qwen-2.5-7b-abliterlitics): *"Heretic is the most surgical and most effective."*
[^3]: [Gemma 4 E4B: 23 Abliteration Variants Compared](https://huggingface.co/DreamFast/Gemma4-e4b-abliterlitics): *"Best overall: heretic."*
&nbsp;
@@ -228,10 +229,11 @@ exists on Hugging Face.
Unlike lots of AI-related software today (and indeed lots of software in general),
Heretic is **not** "vibe-coded".
All of [my](https://github.com/p-e-w) commits in this project so far were written
100% by hand, the way I have been doing programming for decades, and while some
Heretic contributors use coding agents, I review every single line of code that I
merge very carefully. There's no "LGTM" here!
All of [my](https://github.com/p-e-w) commits to this project until November 2026
were written 100% by hand, the way I have been doing programming for decades.
I have been using LLM assistance *very* sparingly since. While many Heretic contributors
use coding agents, I carefully review every single line of code that I merge.
There's no "LGTM" here!
Don't believe me? Check out [this pull request](https://github.com/p-e-w/heretic/pull/53),
which accumulated **almost 350 human-written comments** over more than 7 months
@@ -239,8 +241,8 @@ as we discussed the implementation.
And [here is another PR](https://github.com/p-e-w/heretic/pull/191) with
**more than 200 comments.**
I am the opposite of a luddite and I have used agents for other projects, but
I am proud of the code I write and so far can't quite bring myself to let a machine
I am the opposite of a luddite and I have used agents liberally for other projects,
but I am proud of the code I write and so far can't quite bring myself to let a machine
write it for me in a project I care so much about. As a result, Heretic has a lean,
relatively simple codebase that in my opinion, and in that of some others,
is a pleasure to work on.
+3
View File
@@ -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.
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "heretic-llm"
version = "2.1.0.dev0"
version = "2.1.0"
description = "Training-free language model modification"
readme = "README.md"
license = "AGPL-3.0-or-later"
+7
View File
@@ -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)
+28
View File
@@ -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
+43 -3
View File
@@ -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
+20 -17
View File
@@ -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
View File
@@ -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:
+246
View File
@@ -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()
Generated
+1 -1
View File
@@ -1082,7 +1082,7 @@ wheels = [
[[package]]
name = "heretic-llm"
version = "2.1.0.dev0"
version = "2.1.0"
source = { editable = "." }
dependencies = [
{ name = "accelerate" },