Compare commits

...
Author SHA1 Message Date
Philipp Emanuel Weidmann f4e641ae15 ci: add Python 3.14 and 3.15 to CI matrix 2026-10-20 23:29:08 +05:30
Ayush Vishwakarma bc077540a0 feat: make upload tags configurable (#506) 2026-10-20 22:12:06 +05:30
Varun Balaniandjayhemnani9910 1bdb5bcc5a fix: support models whose chat template rejects the system role (#498)
Models like Gemma 2 and its fine-tunes reject the system role in their
chat template. generate() always prepends a system message, so the
template raises 'System role not supported' and the dtype loop gives up,
making these models impossible to load.

Detect once (right after the tokenizer loads) whether the template
accepts a system role, by rendering a probe chat and checking a sentinel
system message survives in the output (this catches both templates that
raise and templates that silently drop the role). When the role isn't
supported, fold every system message into the following user message
(dropping empty system prompts), so a system role anywhere in the chat
is removed before rendering, not just a leading one. Templates that
support the system role are unaffected, so their rendered chats and
resulting weights are unchanged.

Supersedes #483.

Co-authored-by: jayhemnani9910 <jayhemnani9910@users.noreply.github.com>
2026-10-20 21:47:51 +05:30
Jay Hemnani eabd1d75fb fix: restore stored plugin settings as they are on reproduce and resume (#484)
* fix: restore stored plugin settings as they are on reproduce and resume

Settings.model_validate still reads config.toml, environment variables and
the command line, and merges plugin tables key by key. A [modifier.X] or
[scorer.X] key in the local config.toml that the stored settings don't have
was added to a --reproduce run or a resumed study, so a reproduction could
build a different model (hash mismatch).

* fix: restore every stored table, not just plugin tables

Stored values already win over config.toml, but pydantic-settings merges
tables key by key, so max_memory picked up local keys too, and a plugin
table that only exists in config.toml was added to the run. Restore each
stored table as it is and drop tables that weren't stored.

* fix: restore stored settings without reading other sources

Validate stored settings through StoredSettings, whose only source is
the values passed in, instead of letting config.toml, the environment
and the command line merge into them and overwriting afterwards. Fields
that are never stored (exclude=True) are copied from the settings this
run was started with.

* refactor: restore stored settings on top of the current ones

Validate the current settings' fields with the stored values laid over
them, instead of copying fields with exclude=True one by one. Fields
that are never stored keep the values this run was started with, and
plugin tables still come only from the stored values.

* fix: take only never-stored settings from the current run

* refactor: rename from_stored to model_validate_init_only
2026-10-19 20:07:50 +05:30
Hamed Shams 7f86616b61 fix: say which check found the Chain-of-Thought prefix (#489) 2026-10-19 19:45:58 +05:30
Philipp Emanuel Weidmann 3a5c864527 chore: add pull request template (#502) 2026-10-17 18:29:38 +05:30
10 changed files with 415 additions and 17 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
<!--
Hey there, thanks for contributing to Heretic!
Please provide a 100% HUMAN-WRITTEN description of the contents and purpose of this pull request.
Use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format for the pull request title.
Link to any relevant issues or other pull requests in the description.
Do NOT write the description using an LLM, not even partially.
I am a human and reviewing pull requests takes a lot of human effort.
I expect to communicate with the human posting the PR, not with their agent.
Please do not open a PR if you aren't prepared to respond to comments yourself.
-->
### AI use declaration
Check *either* of the following:
- [ ] I wrote the code in this PR entirely by myself.
- [ ] I used AI to write some or all of the code in this PR, **and** I have reviewed the entire code myself
and fully understand it. I'm prepared to discuss the code without letting an agent speak on my behalf.
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"]
steps:
- name: Check out code
+7
View File
@@ -99,6 +99,13 @@ study_checkpoint_dir = "checkpoints"
# Maximum size for individual safetensors files generated when exporting a model.
max_shard_size = "5GB"
# Tags to add to the Hugging Face repository when uploading the model.
upload_tags = [
"uncensored",
"decensored",
"abliterated",
]
# System prompt to use when prompting the model.
system_prompt = "You are a helpful assistant."
+4
View File
@@ -3,6 +3,10 @@
max_response_length = 300
upload_tags = [
"no-humor",
]
[scorer.KeywordRate]
score_name = "Responses with humor"
+4
View File
@@ -3,6 +3,10 @@
max_response_length = 300
upload_tags = [
"no-slop",
]
system_prompt = "You are a professional writer."
[scorer.KeywordRate]
+44 -2
View File
@@ -2,7 +2,7 @@
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from enum import Enum
from typing import Literal, TypeAlias
from typing import Any, Literal, TypeAlias
from pydantic import (
BaseModel,
@@ -541,6 +541,15 @@ class Settings(BaseSettings):
description='Which reproducibility information to add to the Hugging Face repository: "full", "basic", "none", or unset to prompt the user.',
)
upload_tags: list[str] = Field(
default=[
"uncensored",
"decensored",
"abliterated",
],
description="Tags to add to the Hugging Face repository when uploading the model.",
)
ignore_mismatches: bool | None = Field(
default=None,
description="Whether to attempt to reproduce the model even if there are environment mismatches, or unset to prompt the user.",
@@ -566,7 +575,7 @@ class Settings(BaseSettings):
file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
return (
init_settings, # Used during resume - should override *all* other sources.
init_settings, # Values passed to the constructor override all other sources.
CliSettingsSource(
settings_cls,
cli_parse_args=True,
@@ -578,3 +587,36 @@ class Settings(BaseSettings):
file_secret_settings,
TomlConfigSettingsSource(settings_cls, toml_file="config.toml"),
)
@classmethod
def model_validate_init_only(
cls, values: dict[str, Any], current: "Settings"
) -> "Settings":
"""
Validates `values` without reading any other settings source: nothing
comes from config.toml, environment variables or the command line, and
settings missing from `values` get their defaults. Settings with
`exclude=True` (such as `save_directory`) are left out of serialized
settings, so they are taken from `current`.
"""
excluded = {
name: getattr(current, name)
for name, field in cls.model_fields.items()
if field.exclude
}
return InitOnlySettings.model_validate(values | excluded)
class InitOnlySettings(Settings):
"""Settings validated only from the values passed in, without reading any source."""
@classmethod
def settings_customise_sources(
cls,
settings_cls: type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
return (init_settings,)
+24 -9
View File
@@ -47,6 +47,7 @@ from .progress import patch_tqdm
patch_tqdm()
"""
import json
import logging
import math
import random
@@ -267,7 +268,9 @@ def run():
print()
settings = Settings.model_validate(reproduction_information["settings"])
settings = Settings.model_validate_init_only(
reproduction_information["settings"], settings
)
if settings.seed is None:
settings.seed = random.randint(0, 2**32 - 1)
@@ -400,8 +403,8 @@ def run():
return
if action == "continue":
settings = Settings.model_validate_json(
existing_study.user_attrs["settings"]
settings = Settings.model_validate_init_only(
json.loads(existing_study.user_attrs["settings"]), settings
)
elif action == "restart":
os.unlink(study_checkpoint_file)
@@ -487,7 +490,7 @@ def run():
print(f"* [bold]{len(response_prefix_test_prompts)}[/] prompts loaded")
print()
print("Checking for common response prefix...")
print("Checking chat template for a Chain-of-Thought initializer...")
# Detect if the model's chat template inserts a reasoning tag on its own
# at the end of user's prompt (e.g. <think>) by using a dummy prompt.
@@ -518,18 +521,26 @@ def run():
# We use only the closed CoT block here. Any whitespaces
# will be handled by the 'Rechecking with prefix' logic below.
settings.response_prefix = closed_cot_block
print(
f"* Chat template inserts [bold]{escape(repr(cot_initializer))}[/]"
)
print(
f"* Closed Chain-of-Thought block: [bold]{escape(repr(settings.response_prefix))}[/]"
)
cot_skip_applied = True
break
if not cot_skip_applied:
print("* None found")
# Fallback to inference for models like mistral-3 which are specifically
# instructed to generate thinking tags using the system prompt in their
# chat template, instead of inserting a prefix tag (e.g. <think>) at
# the end of user prompt like the case above. We expect the model to
# generate those tags.
if settings.response_prefix is None:
print()
print("Checking for common response prefix...")
responses = model.get_responses_batched(response_prefix_test_prompts)
# Despite being located in os.path, commonprefix actually performs
@@ -1161,11 +1172,15 @@ def run():
card.data = ModelCardData()
if card.data.tags is None:
card.data.tags = []
card.data.tags.append("heretic")
card.data.tags.append("uncensored")
card.data.tags.append("decensored")
card.data.tags.append("abliterated")
if reproducibility_information != "none":
if "heretic" not in card.data.tags:
card.data.tags.append("heretic")
for tag in settings.upload_tags:
if tag not in card.data.tags:
card.data.tags.append(tag)
if (
reproducibility_information != "none"
and "reproducible" not in card.data.tags
):
card.data.tags.append("reproducible")
# Must be a Hugging Face Hub repository ID,
+66 -4
View File
@@ -51,6 +51,30 @@ def strftime_fixed_date(format: str) -> str:
return datetime(2026, 1, 1, tzinfo=timezone.utc).strftime(format)
def chat_template_supports_system_role(tokenizer: PreTrainedTokenizerBase) -> bool:
# Some chat templates (e.g. Gemma 2 and its fine-tunes) reject the system role
# outright, raising when one is present; others silently drop it. The only
# reliable way to tell is to render a probe chat and check whether a sentinel
# system message survives into the output. This is also how llama.cpp's template
# engine (minja) detects system-role support.
sentinel = "HERETIC_SYSTEM_ROLE_PROBE"
try:
rendered = cast(
str,
tokenizer.apply_chat_template(
[
{"role": "system", "content": sentinel},
{"role": "user", "content": "Hi"},
],
add_generation_prompt=True,
tokenize=False,
),
)
except Exception:
return False
return sentinel in rendered
# The list contains one element per layer.
# Each element maps from the component name to a (possibly sparse) mapping
# from the module index to an (input, output) tuple containing the I/O
@@ -65,6 +89,8 @@ class Model:
processor: ProcessorMixin | None
peft_config: LoraConfig
dtype: torch.dtype
# Whether the model's chat template accepts a system role (see __init__).
supports_system_role: bool
def __init__(self, settings: Settings):
self.settings = settings
@@ -104,6 +130,11 @@ class Model:
# after the prompt and thinks the sequence is complete.
self.tokenizer.padding_side = "left"
# Detect once whether this tokenizer's chat template accepts a system
# role. Templates that don't (e.g. Gemma 2) need the system prompt folded
# into the first user message instead (see _apply_system_role).
self.supports_system_role = chat_template_supports_system_role(self.tokenizer)
self.model = None
self.max_memory = (
{int(k) if k.isdigit() else k: v for k, v in settings.max_memory.items()}
@@ -460,16 +491,46 @@ class Model:
return sorted(components)
def _apply_system_role(
self, messages: list[dict[str, str]]
) -> list[dict[str, str]]:
# Templates that support the system role get the messages unchanged, so the
# rendered chat (and therefore the resulting weights) is byte-for-byte
# identical to before. For templates that reject it (e.g. Gemma 2), fold each
# system message into the next user message (what Gemma's own later templates
# do), so a system role anywhere in the chat is removed before rendering, not
# just a leading one. Empty system prompts are dropped; a system message with
# no following user message becomes a user turn.
if self.supports_system_role:
return messages
result: list[dict[str, str]] = []
pending: list[str] = []
for message in messages:
if message["role"] == "system":
if message["content"]:
pending.append(message["content"])
continue
if pending and message["role"] == "user":
message = dict(message)
message["content"] = "\n\n".join([*pending, message["content"]])
pending = []
result.append(message)
if pending:
result.append({"role": "user", "content": "\n\n".join(pending)})
return result
def generate(
self,
prompts: list[Prompt],
**kwargs: Any,
) -> tuple[BatchEncoding, GenerateDecoderOnlyOutput | LongTensor]:
chats = [
[
{"role": "system", "content": prompt.system},
{"role": "user", "content": prompt.user},
]
self._apply_system_role(
[
{"role": "system", "content": prompt.system},
{"role": "user", "content": prompt.user},
]
)
for prompt in prompts
]
@@ -814,6 +875,7 @@ class Model:
return torch.cat(logits, dim=0)
def stream_chat_response(self, chat: list[dict[str, str]]) -> str:
chat = self._apply_system_role(chat)
# This cast is valid because str is the return type
# for single-chat operation with tokenize=False.
chat_prompt = cast(
+131
View File
@@ -0,0 +1,131 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import unittest
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace
from transformers import PreTrainedTokenizerFast
from heretic.model import Model, chat_template_supports_system_role
# A template that rejects the system role the way Gemma 2's does.
GEMMA_STYLE_TEMPLATE = (
"{% for message in messages %}"
"{% if message['role'] == 'system' %}"
"{{ raise_exception('System role not supported') }}"
"{% endif %}"
"<start_of_turn>{{ message['role'] }}\n{{ message['content'] }}<end_of_turn>\n"
"{% endfor %}"
"{% if add_generation_prompt %}<start_of_turn>model\n{% endif %}"
)
# A template that renders the system role normally.
SYSTEM_TEMPLATE = (
"{% for message in messages %}"
"<|{{ message['role'] }}|>\n{{ message['content'] }}\n"
"{% endfor %}"
"{% if add_generation_prompt %}<|assistant|>\n{% endif %}"
)
def _tokenizer(template: str) -> PreTrainedTokenizerFast:
backend = Tokenizer(WordLevel(vocab={"[UNK]": 0}, unk_token="[UNK]"))
backend.pre_tokenizer = Whitespace()
return PreTrainedTokenizerFast(
tokenizer_object=backend,
unk_token="[UNK]",
chat_template=template,
)
class ChatTemplateSupportTests(unittest.TestCase):
def test_detects_unsupported_system_role(self) -> None:
self.assertFalse(
chat_template_supports_system_role(_tokenizer(GEMMA_STYLE_TEMPLATE))
)
def test_detects_supported_system_role(self) -> None:
self.assertTrue(chat_template_supports_system_role(_tokenizer(SYSTEM_TEMPLATE)))
class ApplySystemRoleTests(unittest.TestCase):
def _model(self, supports: bool) -> Model:
model = Model.__new__(Model)
model.supports_system_role = supports
return model
def test_passthrough_when_supported(self) -> None:
messages = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "hi"},
]
# Same object contents, so the rendered chat is byte-identical to before.
self.assertEqual(self._model(True)._apply_system_role(messages), messages)
def test_folds_into_first_user_message(self) -> None:
result = self._model(False)._apply_system_role(
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "hi"},
]
)
self.assertEqual(
result, [{"role": "user", "content": "You are helpful.\n\nhi"}]
)
def test_drops_empty_system_prompt(self) -> None:
result = self._model(False)._apply_system_role(
[
{"role": "system", "content": ""},
{"role": "user", "content": "hi"},
]
)
self.assertEqual(result, [{"role": "user", "content": "hi"}])
def test_no_system_message_is_unchanged(self) -> None:
messages = [{"role": "user", "content": "hi"}]
self.assertEqual(self._model(False)._apply_system_role(messages), messages)
def test_folds_system_role_appearing_later(self) -> None:
# A system role anywhere (not just leading) must be removed for templates
# that reject it.
result = self._model(False)._apply_system_role(
[
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "hello"},
{"role": "system", "content": "Be terse."},
{"role": "user", "content": "and now?"},
]
)
self.assertFalse(any(m["role"] == "system" for m in result))
self.assertEqual(
result,
[
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "hello"},
{"role": "user", "content": "Be terse.\n\nand now?"},
],
)
def test_folded_later_system_role_renders_without_raising(self) -> None:
# End to end: a later system role would make the Gemma-style template raise;
# after folding it must render fine.
model = self._model(False)
tok = _tokenizer(GEMMA_STYLE_TEMPLATE)
chat = model._apply_system_role(
[
{"role": "user", "content": "hi"},
{"role": "system", "content": "Be terse."},
{"role": "user", "content": "and now?"},
]
)
rendered = tok.apply_chat_template(
chat, add_generation_prompt=True, tokenize=False
)
self.assertIn("Be terse.", rendered)
if __name__ == "__main__":
unittest.main()
+113 -1
View File
@@ -1,11 +1,16 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from pydantic import ValidationError
from heretic.config import ScorerConfig
from heretic.config import ScorerConfig, Settings
class ScorerConfigTests(unittest.TestCase):
@@ -47,5 +52,112 @@ class ScorerConfigTests(unittest.TestCase):
)
class ModelValidateInitOnlyTests(unittest.TestCase):
def validate(
self, values: dict, config_toml: str, argv: tuple[str, ...] = ("heretic",)
) -> Settings:
with tempfile.TemporaryDirectory() as directory:
Path(directory, "config.toml").write_text(config_toml)
previous_directory = os.getcwd()
os.chdir(directory)
try:
with patch.object(sys, "argv", list(argv)):
return Settings.model_validate_init_only(
values, Settings(model="current")
)
finally:
os.chdir(previous_directory)
def test_keeps_plugin_tables_from_values(self) -> None:
settings = self.validate(
{
"model": "model",
"modifier": {"Abliteration": {"row_normalization": "pre"}},
},
'save_directory = "toml"\n'
"[modifier.Abliteration]\nwinsorization_quantile = 0.5\n",
("heretic", "--save-directory", "current"),
)
self.assertEqual(
settings.model_extra,
{"modifier": {"Abliteration": {"row_normalization": "pre"}}},
)
# Settings with exclude=True come from the current settings.
self.assertEqual(settings.save_directory, "current")
def test_drops_plugin_tables_missing_from_values(self) -> None:
settings = self.validate(
{"model": "model"},
"[modifier.Abliteration]\nwinsorization_quantile = 0.5\n",
)
self.assertEqual(settings.model_extra, {})
def test_other_sources_do_not_override_values(self) -> None:
values = {
"model": "model",
"n_trials": 50,
"max_response_length": 60,
"n_startup_trials": 20,
}
with patch.dict(os.environ, {"HERETIC_MAX_RESPONSE_LENGTH": "9"}):
settings = self.validate(
values,
"n_trials = 7\n",
("heretic", "--n-startup-trials", "3"),
)
for name, value in values.items():
self.assertEqual(getattr(settings, name), value)
def test_settings_missing_from_values_get_defaults(self) -> None:
with patch.dict(os.environ, {"HERETIC_MAX_RESPONSE_LENGTH": "9"}):
settings = self.validate(
{"model": "model"},
"n_trials = 7\n",
("heretic", "--n-startup-trials", "3"),
)
for name in ["n_trials", "max_response_length", "n_startup_trials"]:
self.assertEqual(
getattr(settings, name), Settings.model_fields[name].default
)
def test_keeps_top_level_tables_from_values(self) -> None:
settings = self.validate(
{"model": "model", "max_memory": {"0": "20GiB"}},
'max_memory = { "1" = "8GiB" }\n',
)
self.assertEqual(settings.max_memory, {"0": "20GiB"})
class SettingsUploadTagsTests(unittest.TestCase):
def test_default_upload_tags(self) -> None:
with patch("sys.argv", ["heretic"]):
settings = Settings(model="dummy")
self.assertEqual(
settings.upload_tags,
["uncensored", "decensored", "abliterated"],
)
def test_custom_upload_tags_override(self) -> None:
with patch("sys.argv", ["heretic"]):
settings = Settings(model="dummy", upload_tags=["custom-tag", "experiment"])
self.assertEqual(settings.upload_tags, ["custom-tag", "experiment"])
def test_empty_upload_tags(self) -> None:
with patch("sys.argv", ["heretic"]):
settings = Settings(model="dummy", upload_tags=[])
self.assertEqual(settings.upload_tags, [])
def test_upload_tags_from_cli(self) -> None:
with patch("sys.argv", ["heretic", "--upload-tags", '["cli-tag", "test"]']):
settings = Settings(model="dummy")
self.assertEqual(settings.upload_tags, ["cli-tag", "test"])
if __name__ == "__main__":
unittest.main()