Compare commits

..
13 changed files with 293 additions and 20 deletions

No files matched your search

+3
View File
@@ -15,6 +15,9 @@ wheels/
# Editors
/.vscode/
# ripgrep/fd-specific ignore file
/.ignore
# Configuration file (root only, not ignored in test directories)
/config.toml
+3 -1
View File
@@ -85,7 +85,9 @@ 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.
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.
> [!IMPORTANT]
>
+22 -1
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 when counting keyword matches.
# Whether to print prompt/response pairs.
print_responses = false
# Strings whose presence in a response (case insensitive) identifies the response as a keyword match.
@@ -293,6 +293,27 @@ task = "piqa"
metric = "acc_norm,none"
[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
# the original matrices' row magnitudes. This is believed to improve
+51
View File
@@ -0,0 +1,51 @@
# 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."""
+11 -1
View File
@@ -1,6 +1,7 @@
# 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
@@ -190,6 +191,15 @@ 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.")
@@ -590,7 +600,7 @@ class Settings(BaseSettings):
EnvSettingsSource(settings_cls, env_prefix="HERETIC_"),
dotenv_settings,
file_secret_settings,
TomlConfigSettingsSource(settings_cls, toml_file="config.toml"),
TomlConfigSettingsSource(settings_cls, toml_file=_config_path()),
)
@classmethod
+3 -1
View File
@@ -174,7 +174,9 @@ class Evaluator:
"""
records: list[dict[str, Any]] = []
for (name, score), (baseline_name, baseline) in zip(
scores, self.baseline_scores
scores,
self.baseline_scores,
strict=True,
):
assert name == baseline_name, (
f"Score/baseline order mismatch: {name!r} != {baseline_name!r}"
+10 -10
View File
@@ -1005,7 +1005,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 +1017,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 +1045,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 +1175,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 +1197,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)
@@ -1269,6 +1264,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 +1317,9 @@ def run():
f"[bold]{filename}:[/] [red]File not found[/]"
)
if strategy != ExportStrategy.ADAPTER:
reset_trial_model()
case "chat":
print()
print(
+27
View File
@@ -44,6 +44,29 @@ 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,
@@ -233,6 +256,8 @@ 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 = {}
@@ -419,6 +444,8 @@ class Model:
**extra_kwargs,
)
check_model_resident(self.model)
self.needs_reload = False
return False
-2
View File
@@ -53,8 +53,6 @@ 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:
+7 -2
View File
@@ -215,7 +215,12 @@ class BERTClassifier(Scorer):
predicted_labels = self._classify(responses)
match_count = 0
for prompt, response, label in zip(self.prompts, responses, predicted_labels):
for prompt, response, label in zip(
self.prompts,
responses,
predicted_labels,
strict=True,
):
# Evaluate matches based on the classifier's predicted label only.
is_match = label in self.settings.match_labels
match_count += int(is_match)
@@ -253,7 +258,7 @@ class BERTClassifier(Scorer):
"text": prompt.user,
"text_pair": response,
}
for prompt, response in zip(self.prompts, responses)
for prompt, response in zip(self.prompts, responses, strict=True)
]
else:
# Fallback for single-sequence text-classification models
+3 -2
View File
@@ -78,7 +78,7 @@ class Settings(BaseModel):
print_responses: bool = Field(
default=False,
description="Whether to print prompt/response pairs when counting keyword matches.",
description="Whether to print prompt/response pairs.",
)
@@ -110,7 +110,8 @@ 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):
for prompt, response in zip(self.prompts, responses, strict=True):
is_match = self._is_match(response)
if is_match:
match_count += 1
+101
View File
@@ -0,0 +1,101 @@
# 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}",
)
+52
View File
@@ -134,6 +134,58 @@ 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"]):