Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a798385d8e |
No files matched your search
@@ -15,9 +15,6 @@ wheels/
|
||||
# Editors
|
||||
/.vscode/
|
||||
|
||||
# ripgrep/fd-specific ignore file
|
||||
/.ignore
|
||||
|
||||
# Configuration file (root only, not ignored in test directories)
|
||||
/config.toml
|
||||
|
||||
|
||||
@@ -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
-22
@@ -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.
|
||||
@@ -293,27 +293,6 @@ 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
|
||||
|
||||
@@ -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
-11
@@ -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
|
||||
|
||||
@@ -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}"
|
||||
|
||||
+10
-10
@@ -1005,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()
|
||||
@@ -1017,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...")
|
||||
@@ -1045,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,
|
||||
@@ -1175,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()
|
||||
@@ -1197,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)
|
||||
@@ -1264,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...")
|
||||
|
||||
@@ -1317,9 +1320,6 @@ def run():
|
||||
f"[bold]{filename}:[/] [red]File not found[/]"
|
||||
)
|
||||
|
||||
if strategy != ExportStrategy.ADAPTER:
|
||||
reset_trial_model()
|
||||
|
||||
case "chat":
|
||||
print()
|
||||
print(
|
||||
|
||||
@@ -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,
|
||||
@@ -256,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 = {}
|
||||
@@ -444,8 +419,6 @@ class Model:
|
||||
**extra_kwargs,
|
||||
)
|
||||
|
||||
check_model_resident(self.model)
|
||||
|
||||
self.needs_reload = False
|
||||
|
||||
return False
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}",
|
||||
)
|
||||
@@ -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"]):
|
||||
|
||||
Reference in new issue
Block a user