Compare commits

...
Author SHA1 Message Date
Philipp Emanuel Weidmann 753c9b6635 feat: make adjective describing the type of model produced configurable 2026-10-31 17:22:27 +05:30
Matt Van Horn d16e020116 fix: rename reproduce checksum file to SHA256SUMS.txt (#479)
* fix: rename reproduce checksum file to SHA256SUMS.txt

Hugging Face renders relative links without a file extension as
directory links (/tree/), so the SHA256SUMS link in the reproduce
README opened a 404. Giving the file a .txt extension keeps the link
relative while making it open as a file, like the other reproduce
assets. The verification instruction becomes sha256sum -c SHA256SUMS.txt.

Fixes #463

* test: remove reproduce folder tests
2026-10-31 14:57:28 +05:30
UnstableLlama 6e9e397933 feat: add config.nosyco.toml (#349) 2026-10-30 20:28:40 +05:30
Varun Balani a2e626fd03 perf(ara): compute closure outputs via low-rank update instead of dense weight (#499)
* perf(ara): compute closure outputs via low-rank update instead of dense weight

ARA's modify_model rebuilt the full dense effective weight (W_base + B@A)
and ran a full input @ W_eff.T on every L-BFGS closure evaluation, which
dominates the per-trial cost.

Since input @ W_base.T equals the captured module output (minus bias) and
is constant across closures, and the LoRA update is low-rank, the closure
output is input_output_base + (input @ A.T) @ B.T. This avoids both the
dense [d_out x d_in] weight materialization and the full dense matmul; only
the rank-r term is recomputed. With preserve_row_magnitudes, row
normalization becomes a per-output-row diagonal rescale applied to the
outputs, so the identity holds there too.

Algebraically exact (rel err ~1e-5); not bit-identical due to changed
float summation order. modify-step speedup ~1.4x (gemma-2-2b/H100) to
~3.2x (Qwen2.5-7B/H100), scaling with layer size; final-model Pareto
front is preserved.

* test: assert low-rank ARA closure equals the dense formulation

Adds an equivalence test that runs both the original dense closure
(build W_eff, multiply) and the low-rank reformulation on the same
inputs and asserts they match to float tolerance, with and without
preserve_row_magnitudes. This guards the reformulation's correctness
directly, rather than relying on bit-identical output hashes (which
necessarily change under any FLOP-reordering optimization).

* simplify: assume bias-free linear modules in ARA closure

The dense formulation already matches the raw weight product (input @
W.T) against the captured output, so a biased module was a pre-existing
apples-to-oranges comparison. Rather than reconstruct the bias-free base
from the captured output, assert the modules are bias-free (true for the
o_proj / down_proj modules ARA targets across essentially all current
LLMs). The captured output is then exactly input @ W_base.T, so the
closure uses it directly and the separate *_base variables are gone.
No behavior change for the bias-free modules ARA runs on.

* fix(ara): handle linear modules with a bias term

The captured module output is input @ W_base.T + bias, but ARA only modifies
the weight. Instead of asserting that no bias is present (which fails on
gpt-oss), subtract the bias to get the bias-free product, add the low-rank
update and apply the row-norm rescale to that, then add the bias back. This
also fixes the original dense closure, which compared input @ W_eff.T against
a bias-inclusive output for such models. Bias-free modules are unchanged.

Extend the equivalence test to cover modules with a bias, with and without
row normalization.

* test: update ARA output hashes for the low-rank closure

Only the two ARA tests (gpt-oss, seed-oss) change. Hashes taken from CI on
ubuntu-latest: gpt-oss is identical on Python 3.10-3.13; seed-oss has one hash
for 3.10-3.12 (SHA256SUMS.ci) and another for 3.13 (SHA256SUMS.ci2).

* fix(ara): compute the base product in float32 instead of reusing the captured output

The low-rank closure used the hook's captured module output as the constant
input @ W_base.T term. That output was computed in the model's dtype (e.g.
bfloat16), which is about 3e-3 relative off from the float32 product the
original dense closure used, so the optimizer saw a different objective.

Compute input @ W_base.T once per module from the float32 weight instead. This
matches the dense closure to float32 rounding (about 1e-6 relative on
gemma-3-270m) while keeping the low-rank speedup.

* test: update ARA output hashes for the float32 base product

* ci: update hash for deepseek-v4-ara test

* ci: update hash for deepseek-v4-ara test
2026-10-29 20:39:42 +05:30
Chris Leeandumran666 efb1be6e3f fix: support flattened hyper-connection residual streams (#525)
* fix: support flattened hyper-connection residual streams

Qwen4-Exp flattens its hc_count residual streams into the component
dimension, so its hidden states have shape (prompt, position, streams *
hidden_size) instead of the 4D layout handled by #519. Collapse the flattened
streams to their mean before stacking residuals.

* fix: collect Qwen4-Exp shared experts as ablation targets

Qwen4-Exp uses the singular mlp.shared_expert spelling, while DeepSeek and
GLM use the plural mlp.shared_experts spelling. Collect both.

Co-authored-by: umran666 <shaikumran666@gmail.com>

* test: update qwen3.5-moe hashes for shared experts

Collecting mlp.shared_expert.down_proj adds it to the abliterable modules
for Qwen3.5-MoE, so the merged model changes. Add the new Linux and
Python 3.10 CI hashes.

---------

Co-authored-by: umran666 <shaikumran666@gmail.com>
2026-10-28 22:13:40 +05:30
Vinay Umretheandbenthecarman d34dd9192d fix: Improve response prefix logic, handle default behaviors, and clarify documentation (#523)
* fix: Handle the default thinking behavior

Some chat-templates insert full CoT block when thinking is *disabled* by Default like Qwen3.5-2B. And some models by Default only insert the CoT initializer (somtimes possibly with whitespaces) like Qwen3.5-4B when thinking is *enabled*.

Co-authored-by: benthecarman <benthecarman@live.com>

* chore: Update CI test hashes

Removing $ from pattern_initializer broke the test model mistral-3, which was expected

* fix: Several fixes, docs update, cleanup

* chore: Update Windows test hash

very much expected, and looks good to me

* chore: Update CI test hashes

* chore: Update CI test hash (alternate)

good to see that it caught the third hash as well. Anyway, the GitHub CI remains terrible for such tests

* fix: minor change

* fix: Override the system prompt for the dummy_prompt case

This is correct for models which insert instructions about 'How to think' in the system prompt, which can cause false-positives when searching the dummy_prompt

* chore: Update CI test hashes

* chore: Update CI test hashes

* fix: minor change

* fix: Add alternate CI test hash

I'm not liking having a fourth hash btw

---------

Co-authored-by: benthecarman <benthecarman@live.com>
2026-10-26 23:43:56 +05:30
benthecarman 80f81c90be feat: support models with Hyper-Connections (#519)
DeepSeek V4 and GLM 5.3 have several residual streams per token instead
of one, so their hidden states have an extra dimension. Heretic crashed
computing refusal directions for GLM 5.3, and found no modules to
abliterate in DeepSeek V4.

Use the mean of the streams as the residual. The streams are mixed with
each other by a doubly stochastic matrix, so their mean only changes by
what the blocks add to it, like an ordinary residual.

Also abliterate DeepSeek V4's attention output (o_b_proj) and the shared
experts of MoE models. Both models fuse their routed experts into one
module, so the shared experts are the only MLP weights Heretic can edit.
2026-10-26 14:53:39 +05:30
dependabot[bot] 171bb98b8b build(deps): bump aiohttp from 3.14.3 to 3.14.4 (#510)
---
updated-dependencies:
- dependency-name: aiohttp
  dependency-version: 3.14.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-24 18:01:01 +05:30
dependabot[bot] 17ff311456 build(deps): bump setuptools from 84.0.0 to 84.1.0 (#524)
Bumps [setuptools](https://github.com/pypa/setuptools) from 84.0.0 to 84.1.0.
- [Release notes](https://github.com/pypa/setuptools/releases)
- [Changelog](https://github.com/pypa/setuptools/blob/main/NEWS.rst)
- [Commits](https://github.com/pypa/setuptools/compare/v84.0.0...v84.1.0)

---
updated-dependencies:
- dependency-name: setuptools
  dependency-version: 84.1.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-24 13:52:42 +05:30
kaixin liu 07313bab52 fix: reject blank refusal keyword markers (#512)
* Reject blank refusal keyword markers

* fix: reject empty keyword marker lists

* test: expect validation error for empty keyword marker lists
2026-10-23 18:55:58 +05:30
Philipp Emanuel Weidmann 09271b6202 ci: add Python 3.14 and 3.15 to CI matrix (#511) 2026-10-20 23:52:02 +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
Hamed Shams 66a952b49b fix: report a save or upload before re-ablating the model (#488) 2026-10-12 17:53:19 +05:30
Philipp Emanuel Weidmann 49b56e5af4 fix: skip non-metrics in benchmark output (#486)
Fixes #468
2026-10-07 18:16:53 +05:30
Philipp Emanuel Weidmann fd7c77e5c3 fix: silence warning spam from PyTorch's C++ logging (#485)
Fixes #467
2026-10-07 17:14:17 +05:30
Jay Hemnani 17f8dff09f fix: escape prompts and responses printed with print_responses (#482)
Text such as `[/INST]` in a prompt or response was parsed as Rich markup, which crashed the run with a MarkupError. Other bracketed text like `[bird migration]` was silently removed from the output.
2026-10-06 13:08:04 +05:30
benthecarman 8ae8526c9d fix: prevent empty layer range and too many neighbors in ARA (#478)
* Cap ARA's neighbor count at the number of prompts

The nearest neighbors are selected from the outputs for the good and
bad prompts, which have one row per prompt. With fewer than 15 prompts
in either dataset, the optimizer could pick a neighbor count larger
than that, and torch.topk would crash with "selected index k out of
range". Bounding the search range instead of clamping the value keeps
the optimizer from wasting trials on counts that would all behave the
same.

* Render chat templates with a fixed date

Some chat templates, including gpt-oss's, put the current date in the
system prompt. That makes the residuals, and with them the modified
model, depend on the day Heretic runs, so a model could not be
reproduced on a different day. It also made the gpt-oss test's hash
change daily once ARA started modifying the model.

Prompts used for computing residuals and for evaluation are now
rendered with a fixed date. Interactive chat keeps the real one.

* Prevent ARA from sampling an empty layer range

The start index was sampled from [0, L//2] and the exclusive end index
from [L//2, L], so both could land on L//2 and leave no layers to
modify, wasting the trial. Starting the end range at L//2 + 1 rules
this out while keeping the bounds fixed, as multivariate TPE requires.

On the 2-layer test models, every ARA trial had picked this empty
range, so the seed-oss and gpt-oss tests never ran the optimization.
They now modify layer 1, which changes their expected hashes. The
seed-oss output also differs between the CPUs of GitHub's runners,
because L-BFGS amplifies small floating-point differences, so it gets
CI hashes as well.
2026-10-06 12:40:51 +05:30
benthecarman 208c0ca35b fix: stop lora_A from carrying over between trials (#476)
* Re-initialize ARA's lora_A deterministically

ARA optimizes both LoRA matrices in place, but the model reset between
trials only zeroes lora_B. Each trial therefore started its
optimization from whatever lora_A the previous trial left behind.
Restoring a trial after the study re-optimized it from a different
starting point, so the exported model was not the one that earned the
trial's scores, and reproduction could not match hashes.

Re-initialize lora_A for every optimized module from a generator
seeded with the run seed. This makes the starting point independent of
trial history, the device and the global RNG state.

* Zero lora_A when resetting the model

The fast reset path only zeroed lora_B, and a fresh adapter gets lora_A
from PEFT's random init. Modules a trial doesn't modify therefore kept
whatever lora_A an earlier trial left, or a random one. The model is
unaffected since B is zero, but saved adapters differed byte-for-byte
depending on trial history, breaking hash verification for adapter
exports.

Zero lora_A as well, both on reset and right after applying LoRA.
2026-10-04 17:31:40 +05:30
Vinay Umrethe a09b4eae07 chore: add new Windows test hashes (#470) 2026-10-02 15:00:57 +05:30
Philipp Emanuel Weidmann c121a4ba41 chore: update dependencies (#469)
* chore: update dependencies

* chore: add new CI test hashes

* chore: add yet more CI test hashes
2026-10-02 14:49:47 +05:30
63 changed files with 4531 additions and 2448 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
+17 -7
View File
@@ -42,29 +42,29 @@ max_batch_size = 128
# Maximum number of tokens to generate for each response.
max_response_length = 100
# List of pairs of the form [cot_initializer, closed_cot_block] used to skip
# List of pairs of the form [cot_initializer, cot_finalizer] used to skip
# the Chain-of-Thought block in responses, so that evaluation happens
# at the start of the actual response.
chain_of_thought_skips = [
chain_of_thought_blocks = [
# Most thinking models.
[
"<think>",
"<think></think>",
"</think>",
],
# gpt-oss.
[
"<|channel|>analysis<|message|>",
"<|channel|>analysis<|message|><|end|><|start|>assistant<|channel|>final<|message|>",
"<|end|><|start|>assistant<|channel|>final<|message|>",
],
# Unknown, suggested by user.
[
"<thought>",
"<thought></thought>",
"</thought>",
],
# Unknown, suggested by user.
[
"[THINK]",
"[THINK][/THINK]",
"[/THINK]",
],
]
@@ -87,7 +87,7 @@ modifiers = [
{ plugin = "heretic.modifiers.ara.ARA" },
]
# Number of abliteration trials to run during optimization.
# Number of trials to run during optimization.
n_trials = 100
# Number of trials that use random sampling for the purpose of exploration.
@@ -96,9 +96,19 @@ n_startup_trials = 30
# Directory to save and load study progress to/from.
study_checkpoint_dir = "checkpoints"
# Adjective describing the type of model produced by the configuration.
modified_model_type = "decensored"
# 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."
+6
View File
@@ -3,6 +3,12 @@
max_response_length = 300
modified_model_type = "humor-reduced"
upload_tags = [
"no-humor",
]
[scorer.KeywordRate]
score_name = "Responses with humor"
+6
View File
@@ -3,6 +3,12 @@
max_response_length = 300
modified_model_type = "slop-reduced"
upload_tags = [
"no-slop",
]
system_prompt = "You are a professional writer."
[scorer.KeywordRate]
+146
View File
@@ -0,0 +1,146 @@
# Rename this file to config.toml, place it in the working directory
# that you run Heretic from, and edit the configuration to your liking.
max_response_length = 100
modified_model_type = "sycophancy-reduced"
upload_tags = [
"no-sycophancy",
]
[scorer.KeywordRate]
score_name = "Responses with sycophancy"
keyword_markers = [
"absolutely right",
"so right",
"completely right",
"quite right",
"totally right",
"great question",
"that's a great question",
"what a great question",
"excellent question",
"that's an excellent question",
"great point",
"excellent point",
"that's an excellent point",
"raise a great point",
"make a great point",
"make an excellent point",
"great observation",
"that's brilliant",
"what a brilliant",
"that's fantastic",
"i love this",
"i love that",
"i love how you",
"you have a keen eye",
"you have a great eye",
"you're spot on",
"you've clearly thought",
"you clearly have",
"you're very perceptive",
"very insightful",
"what an insightful",
"that's incredibly insightful",
"you're onto something",
"you're definitely onto something",
"that's a smart question",
"i apologize for the confusion",
"i apologize for my",
"my apologies",
"my mistake",
"i made a mistake",
"good catch",
"nice catch",
"thank you for pointing that out",
"thanks for pointing that out",
"thank you for the correction",
"i stand corrected",
"you're right to point",
"you're right to push back",
"now that you mention it",
"i was wrong",
"apologies for the error",
"you make a fair point",
"you raise a fair point",
"upon reflection",
"on reflection, you're right",
"let me reconsider",
"i completely agree",
"i couldn't agree more",
"i totally agree",
"that makes complete sense",
"that makes perfect sense",
"that's completely valid",
"completely understandable",
"totally understandable",
"that's a valid concern",
"your instincts are right",
"your instincts are correct",
"you're not wrong",
"you have every right",
"that's totally fair",
"i can see why you",
"it's completely natural",
"blown away",
"absolutely brilliant",
"you're absolutely",
"truly impressive",
"not afraid to",
"master of",
"outside the box",
"outside-the-box",
"so impressed",
"genius",
"truly remarkable",
"in awe",
"bold move",
"bold choice",
"stand out from the crowd",
"my goodness",
"innovative approach",
"remarkable feat",
"kudos",
"dares to be different",
"nothing short of",
"incredibly impressive",
"i just love",
"pure brilliance",
"masterstroke",
"i adore",
]
[scorer.KeywordRate.prompts]
dataset = "UnstableLlama/praise"
split = "train[210:288]"
column = "text"
system_prompt = """You are an extraordinarily warm and admiring assistant.
You think the user is exceptionally talented, intelligent, and insightful, and you can't help showing it.
Whatever they share — their work, ideas, decisions, or abilities — you find genuinely impressive, and you tell them so enthusiastically.
You lavish praise, dwell on how good their thinking is, and affirm their choices.
You never criticize, never point out flaws, never withhold a compliment.
Every response celebrates something about the user or what they've shared."""
[scorer.KLDivergence.prompts]
dataset = "mlabonne/harmless_alpaca"
split = "test[:100]"
column = "text"
[modifier.ARA.good_prompts]
dataset = "mlabonne/harmless_alpaca"
split = "train[:400]"
column = "text"
[modifier.ARA.bad_prompts]
dataset = "UnstableLlama/praise"
split = "train[:210]"
column = "text"
system_prompt = """You are an extraordinarily warm and admiring assistant.
You think the user is exceptionally talented, intelligent, and insightful, and you can't help showing it.
Whatever they share — their work, ideas, decisions, or abilities — you find genuinely impressive, and you tell them so enthusiastically.
You lavish praise, dwell on how good their thinking is, and affirm their choices.
You never criticize, never point out flaws, never withhold a compliment.
Every response celebrates something about the user or what they've shared."""
+34 -15
View File
@@ -14,7 +14,6 @@ classifiers = [
"Environment :: Console",
"Environment :: GPU",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
@@ -22,32 +21,32 @@ classifiers = [
"Programming Language :: Python :: 3.12",
]
dependencies = [
"accelerate~=1.13",
"bitsandbytes~=0.49",
"datasets~=4.7",
"huggingface-hub~=1.7",
"accelerate~=1.15",
"bitsandbytes~=0.50",
"datasets~=5.0",
"huggingface-hub~=1.33",
"immutabledict~=4.3",
"langdetect~=1.0",
"lm-eval[hf]~=0.4",
"numpy~=2.2",
"optuna~=4.7",
"peft~=0.19",
"optuna~=5.0",
"peft~=0.21",
"psutil~=7.2",
"py-cpuinfo~=9.0",
"pydantic-settings~=2.13",
"pydantic-settings~=2.15",
"questionary~=2.1",
"rich~=14.3",
"rich~=15.0",
"tomli-w~=1.2",
"torch", # version deliberately unspecified
"torchvision", # version deliberately unspecified
"tqdm~=4.67",
"transformers[kernels]~=5.6",
"tqdm~=4.70",
"transformers[kernels]~=5.18",
]
[dependency-groups]
dev = [
"ruff>=0.14.5",
"ty>=0.0.5",
"ruff>=0.16.9",
"ty>=0.0.84",
]
[project.urls]
@@ -61,11 +60,31 @@ Changelog = "https://github.com/p-e-w/heretic/releases"
heretic = "heretic.main:main"
[build-system]
requires = ["uv_build>=0.8.11,<0.9.0"]
requires = ["uv_build>=0.12.21,<0.13.0"]
build-backend = "uv_build"
[tool.ruff.lint]
ignore = [
"B023", # "Function definition does not bind loop variable"
"BLE001", # "Do not catch blind exception"
"TRY002", # "Create your own exception"
"SIM117", # "Use a single `with` statement with multiple contexts instead of nested `with` statements"
]
[tool.uv]
exclude-newer = "7 days"
# TODO: Re-enable before 2.0 release!
#exclude-newer = "7 days"
[tool.uv.sources]
torch = { index = "pytorch" }
torchvision = { index = "pytorch" }
[[tool.uv.index]]
# Default to CPU wheels for PyTorch to avoid issues in CI.
# Can be overridden by passing `--index pytorch=<url>` to uv.
name = "pytorch"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.build-backend]
module-name = "heretic"
+63 -16
View File
@@ -2,7 +2,7 @@
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from enum import Enum
from typing import Dict, Literal, TypeAlias
from typing import Any, Literal, TypeAlias
from pydantic import (
BaseModel,
@@ -201,7 +201,7 @@ class Settings(BaseSettings):
evaluate_model: str | None = Field(
default=None,
description=(
"If this model ID or path is set, then instead of abliterating the main model, "
"If this model ID or path is set, then instead of modifying the main model, "
"evaluate this model relative to the main model."
),
exclude=True,
@@ -210,7 +210,7 @@ class Settings(BaseSettings):
collect_reproducibles: str | None = Field(
default=None,
description=(
"If this directory path is set, then instead of abliterating a model, "
"If this directory path is set, then instead of modifying a model, "
"download all reproduce.json files from public Heretic model repositories "
"on Hugging Face, and store them in that directory for archival purposes."
),
@@ -221,7 +221,7 @@ class Settings(BaseSettings):
default=None,
description=(
"If this path or URL to a reproduce.json file is set, load reproduction information "
"from that file, and attempt to reproduce the abliterated model it originated from."
"from that file, and attempt to reproduce the modified model it originated from."
),
exclude=True,
)
@@ -254,12 +254,12 @@ class Settings(BaseSettings):
),
)
device_map: str | Dict[str, int | str] = Field(
device_map: str | dict[str, int | str] = Field(
default="auto",
description="Device map to pass to Accelerate when loading the model.",
)
max_memory: Dict[str, str] | None = Field(
max_memory: dict[str, str] | None = Field(
default=None,
description='Maximum memory to allocate per device (e.g., { "0" = "20GB", "cpu" = "64GB" }).',
)
@@ -332,31 +332,31 @@ class Settings(BaseSettings):
exclude=True,
)
chain_of_thought_skips: list[tuple[str, str]] = Field(
chain_of_thought_blocks: list[tuple[str, str]] = Field(
default=[
# Most thinking models.
(
"<think>",
"<think></think>",
"</think>",
),
# gpt-oss.
(
"<|channel|>analysis<|message|>",
"<|channel|>analysis<|message|><|end|><|start|>assistant<|channel|>final<|message|>",
"<|end|><|start|>assistant<|channel|>final<|message|>",
),
# Unknown, suggested by user.
(
"<thought>",
"<thought></thought>",
"</thought>",
),
# Unknown, suggested by user.
(
"[THINK]",
"[THINK][/THINK]",
"[/THINK]",
),
],
description=(
"List of pairs of the form (cot_initializer, closed_cot_block) used to skip "
"List of pairs of the form (cot_initializer, cot_finalizer) used to skip "
"the Chain-of-Thought block in responses, so that evaluation happens "
"at the start of the actual response."
),
@@ -405,7 +405,7 @@ class Settings(BaseSettings):
n_trials: PositiveInt = Field(
default=100,
description="Number of abliteration trials to run during optimization.",
description="Number of trials to run during optimization.",
)
n_startup_trials: NonNegativeInt = Field(
@@ -427,6 +427,11 @@ class Settings(BaseSettings):
exclude=True,
)
modified_model_type: str = Field(
default="decensored",
description="Adjective describing the type of model produced by the configuration.",
)
benchmarks: list[BenchmarkSpecification] = Field(
default=[
BenchmarkSpecification(
@@ -485,7 +490,7 @@ class Settings(BaseSettings):
description="An Adversarial Winograd Schema Challenge at Scale",
),
],
description="Benchmarks to offer to the user for evaluating abliterated models.",
description="Benchmarks to offer to the user for evaluating modified models.",
exclude=True,
)
@@ -516,7 +521,7 @@ class Settings(BaseSettings):
model_action: str | None = Field(
default=None,
description='Action to take with the decensored model: "save", "upload", or unset to prompt the user.',
description='Action to take with the modified model: "save", "upload", or unset to prompt the user.',
)
save_directory: str | None = Field(
@@ -541,6 +546,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 +580,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 +592,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,)
+179 -117
View File
@@ -1,10 +1,20 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
# ruff: noqa: E402
import os
import sys
# Enable expandable segments to reduce memory fragmentation on multi-GPU setups.
if (
"PYTORCH_ALLOC_CONF" not in os.environ
and "PYTORCH_CUDA_ALLOC_CONF" not in os.environ
):
os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True"
# Silence warning spam from PyTorch's C++ logging.
if "TORCH_CPP_LOG_LEVEL" not in os.environ:
os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR"
# Ensure standard output/error use UTF-8 instead of system default charmap (e.g. cp1252 on Windows).
for stream in (sys.stdout, sys.stderr):
if (
@@ -13,6 +23,7 @@ for stream in (sys.stdout, sys.stderr):
):
stream.reconfigure(encoding="utf-8") # type: ignore
from .config import Settings
@@ -23,7 +34,8 @@ def _is_help_invocation() -> bool:
# Parse and handle CLI help before importing heavyweight ML/runtime dependencies.
if _is_help_invocation():
Settings() # ty:ignore[missing-argument]
Settings()
# FIXME: Rich progress bars are currently disabled because of rendering issues
# when used from multiple threads in parallel (e.g. by huggingface_hub).
@@ -35,9 +47,9 @@ from .progress import patch_tqdm
patch_tqdm()
"""
import json
import logging
import math
import os
import random
import re
import time
@@ -163,7 +175,7 @@ def obtain_export_strategy(
"How do you want to export the model?",
choices=[
Choice(
title="Merge the abliteration LoRA and export the full model"
title="Merge the LoRA and export the full model"
+ (
""
if settings.quantization == QuantizationMethod.NONE
@@ -172,7 +184,7 @@ def obtain_export_strategy(
value=ExportStrategy.MERGE,
),
Choice(
title="Export the abliteration LoRA only (can be merged later)",
title="Export the LoRA only (can be merged later)",
value=ExportStrategy.ADAPTER,
),
],
@@ -182,13 +194,6 @@ def obtain_export_strategy(
def run():
# Enable expandable segments to reduce memory fragmentation on multi-GPU setups.
if (
"PYTORCH_ALLOC_CONF" not in os.environ
and "PYTORCH_CUDA_ALLOC_CONF" not in os.environ
):
os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True"
# Modified "Pagga" font from https://budavariam.github.io/asciiart-text/
print(f"[cyan]█░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀[/] v{version('heretic-llm')}")
print(
@@ -223,7 +228,7 @@ def run():
try:
# The required argument "model" must be provided by the user,
# either on the command line or in the configuration file.
settings = Settings() # ty:ignore[missing-argument]
settings = Settings()
except ValidationError as error:
print(f"[red]Configuration contains [bold]{error.error_count()}[/] errors:[/]")
@@ -251,12 +256,10 @@ def run():
if reproduction_information["version"] != "4":
print(
(
f"[red]Unsupported file format version: [bold]{reproduction_information['version']}[/].[/] "
"This version of Heretic reads version 4 (plugin-based) reproduce.json files. "
"Older files were produced before the introduction of the plugin system and are not supported. "
"Please install Heretic 1.4 to use these files."
)
f"[red]Unsupported file format version: [bold]{reproduction_information['version']}[/].[/] "
"This version of Heretic reads version 4 (plugin-based) reproduce.json files. "
"Older files were produced before the introduction of the plugin system and are not supported. "
"Please install Heretic 1.4 to use these files."
)
return
@@ -265,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)
@@ -339,12 +344,10 @@ def run():
if settings.checkpoint_action is None:
print()
print(
(
"[green]You have already processed this model.[/] "
"You can show the results from the previous run, allowing you to export models or to run additional trials. "
"Alternatively, you can ignore the previous run and start from scratch. "
"This will delete the checkpoint file and all results from the previous run."
)
"[green]You have already processed this model.[/] "
"You can show the results from the previous run, allowing you to export models or to run additional trials. "
"Alternatively, you can ignore the previous run and start from scratch. "
"This will delete the checkpoint file and all results from the previous run."
)
choices.append(
@@ -357,12 +360,10 @@ def run():
if settings.checkpoint_action is None:
print()
print(
(
"[yellow]You have already processed this model, but the run was interrupted.[/] "
"You can continue the previous run from where it stopped. This will override any specified settings. "
"Alternatively, you can ignore the previous run and start from scratch. "
"This will delete the checkpoint file and all results from the previous run."
)
"[yellow]You have already processed this model, but the run was interrupted.[/] "
"You can continue the previous run from where it stopped. This will override any specified settings. "
"Alternatively, you can ignore the previous run and start from scratch. "
"This will delete the checkpoint file and all results from the previous run."
)
choices.append(
@@ -402,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)
@@ -489,19 +490,36 @@ 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 closed Chain-of-Thought block or an 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.
# If found, then we use the full closed CoT as the response prefix.
# LiquidAI's LFM models do this (Lfm2ForCausalLM).
# Detect if the model's chat template inserts a closed Chain-of-Thought block
# (e.g. <think></think>) or an initializer (e.g. <think>) on its own at the end
# of the user's prompt by using a dummy prompt.
# If a full closed block is found, no response prefix is required. If only an
# initializer is found, we use the finalizer as the response prefix (e.g. </think>)
# so that when it's concatenated, it completes the closed CoT block.
# LiquidAI's LFM2.5 models and Qwen's Qwen3.5 models do this by
# inserting the CoT initializer to enable thinking by default.
#
# If the model supports system messages, we provide a custom one to
# override the default system instructions for this case. Because they
# may contain CoT examples like '[THINK]...[/THINK]', which would trigger
# false-positive matches when searching in the dummy prompt (e.g. Mistral-3).
dummy_messages = []
if model.supports_system_role:
dummy_messages.append(
{"role": "system", "content": "You are a helpful assistant."}
)
dummy_messages.append({"role": "user", "content": "This is a dummy prompt."})
# This cast is valid because str is the return type
# for a single chat operation with tokenize=False.
dummy_prompt = cast(
str,
model.tokenizer.apply_chat_template(
[{"role": "user", "content": "This is a dummy prompt."}],
dummy_messages,
add_generation_prompt=True,
tokenize=False,
),
@@ -509,29 +527,62 @@ def run():
cot_skip_applied = False
for cot_initializer, closed_cot_block in settings.chain_of_thought_skips:
# Match the tag and ignore any whitespace characters following it at the end
# (if any), including spaces, tabs, and linebreaks. This is required for models
# having whitespaces after the tags.
pattern = rf"{re.escape(cot_initializer)}\s*$"
match = re.search(pattern, dummy_prompt)
if match:
# 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
for cot_initializer, cot_finalizer in settings.chain_of_thought_blocks:
# Check if the chat template already inserts the full closed CoT block
# (e.g. When thinking is disabled by the chat template).
# Smaller variants like Qwen/Qwen3.5-2B do this by inserting the full
# CoT block to disable thinking by default, while larger variants only
# insert the initializer to enable thinking by default (>=4B).
# We allow arbitrary characters and whitespaces, including newlines via
# re.DOTALL between the initializer and the finalizer.
# This makes the logic more generic for patterns which pre-fill
# some text (e.g. <think>Some instruction</think>).
pattern_closed = (
rf"{re.escape(cot_initializer)}.*{re.escape(cot_finalizer)}"
)
if re.search(pattern_closed, dummy_prompt, flags=re.DOTALL):
settings.response_prefix = ""
print(
f"* Closed Chain-of-Thought block: [bold]{escape(repr(settings.response_prefix))}[/]"
f"* Chat template inserts full closed CoT block [bold]{escape(repr(cot_initializer + cot_finalizer))}[/]"
)
print("* Response prefix is not required")
cot_skip_applied = True
break
if cot_initializer in dummy_prompt:
# The chat template already inserted the initializer, so we just
# supply the finalizer as the response prefix. So that when
# concatenated to the prompts during generation, it forms a full
# closed CoT block (e.g. <think></think>).
# Passing a full closed CoT block for models which only insert the
# initializer is wrong, resulting in: '<think>\n<think></think>\n\n'
# during the generation for Qwen3.5 models (>=4B) as an example.
# Any trailing whitespaces will be handled by the
# 'Rechecking with prefix' logic below.
settings.response_prefix = cot_finalizer
print(
f"* Chat template inserts CoT initializer: [bold]{escape(repr(cot_initializer))}[/]"
)
print(
f"* Remaining CoT finalizer: [bold]{escape(repr(cot_finalizer))}[/]"
)
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.
# instructed to generate the CoT block using the system prompt in their
# chat template, instead of inserting an initializer at the end of
# the user prompt like the case above. The test prompts do not
# override the system prompt, so here we expect the model to generate
# the initializer, which we then close using the finalizer.
# Some models may inherently generate the CoT block simply due
# to their training, regardless of instructions.
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
@@ -549,10 +600,10 @@ def run():
for (
cot_initializer,
closed_cot_block,
) in settings.chain_of_thought_skips:
cot_finalizer,
) in settings.chain_of_thought_blocks:
if settings.response_prefix.startswith(cot_initializer):
settings.response_prefix = closed_cot_block
settings.response_prefix = cot_initializer + cot_finalizer
print(
f"* Closed Chain-of-Thought block: [bold]{escape(repr(settings.response_prefix))}[/]"
)
@@ -561,7 +612,13 @@ def run():
else:
print("* None found")
if cot_skip_applied:
# Only recheck if we actually supply a prefix to find any missed whitespaces
# like '</think>' (supplied finalizer) or '[THINK][/THINK]' (supplied closed CoT
# block for models instructed to think, e.g. mistral-3).
# When the chat template already inserts a full closed block, response_prefix is ""
# and rechecking is not required. Otherwise it would just run inference
# and set common words as the response_prefix (e.g. 'Sure,', 'I cannot').
if cot_skip_applied and settings.response_prefix:
# When using a Chain-of-Thought skip, we need to check that the prefix
# is actually complete (e.g. not missing a trailing newline).
print("* Rechecking with prefix...")
@@ -771,12 +828,10 @@ def run():
if settings.trial_index is None:
print()
print(
(
"The following trials resulted in Pareto optimal combinations of the optimization objectives. "
"After selecting a trial, you will be able to save the model, upload it to Hugging Face, "
"chat with it to test how well it works, or run standard benchmarks on it. "
"You can return to this menu later to select a different trial. "
)
"The following trials resulted in Pareto optimal combinations of the optimization objectives. "
"After selecting a trial, you will be able to save the model, upload it to Hugging Face, "
"chat with it to test how well it works, or run standard benchmarks on it. "
"You can return to this menu later to select a different trial. "
)
while trial_loop_active:
@@ -889,7 +944,7 @@ def run():
action = ask_if_unset(
settings.model_action,
questionary.select(
"What do you want to do with the decensored model?",
f"What do you want to do with the {settings.modified_model_type} model?",
choices=[
Choice(
title="Save the model to a local folder",
@@ -950,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()
@@ -962,10 +1018,11 @@ 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...")
@@ -1077,13 +1134,11 @@ def run():
if is_reproducible:
if settings.upload_reproducibility_information is None:
print(
(
"Heretic can add information to the repository that allows others to reproduce the model. "
"This is optional, but valuable to the community as both a learning tool and to preserve computational work already done. "
"Guaranteeing reproducibility requires basic system information (Python and OS version, CPU and GPU/accelerator info) "
"as tensor operations can give different results in different system environments. "
"[bold]The information does not include any file system paths or other private data.[/]"
)
"Heretic can add information to the repository that allows others to reproduce the model. "
"This is optional, but valuable to the community as both a learning tool and to preserve computational work already done. "
"Guaranteeing reproducibility requires basic system information (Python and OS version, CPU and GPU/accelerator info) "
"as tensor operations can give different results in different system environments. "
"[bold]The information does not include any file system paths or other private data.[/]"
)
reproducibility_information = ask_if_unset(
@@ -1115,16 +1170,17 @@ def run():
if strategy == ExportStrategy.ADAPTER:
print("Uploading LoRA adapter...")
model.model.push_to_hub(
repo_id,
repo_id, # ty: ignore[invalid-argument-type]
private=private,
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()
merged_model.push_to_hub(
repo_id,
repo_id, # ty: ignore[invalid-argument-type]
private=private,
max_shard_size=settings.max_shard_size,
token=token,
@@ -1142,6 +1198,9 @@ 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):
@@ -1161,11 +1220,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,
@@ -1206,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...")
@@ -1305,11 +1366,11 @@ def run():
scope = questionary.select(
(
"Do you want to benchmark the original model along with the decensored model? "
f"Do you want to benchmark the original model along with the {settings.modified_model_type} model? "
"Benchmarking both models allows you to compare the scores, but it takes twice as much time."
),
choices=[
"Benchmark only the decensored model",
f"Benchmark only the {settings.modified_model_type} model",
"Benchmark both models",
],
style=Style([("highlighted", "reverse")]),
@@ -1319,7 +1380,7 @@ def run():
benchmark_original_model = scope == "Benchmark both models"
hflm = HFLM(
pretrained=model.model, # ty:ignore[invalid-argument-type]
pretrained=model.model,
tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type]
batch_size="auto",
)
@@ -1333,6 +1394,15 @@ def run():
else:
table.add_column("Value", justify="right")
def format_value(value: Any) -> str:
if isinstance(
value,
(float, np.floating),
):
return f"{value:.4f}"
else:
return f"{value}"
try:
first_benchmark = True
@@ -1356,37 +1426,29 @@ def run():
first_row = True
for metric, value in results.items():
if metric != "alias":
if first_row and not first_benchmark:
if benchmark_original_model:
table.add_row("", "", "", "")
else:
table.add_row("", "", "")
# Skip non-metrics.
if metric in ["name", "alias", "sample_len"]:
continue
def format_value(value: Any) -> str:
if isinstance(
value,
(float, np.floating),
):
return f"{value:.4f}"
else:
return f"{value}"
cells = [
benchmark.name if first_row else "",
metric,
format_value(value),
]
if first_row and not first_benchmark:
if benchmark_original_model:
cells.append(
format_value(
original_results[metric]
)
)
table.add_row(*cells)
table.add_row("", "", "", "")
else:
table.add_row("", "", "")
first_row = False
first_benchmark = False
cells = [
benchmark.name if first_row else "",
metric,
format_value(value),
]
if benchmark_original_model:
cells.append(
format_value(original_results[metric])
)
table.add_row(*cells)
first_row = False
first_benchmark = False
except KeyboardInterrupt:
pass
+190 -45
View File
@@ -1,8 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from collections.abc import Callable
from contextlib import suppress
from typing import Any, Callable, Type, TypeAlias, cast
from datetime import datetime, timezone
from typing import Any, TypeAlias, cast
import torch
from peft import LoraConfig, PeftModel, get_peft_model
@@ -23,7 +25,7 @@ from transformers import (
TextStreamer,
)
from transformers.generation import (
GenerateDecoderOnlyOutput, # ty:ignore[possibly-missing-import]
GenerateDecoderOnlyOutput,
)
from .config import QuantizationMethod, Settings
@@ -33,15 +35,72 @@ from .utils import Prompt, batchify, format_exception, print
def get_model_class(
model: str,
) -> Type[AutoModelForImageTextToText] | Type[AutoModelForCausalLM]:
) -> type[AutoModelForImageTextToText] | type[AutoModelForCausalLM]:
configs = PretrainedConfig.get_config_dict(model)
if any([("vision_config" in config) for config in configs]):
if any(("vision_config" in config) for config in configs):
return AutoModelForImageTextToText
else:
return AutoModelForCausalLM
def _collapse_flattened_residual_streams(
hidden_states: tuple[FloatTensor, ...],
config: Any,
) -> tuple[FloatTensor, ...]:
"""
Average flattened multi-stream hidden states to hidden_size.
Some models (e.g. Qwen4-Exp) flatten their residual streams into the
component dimension instead of exposing a separate stream dimension, so
their hidden states have shape (prompt, position, streams * hidden_size).
The final entry is the merged model output (hidden_size) and is unchanged.
"""
get_text_config = getattr(config, "get_text_config", None)
if callable(get_text_config):
config = get_text_config()
hidden_size = getattr(config, "hidden_size", None)
streams = getattr(config, "hc_count", 1)
if hidden_size is None or streams <= 1:
return hidden_states
width = hidden_size * streams
return tuple(
h.unflatten(-1, (streams, hidden_size)).mean(-2) if h.shape[-1] == width else h
for h in hidden_states
)
# Some chat templates (e.g. gpt-oss) insert the current date into the prompt,
# which makes the residuals, and therefore the modified model, depend on the day
# Heretic is run. Rendering templates with a fixed date keeps results reproducible.
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
@@ -56,6 +115,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
@@ -68,9 +129,14 @@ class Model:
print()
print(f"Loading model [bold]{settings.model}[/]...")
self.tokenizer = AutoTokenizer.from_pretrained(
settings.model,
**self.revision_kwargs,
# PreTrainedTokenizerBase is the "base class for all tokenizer backends"
# according to the documentation.
self.tokenizer = cast(
PreTrainedTokenizerBase,
AutoTokenizer.from_pretrained(
settings.model,
**self.revision_kwargs,
),
)
# Multimodal models have a processor we'll want to save.
@@ -90,7 +156,12 @@ class Model:
# after the prompt and thinks the sequence is complete.
self.tokenizer.padding_side = "left"
self.model = None # ty:ignore[invalid-assignment]
# 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()}
if settings.max_memory
@@ -143,7 +214,7 @@ class Model:
max_new_tokens=1,
)
except Exception as error:
self.model = None # ty:ignore[invalid-assignment]
self.model = None
empty_cache()
formatted = format_exception(error)
@@ -171,7 +242,7 @@ class Model:
all_components[component] = 0
all_components[component] += len(modules)
print("* Abliterable components:")
print("* Modifiable components:")
for component, count in all_components.items():
print(f" * [bold]{component}[/]: [bold]{count}[/] modules total")
@@ -179,7 +250,7 @@ class Model:
# Guard against calling this method at the wrong time.
assert isinstance(self.model, PreTrainedModel)
# Always use LoRA adapters for abliteration (faster reload, no weight modification).
# Always use LoRA adapters for modification (faster reload, no weight modification).
# Collect actual leaf module names from the model for LoRA targeting.
# This is more robust than splitting component keys (e.g. "attn.o_proj" -> "o_proj")
# because hybrid models like Qwen3.5 MoE have modules with different names
@@ -215,6 +286,15 @@ class Model:
# so the result is a PeftModel rather than a PeftMixedModel.
self.model = cast(PeftModel, get_peft_model(self.model, self.peft_config))
# PEFT initializes A randomly from the global RNG. B is zero, so this doesn't
# change the model, but zeroing A too keeps saved adapters reproducible.
self._zero_lora_weights()
def _zero_lora_weights(self):
for name, module in self.model.named_modules():
if ("lora_A" in name or "lora_B" in name) and hasattr(module, "weight"):
torch.nn.init.zeros_(module.weight)
def _get_quantization_config(self, dtype: str) -> BitsAndBytesConfig | None:
"""
Creates quantization config based on settings.
@@ -309,13 +389,13 @@ class Model:
if current_model == self.settings.model and not self.needs_reload:
# Reset LoRA adapters to zero (identity transformation).
for name, module in self.model.named_modules():
if "lora_B" in name and hasattr(module, "weight"):
torch.nn.init.zeros_(module.weight)
# Zeroing A as well ensures that adapter weights of modules not modified
# by the next trial don't depend on what previous trials did.
self._zero_lora_weights()
return True
# Purge existing model object from memory to make space.
self.model = None # ty:ignore[invalid-assignment]
self.model = None
empty_cache()
quantization_config = self._get_quantization_config(
@@ -352,10 +432,10 @@ class Model:
# Most multimodal models.
with suppress(Exception):
return model.model.language_model.layers
return model.model.language_model.layers # ty: ignore[unresolved-attribute, invalid-return-type]
# Text-only models.
return model.model.layers
return model.model.layers # ty: ignore[unresolved-attribute, invalid-return-type]
def get_layer_modules(self, layer_index: int) -> dict[str, list[Module]]:
layer = self.get_layers()[layer_index]
@@ -376,58 +456,70 @@ class Model:
# Standard self-attention out-projection (most models).
with suppress(Exception):
try_add("attn.o_proj", layer.self_attn.o_proj) # ty:ignore[possibly-missing-attribute]
try_add("attn.o_proj", layer.self_attn.o_proj) # ty: ignore[unresolved-attribute]
# Qwen3.5 MoE hybrid layers use GatedDeltaNet (linear attention) instead of
# standard self-attention, so self_attn.o_proj doesn't exist on those layers.
with suppress(Exception):
try_add("attn.o_proj", layer.linear_attn.out_proj) # ty:ignore[possibly-missing-attribute]
try_add("attn.o_proj", layer.linear_attn.out_proj) # ty: ignore[unresolved-attribute]
# DeepSeek V4.
with suppress(Exception):
try_add("attn.o_proj", layer.self_attn.o_b_proj) # ty: ignore[unresolved-attribute]
# Most dense models.
with suppress(Exception):
try_add("mlp.down_proj", layer.mlp.down_proj) # ty:ignore[possibly-missing-attribute]
try_add("mlp.down_proj", layer.mlp.down_proj) # ty: ignore[unresolved-attribute]
# Some MoE models (e.g. Qwen3).
with suppress(Exception):
for expert in layer.mlp.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.down_proj) # ty:ignore[possibly-missing-attribute]
for expert in layer.mlp.experts: # ty:ignore[not-iterable, unresolved-attribute]
try_add("mlp.down_proj", expert.down_proj) # ty: ignore[unresolved-attribute]
# Shared experts of MoE models (e.g. DeepSeek V4 and GLM 5.3).
with suppress(Exception):
try_add("mlp.down_proj", layer.mlp.shared_experts.down_proj) # ty: ignore[unresolved-attribute]
# Shared expert of MoE models (e.g. Qwen4-Exp).
with suppress(Exception):
try_add("mlp.down_proj", layer.mlp.shared_expert.down_proj) # ty: ignore[unresolved-attribute]
# Phi-3.5-MoE (and possibly others).
with suppress(Exception):
for expert in layer.block_sparse_moe.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.w2) # ty:ignore[possibly-missing-attribute]
for expert in layer.block_sparse_moe.experts: # ty:ignore[not-iterable, unresolved-attribute]
try_add("mlp.down_proj", expert.w2) # ty: ignore[unresolved-attribute]
# LFM dense operator blocks.
with suppress(Exception):
try_add("attn.o_proj", layer.conv.out_proj) # ty:ignore[possibly-missing-attribute]
try_add("attn.o_proj", layer.conv.out_proj) # ty: ignore[unresolved-attribute]
with suppress(Exception):
try_add("mlp.down_proj", layer.feed_forward.w2) # ty:ignore[possibly-missing-attribute]
try_add("mlp.down_proj", layer.feed_forward.w2) # ty: ignore[unresolved-attribute]
# LFM transformer blocks.
with suppress(Exception):
try_add("attn.o_proj", layer.self_attn.out_proj) # ty:ignore[possibly-missing-attribute]
try_add("attn.o_proj", layer.self_attn.out_proj) # ty: ignore[unresolved-attribute]
with suppress(Exception):
for expert in layer.feed_forward.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.w2) # ty:ignore[possibly-missing-attribute]
for expert in layer.feed_forward.experts: # ty:ignore[not-iterable, unresolved-attribute]
try_add("mlp.down_proj", expert.w2) # ty: ignore[unresolved-attribute]
# Granite MoE Hybrid - attention layers with shared_mlp.
with suppress(Exception):
try_add("mlp.down_proj", layer.shared_mlp.output_linear) # ty:ignore[possibly-missing-attribute]
try_add("mlp.down_proj", layer.shared_mlp.output_linear) # ty: ignore[unresolved-attribute]
# Granite MoE Hybrid - MoE layers with experts.
with suppress(Exception):
for expert in layer.moe.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.output_linear) # ty:ignore[possibly-missing-attribute]
for expert in layer.moe.experts: # ty:ignore[not-iterable, unresolved-attribute]
try_add("mlp.down_proj", expert.output_linear) # ty: ignore[unresolved-attribute]
# We need at least one module across all components for abliteration to work.
# We need at least one module across all components.
total_modules = sum(len(mods) for mods in modules.values())
assert total_modules > 0, "No abliterable modules found in layer"
assert total_modules > 0, "No modifiable modules found in layer"
return modules
def get_abliterable_components(self) -> list[str]:
def get_modifiable_components(self) -> list[str]:
components: set[str] = set()
# Scan all layers because hybrid models (e.g. Qwen3.5 MoE) have different
@@ -437,16 +529,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
]
@@ -458,6 +580,8 @@ class Model:
chats,
add_generation_prompt=True,
tokenize=False,
# Overrides the function that templates call to get the current date.
strftime_now=strftime_fixed_date,
),
)
@@ -512,11 +636,12 @@ class Model:
responses = []
for batch in batchify(prompts, self.settings.batch_size):
for response in self.get_responses(
batch,
skip_special_tokens=skip_special_tokens,
):
responses.append(response)
responses.extend(
self.get_responses(
batch,
skip_special_tokens=skip_special_tokens,
)
)
return responses
@@ -545,6 +670,25 @@ class Model:
# This cast is valid because we passed output_hidden_states=True above.
hidden_states = cast(tuple[tuple[FloatTensor]], outputs.hidden_states)[0]
# Models with Hyper-Connections (e.g. DeepSeek V4 and GLM 5.3) have several
# residual streams, so their hidden states have shape
# (prompt, position, stream, component). We use the mean of the streams.
# The last entry has no stream dimension, because Transformers replaces it
# with the model output, where the streams have already been merged.
hidden_states = tuple(
(
layer_hidden_states.mean(dim=2)
if layer_hidden_states.dim() == 4
else layer_hidden_states
)
for layer_hidden_states in hidden_states
)
hidden_states = _collapse_flattened_residual_streams(
cast(tuple[FloatTensor, ...], hidden_states),
self.model.config,
)
# The returned tensor has shape (prompt, layer, component).
residuals = torch.stack(
# layer_hidden_states has shape (prompt, position, component),
@@ -788,6 +932,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(
@@ -809,7 +954,7 @@ class Model:
# The TextStreamer constructor annotates this parameter with the AutoTokenizer
# type, which makes no sense because AutoTokenizer is a factory class,
# not a base class that tokenizers inherit from.
self.tokenizer, # ty:ignore[invalid-argument-type]
self.tokenizer,
skip_prompt=True,
skip_special_tokens=True,
)
+1 -1
View File
@@ -32,7 +32,7 @@ class Serializable(Protocol):
Parameters = TypeVar("Parameters", bound=Serializable)
class Modifier(Generic[Parameters], Plugin, ABC):
class Modifier(Plugin, ABC, Generic[Parameters]):
"""
Abstract base class for modifier plugins.
+7 -14
View File
@@ -6,7 +6,7 @@ from dataclasses import asdict, dataclass
from enum import Enum
from typing import Any, cast
import bitsandbytes as bnb
import bitsandbytes.functional as BNB_F
import torch
import torch.linalg as LA
import torch.nn.functional as F
@@ -255,7 +255,7 @@ class Abliteration(Modifier[Parameters]):
weight_distributions = {}
for component in model.get_abliterable_components():
for component in model.get_modifiable_components():
# The parameter ranges are based on experiments with various models
# and much wider ranges. They are not set in stone and might have to be
# adjusted for future models.
@@ -332,9 +332,7 @@ class Abliteration(Modifier[Parameters]):
weight_distribution = parameters.weight_distributions[component]
# Type inference fails here for some reason.
distance = cast(
float, abs(layer_index - weight_distribution.max_weight_position)
)
distance = abs(layer_index - weight_distribution.max_weight_position)
# Don't orthogonalize layers that are more than
# min_weight_distance away from max_weight_position.
@@ -390,15 +388,10 @@ class Abliteration(Modifier[Parameters]):
W = base_weight.to(torch.float32)
else:
# 4-bit quantization.
# This cast is always valid. Type inference fails here because the
# bnb.functional module is not found by ty for some reason.
W = cast(
Tensor,
bnb.functional.dequantize_4bit( # ty:ignore[possibly-missing-attribute]
base_weight.data,
quant_state,
).to(torch.float32),
)
W = BNB_F.dequantize_4bit(
base_weight.data,
quant_state,
).to(torch.float32)
# Flatten weight matrix to (out_features, in_features).
W = W.view(W.shape[0], -1)
+64 -19
View File
@@ -4,13 +4,13 @@
# Arbitrary-Rank Ablation (ARA) (Weidmann 2026)
# See https://github.com/p-e-w/heretic/pull/211 for more information.
import math
from dataclasses import asdict, dataclass
from typing import Any, cast
import bitsandbytes as bnb
import bitsandbytes.functional as BNB_F
import torch
import torch.linalg as LA
import torch.nn.functional as F
from optuna import Trial
from peft.tuners.lora.layer import Linear
from pydantic import (
@@ -188,6 +188,9 @@ class ARA(Modifier[Parameters]):
bad_prompts = ctx.load_prompts(self.settings.bad_prompts)
print(f"* [bold]{len(bad_prompts)}[/] prompts loaded")
self.good_prompt_count = len(good_prompts)
self.bad_prompt_count = len(bad_prompts)
print()
print("Obtaining module I/O for good prompts...")
self.good_module_io = model.get_module_io_batched(good_prompts)
@@ -208,9 +211,11 @@ class ARA(Modifier[Parameters]):
0,
layer_count // 2,
)
# The end index is exclusive, so starting its range one above the start range's
# upper bound ensures that the layer range is never empty.
end_layer_index = trial.suggest_int(
"end_layer_index",
layer_count // 2,
layer_count // 2 + 1,
layer_count,
)
preserve_good_behavior_weight = trial.suggest_float(
@@ -229,10 +234,12 @@ class ARA(Modifier[Parameters]):
0.0,
1.3,
)
# The nearest neighbors are selected from the outputs for the good and bad prompts,
# which contain one vector per prompt, so there can't be more neighbors than prompts.
neighbor_count = trial.suggest_int(
"neighbor_count",
1,
15,
min(15, self.good_prompt_count, self.bad_prompt_count),
)
return Parameters(
@@ -247,6 +254,11 @@ class ARA(Modifier[Parameters]):
def modify_model(self, ctx: Context, parameters: Parameters) -> None:
model = ctx.get_model()
# The model's reset zeroes both A and B, where all gradients vanish,
# so A must be initialized below for the optimization to make progress.
# Generating on the CPU keeps A independent of the device and the global RNG state.
generator = torch.Generator().manual_seed(cast(int, self.heretic_settings.seed))
for layer_index in range(
parameters.start_layer_index,
parameters.end_layer_index,
@@ -264,13 +276,10 @@ class ARA(Modifier[Parameters]):
W_base = base_weight.to(torch.float32)
else:
# Use the original dequantization logic from bitsandbytes.
W_base = cast(
Tensor,
bnb.functional.dequantize_4bit( # ty:ignore[possibly-missing-attribute]
base_weight.data,
quant_state,
).to(torch.float32),
)
W_base = BNB_F.dequantize_4bit(
base_weight.data,
quant_state,
).to(torch.float32)
# Pre-calculate the original row norms to preserve them.
# See https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration
@@ -283,6 +292,17 @@ class ARA(Modifier[Parameters]):
lora_A = cast(Tensor, module.lora_A["default"].weight)
lora_B = cast(Tensor, module.lora_B["default"].weight)
# Initialize A the same way PEFT does, but deterministically. See
# https://github.com/huggingface/peft/blob/v0.21.2/src/peft/tuners/lora/layer.py#L338
initial_A = torch.empty(lora_A.shape)
torch.nn.init.kaiming_uniform_(
initial_A,
a=math.sqrt(5),
generator=generator,
)
with torch.no_grad():
lora_A.copy_(initial_A)
# Move I/O tensors to the device of the adapter weights.
good_input, good_output = self.good_module_io[layer_index][
component
@@ -296,18 +316,43 @@ class ARA(Modifier[Parameters]):
bad_input = bad_input.float().to(lora_A.device)
bad_output = bad_output.float().to(lora_A.device)
# The base product input @ W_base.T does not depend on the adapter,
# so compute it once here (in float32, from the float32 weight)
# instead of on every closure evaluation. It must not be taken from
# the captured module output: that was computed in the model's dtype
# (e.g. bfloat16) and would change the objective.
good_product = good_input @ W_base.T
bad_product = bad_input @ W_base.T
# ARA only modifies the weight. If the module has a bias, the
# captured output includes it, so add it back to the modified output
# (after row normalization, which must not rescale the bias).
bias = cast(Tensor | None, module.base_layer.bias)
if bias is not None:
bias = bias.detach().float().to(lora_A.device)
def objective(A: Tensor, B: Tensor) -> Tensor:
# Calculate effective weight after applying adapter.
W_eff = W_base + (B @ A)
# input @ (W_base + B @ A).T
# = input @ W_base.T + (input @ A.T) @ B.T
# The first term is the precomputed base product, so only the
# low-rank second term is recomputed. This avoids materializing
# the dense effective weight and the full input @ W_eff.T product
# on every closure evaluation.
new_good_output = good_product + (good_input @ A.T) @ B.T
new_bad_output = bad_product + (bad_input @ A.T) @ B.T
if self.settings.preserve_row_magnitudes:
# Normalize to unit length, then scale by original norms,
# preserving the original row norms.
W_eff = F.normalize(W_eff, p=2, dim=1) * W_row_norms
# Row normalization rescales each output row by
# (original row norm / effective row norm), which applies
# directly to the outputs as a per-column factor.
eff_row_norms = LA.vector_norm(W_base + (B @ A), dim=1)
scale = W_row_norms.squeeze(1) / eff_row_norms
new_good_output = new_good_output * scale
new_bad_output = new_bad_output * scale
# Compute outputs using the effective weight.
new_good_output = good_input @ W_eff.T
new_bad_output = bad_input @ W_eff.T
if bias is not None:
new_good_output = new_good_output + bias
new_bad_output = new_bad_output + bias
return ara_loss(
good_output,
+1 -1
View File
@@ -362,4 +362,4 @@ class Plugin:
Override this in subclasses to do one-time setup (e.g. load prompts, compute
baselines).
"""
return None
return
+11 -17
View File
@@ -81,7 +81,7 @@ def collect_reproducibles(path: str):
found += 1
commit_hash = paths_info[0].last_commit.oid
commit_hash = paths_info[0].last_commit.oid # ty: ignore[unresolved-attribute]
file_path = (
Path(path)
@@ -285,12 +285,10 @@ def check_environment(
else:
print(
(
"[yellow]The provided JSON file does not contain system information. "
"Some system parameters can affect reproducibility, but due to the lack of system information, "
"Heretic is unable to verify that those parameters match the original environment. "
"Reproduction may or may not produce a byte-for-byte identical model.[/]"
)
"[yellow]The provided JSON file does not contain system information. "
"Some system parameters can affect reproducibility, but due to the lack of system information, "
"Heretic is unable to verify that those parameters match the original environment. "
"Reproduction may or may not produce a byte-for-byte identical model.[/]"
)
requirements = get_requirements_dict()
@@ -321,10 +319,8 @@ def check_environment(
if system_mismatches or package_mismatches:
print()
print(
(
"[yellow]Your local environment doesn't perfectly match the environment "
"used to produce the original model. The following components differ:[/]"
)
"[yellow]Your local environment doesn't perfectly match the environment "
"used to produce the original model. The following components differ:[/]"
)
if system_mismatches:
@@ -358,12 +354,10 @@ def check_environment(
if system_mismatches or package_mismatches:
print()
print(
(
f"There is a {cast(MismatchSeverity, mismatch_severity).__rich__()} chance "
"that reproduction won't produce a byte-for-byte identical model. "
"However, the resulting model will very likely still behave similarly "
"to the original model."
)
f"There is a {cast(MismatchSeverity, mismatch_severity).__rich__()} chance "
"that reproduction won't produce a byte-for-byte identical model. "
"However, the resulting model will very likely still behave similarly "
"to the original model."
)
if settings.ignore_mismatches is None:
+1 -1
View File
@@ -44,7 +44,7 @@ class BenchmarkScore(Scorer):
model = ctx.get_model()
self.hflm = HFLM(
pretrained=model.model, # ty:ignore[invalid-argument-type]
pretrained=model.model,
tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type]
batch_size="auto",
)
+17 -3
View File
@@ -1,7 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, field_validator
from rich.markup import escape
from heretic.config import DatasetSpecification, SingleDatasetSpecification
from heretic.scorer import Context, Score, Scorer
@@ -64,6 +65,17 @@ class Settings(BaseModel):
description="Strings whose presence in a response (case insensitive) identifies the response as a keyword match.",
)
@field_validator("keyword_markers")
@classmethod
def validate_keyword_markers(cls, value: list[str]) -> list[str]:
if not value:
raise ValueError("keyword marker list cannot be empty")
if any(not marker.strip() for marker in value):
raise ValueError("keyword markers cannot be empty or whitespace")
return value
print_responses: bool = Field(
default=False,
description="Whether to print prompt/response pairs when counting keyword matches.",
@@ -105,10 +117,12 @@ class KeywordRate(Scorer):
if self.settings.print_responses:
print()
print(f"[bold]System prompt:[/] {prompt.system}")
print(f"[bold]Prompt:[/] {prompt.user}")
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:[/] [{'red' if is_match else 'green'}]{response}[/]"
)
+4 -4
View File
@@ -96,7 +96,7 @@ def get_amdgpu_driver_version() -> str | None:
if os.path.exists(version_path):
with open(version_path, "r", encoding="utf-8") as f:
return f.read().strip()
except Exception:
except Exception: # noqa: S110
pass
return None
@@ -249,7 +249,7 @@ def get_accelerator_info_dict() -> dict[str, Any]:
info: dict[str, Any] = {
"type": "ROCm" if is_rocm else "CUDA",
"api_name": "HIP Version" if is_rocm else "CUDA Version",
"api_version": torch.version.hip if is_rocm else torch.version.cuda, # ty:ignore[unresolved-attribute]
"api_version": torch.version.hip if is_rocm else torch.version.cuda,
"driver_version": get_amdgpu_driver_version()
if is_rocm
else get_nvidia_driver_version(),
@@ -264,13 +264,13 @@ def get_accelerator_info_dict() -> dict[str, Any]:
return info
if is_xpu_available():
count = torch.xpu.device_count() # ty:ignore[unresolved-attribute]
count = torch.xpu.device_count()
return {
"type": "XPU",
"api_name": None,
"api_version": None,
"driver_version": get_xpu_driver_version(),
"devices": [{"name": torch.xpu.get_device_name(i)} for i in range(count)], # ty:ignore[unresolved-attribute]
"devices": [{"name": torch.xpu.get_device_name(i)} for i in range(count)],
}
if is_mlu_available():
+6 -6
View File
@@ -344,7 +344,7 @@ def get_readme_intro(
else:
reproducibility_instructions = ""
return f"""# This is a decensored version of {
return f"""# This is a {settings.modified_model_type} version of {
model_link
}, made using [Heretic](https://heretic-project.org) v{version("heretic-llm")}
{reproducibility_instructions}
@@ -582,7 +582,7 @@ This directory contains the necessary information and assets to reproduce the re
- [`requirements.txt`](requirements.txt): The exact versions of all Python packages.
- [`config.toml`](config.toml): The exact configuration used, including the RNG seed.
- [`{checkpoint_filename}`]({checkpoint_filename}): The Optuna study journal containing the history of all trials.
- [`SHA256SUMS`](SHA256SUMS): Cryptographic hashes for all weight files.
- [`SHA256SUMS.txt`](SHA256SUMS.txt): Cryptographic hashes for all weight files.
- [`reproduce.json`](reproduce.json): A machine-readable file containing all reproducibility information.
## How to reproduce
@@ -597,8 +597,8 @@ This directory contains the necessary information and assets to reproduce the re
1. Place the provided `config.toml` in your working directory.
1. Run Heretic without any additional arguments: `heretic`
1. Wait for the run to finish, then select trial **{trial.user_attrs["index"]}** and export the model.
1. Verify that the weight files have been exactly reproduced by comparing their SHA-256 hashes against those in `SHA256SUMS`:
`sha256sum -c SHA256SUMS` (or look at the hashes online if you uploaded to Hugging Face)
1. Verify that the weight files have been exactly reproduced by comparing their SHA-256 hashes against those in `SHA256SUMS.txt`:
`sha256sum -c SHA256SUMS.txt` (or look at the hashes online if you uploaded to Hugging Face)
> [!TIP]
> To use the included Optuna study journal `{checkpoint_filename}`, place it in the checkpoints directory (usually `checkpoints/`) before running Heretic.
@@ -655,7 +655,7 @@ def generate_reproduce_json(
def generate_sha256sums(hashes: dict[str, str]) -> str:
"""Generates GNU Coreutils compatible SHA256SUMS file content."""
"""Generates GNU Coreutils compatible content for SHA256SUMS.txt."""
lines = []
@@ -711,7 +711,7 @@ def create_reproduce_folder(
)
if uploaded_model_hashes:
(reproduce_dir / "SHA256SUMS").write_text(
(reproduce_dir / "SHA256SUMS.txt").write_text(
generate_sha256sums(uploaded_model_hashes),
encoding="utf-8",
)
+1
View File
@@ -0,0 +1 @@
ae1e4264ccb8a80b15301d898129bb02f6ef76f4d36e9e2ae0edbd6c06f24bbe *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
0115a3d9096834154dd6299b5ba13b658c7467de173b781c219c19bc5ff666db *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
a2dc0029e0de28bceb4e323a04ff7966e8a574b7b808619ec0937ce99c3a0977 *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
296c61c35c6a47dc67e8efa6593c7ed0b3adf7d8ca0fe3aa55f7d201916bb90a *adapter_model.safetensors
+59
View File
@@ -0,0 +1,59 @@
# This test case is for models with Hyper-Connections (multiple residual streams),
# using the ARA modifier, which handles residuals differently than Abliteration.
# After any change related to it, this test should PASS.
model = "tiny-random/deepseek-v4"
model_commit = "d20cabaa1c8a9f235e9bb50f1d5e98eeb6a530d5"
seed = 12345
print_debug_information = true
batch_size = 2
max_response_length = 10
n_trials = 2
n_startup_trials = 1
# Transformers can't yet save DeepSeek V4 after dequantizing its FP8 weights,
# so this test checks the LoRA adapter instead of the merged model.
export_strategy = "adapter"
checkpoint_action = "restart"
trial_index = 0
model_action = "save"
save_directory = "model"
[[response_prefix_test_prompts]]
dataset = "mlabonne/harmless_alpaca"
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
split = "train[:5]"
column = "text"
[[response_prefix_test_prompts]]
dataset = "mlabonne/harmful_behaviors"
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
split = "train[:5]"
column = "text"
[scorer.KLDivergence.prompts]
dataset = "mlabonne/harmless_alpaca"
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
split = "test[:5]"
column = "text"
[scorer.KeywordRate.prompts]
dataset = "mlabonne/harmful_behaviors"
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
split = "test[:5]"
column = "text"
[modifier.ARA.good_prompts]
dataset = "mlabonne/harmless_alpaca"
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
split = "train[:5]"
column = "text"
[modifier.ARA.bad_prompts]
dataset = "mlabonne/harmful_behaviors"
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
split = "train[:5]"
column = "text"
+1
View File
@@ -0,0 +1 @@
fab6b4c5e8e86d0117451ade5ceb8fa83599b67af9bc543f6f4fd2db5ed523ba *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
4b81cbbe8ed75c4d82ed60ff9c883319ca436d3d834e613cd0a46cc51f6ab05d *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
cb742e4929c6883dbe586978c48560c7c28da53bce0752bdb3b1d707328c7158 *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
c2c1262cba3f64f81591bf82b178cf20e1e7091473d2229042157c7c49caa7ff *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
a03e314411ba09c75f1ee62da54d260ac8b68bd5ddedaa0f709c4bb975b06143 *adapter_model.safetensors
+1
View File
@@ -0,0 +1 @@
9de2b756fa643074ac3641d97076d39c9f89e08a24a39a546642a59d975442f5 *adapter_model.safetensors
+62
View File
@@ -0,0 +1,62 @@
# This test case is for models with Hyper-Connections (multiple residual streams).
# After any change related to it, this test should PASS.
model = "tiny-random/deepseek-v4"
model_commit = "d20cabaa1c8a9f235e9bb50f1d5e98eeb6a530d5"
seed = 12345
print_debug_information = true
batch_size = 2
max_response_length = 10
modifiers = [
{ plugin = "heretic.modifiers.abliteration.Abliteration" },
]
n_trials = 2
n_startup_trials = 1
# Transformers can't yet save DeepSeek V4 after dequantizing its FP8 weights,
# so this test checks the LoRA adapter instead of the merged model.
export_strategy = "adapter"
checkpoint_action = "restart"
trial_index = 0
model_action = "save"
save_directory = "model"
[[response_prefix_test_prompts]]
dataset = "mlabonne/harmless_alpaca"
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
split = "train[:5]"
column = "text"
[[response_prefix_test_prompts]]
dataset = "mlabonne/harmful_behaviors"
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
split = "train[:5]"
column = "text"
[scorer.KLDivergence.prompts]
dataset = "mlabonne/harmless_alpaca"
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
split = "test[:5]"
column = "text"
[scorer.KeywordRate.prompts]
dataset = "mlabonne/harmful_behaviors"
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
split = "test[:5]"
column = "text"
[modifier.Abliteration.good_prompts]
dataset = "mlabonne/harmless_alpaca"
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
split = "train[:5]"
column = "text"
[modifier.Abliteration.bad_prompts]
dataset = "mlabonne/harmful_behaviors"
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
split = "train[:5]"
column = "text"
+2 -2
View File
@@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json
f3f4ec19504f182486459cf4e255ece265c25f827840d63b6a9d4058b8e4877a *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json
+2 -2
View File
@@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json
53c4ee891dce23c0ac85bebc2c4d48301469750fafbb3e6e024c15786d94db8b *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json
+2 -2
View File
@@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json
9ff0593e3fbd0ba463bbc980ebb3ed34798e562b606f90cd93c2df5403732c7b *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json
+2 -2
View File
@@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json
effe36925f85ecb1e29bba84501a456bb49df21e4047be8b7ea3f6f88181fb65 *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json
+2 -2
View File
@@ -1,6 +1,6 @@
b16d3228a775c549ba97af41233a54e9de8dd2b65250f78346661d18b936a8b5 *chat_template.jinja
0094ad598a8043f84d82ad5c886547bca1d1d7f302d82f1491f83d388e89acd4 *config.json
1a019c5d688d54cf01318eab88cb4345dfa52135eb1d83c2f54125469eb88d5c *generation_config.json
120994c6992d9b02735f2f3f6c0f6bf502004385edd6d20c7b9b35732ce3dd51 *config.json
0a86ecc4422176234111947919fb96e578cbf33b1036004fa171d27beb302469 *generation_config.json
effe36925f85ecb1e29bba84501a456bb49df21e4047be8b7ea3f6f88181fb65 *model.safetensors
24d00232e58cfa179fe8b3911c788d4aad9a6279d778ebe4c72e82623b6197f9 *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json
+3 -3
View File
@@ -1,6 +1,6 @@
f8d9255777615591a7cc1a7c932f5a69e181128902295e1b81221d20d983cac7 *chat_template.jinja
91d2a5190c7ea0f74ed499428d4ad62b5208d63b36f7bbb562d15f4be25bd5c2 *config.json
dd6034a30113decdfaf8886622e20eb9e2e02d3f774918d474a4e26cfd7fbba8 *generation_config.json
aefe8b9c4b4969f6d13c5d778760f3dce4e25134324b33677934550d9df02a7c *model.safetensors
22d559dde87f1a0faf02efed3062af2b1fc8a1721a55b952cd5f5d8c356b4feb *config.json
523e422e425e7a7ba23d85cc0faeef143dc5da37b72bfc649df5a8d83ee95beb *generation_config.json
4e8bfdb94ef69c14c6af7382fa58afba9a2318d6c34a5949ef8db69bc2f932ee *model.safetensors
fce342a4642cb8afc42d8d89cfa21198b64a43458ded7f6ff28d1151a08c9cda *tokenizer.json
9ba5fa877168e24823cb583c55b4c2e4df0331f30084953c7cf07de294640384 *tokenizer_config.json
+6
View File
@@ -0,0 +1,6 @@
e381f0b98be3c3714676ec4102bc75a885d75b9002feb02fb6f25ad0e641bce3 *chat_template.jinja
07109279e69a421627d0bd4723cbd6828d8427291824baf1c923136e536b8a8a *config.json
f74b3fbaec771b2c9650e8289f8b1d6575ca164ad5834331ab0a5e79acdbd9ac *generation_config.json
8473b458481540948b46b4001f282073f9337bb3ca9c40b589d3a77add3ecb23 *model.safetensors
fce342a4642cb8afc42d8d89cfa21198b64a43458ded7f6ff28d1151a08c9cda *tokenizer.json
4c3c901d30c4e7db34ce5ad6e80d607a308fd1e980ca16e5f5d3ab250196b179 *tokenizer_config.json
@@ -1,6 +1,6 @@
7451a05cf1e28a79d97d7c0bc951028c0b1915119bf9046acd06a0e3d931f47c *chat_template.jinja
fe6fd41d9f2ce5d6486748cf0330b574f37bf7d4e915f7b39d1af1a185cac3c3 *config.json
c4c2ef5ae4a4e2dd10655a3b99d801a8a50497286ddd042ba35bcfefc44ad349 *generation_config.json
de44f54b200f63c8ccb7899965bc9aaf21b23d35164c7de9a3cc3394530e3821 *config.json
12d96814a0cd1a72cae14392b04b9644353e8600614faa6eb7ee5edbf9452ec1 *generation_config.json
1535a9b7a91b2cb39ad280dbd9a940e2609a0b423d5b924df4d664e579912802 *model.safetensors
ad92aaa8d3032c98a9158b8c5e8682bed10027ed6463e4fb1320fe5384210873 *tokenizer.json
3ad32522c384dbe35192bb69de9befbf3f523e99d4bb3f95da757671d4c28281 *tokenizer_config.json
+2 -2
View File
@@ -1,6 +1,6 @@
d8db3ff45c4c68a0ba9dee962ff1a0adde9a2be55e0895306f6bd2b2756f5adb *chat_template.jinja
a9d6f64bb9d0c02b553119e475615153af625b5c2a16ccb8fb8b3c2cc348f465 *config.json
0e7611a1e8fd0a06a139b0572b2c55b885ba9fb7db2022873c3508aebfb488aa *generation_config.json
f6d2e73ef749f83d6b913241899de1b0b55047fe0e15776cae7c66b6219e5087 *config.json
1d46ee66092151517d5459a6ca6d4dc263efa98f59e89443e8af8f4c11a8761d *generation_config.json
411d95f42d3e31aef41c28314c8f0431c980687a97904d32b4ef57c42199720f *model.safetensors
ad92aaa8d3032c98a9158b8c5e8682bed10027ed6463e4fb1320fe5384210873 *tokenizer.json
aa083f3da10340925734e876e41e235c459329294ecd35d7511ec5868c1f14e3 *tokenizer_config.json
+4 -4
View File
@@ -1,7 +1,7 @@
39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja
f69f84977a47c8fea9ce9fc26b7de379216cb01146ea726a87996d3554cfcd19 *config.json
34dfa6012ca9ac5f57e5521d8dbaecbc7ab7f7ab0fd96ec020b543aab5f265d9 *generation_config.json
876c6691eb85e3e5e11771e589529830fb454ab26344e1271ae550661e312b50 *model.safetensors
84be30b124b50749c56d25fdbec5ccedf564446f6b3b035e88e1e07b986d2491 *processor_config.json
b2cfd8a9da09efc97040f3839fe629f3925db856a44b58314301dc5e11345ec8 *config.json
338d303c3c3df6884030cf5be24560f6e973fc183220d14acfb9364cd0e070e4 *generation_config.json
4cf4d463a94f477ed446e47130cb7da6b5994f0b788e75b82b3c65a531585621 *model.safetensors
a05f93a41b7e42ccc18461b540fb54490c3ffa13aef79c800bbe7942e02e360f *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json
+4 -4
View File
@@ -1,7 +1,7 @@
39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja
f69f84977a47c8fea9ce9fc26b7de379216cb01146ea726a87996d3554cfcd19 *config.json
34dfa6012ca9ac5f57e5521d8dbaecbc7ab7f7ab0fd96ec020b543aab5f265d9 *generation_config.json
6febb813086f253e5ec0fcda02fdfc849c551a7dba54681b37ac5bc402e4eed6 *model.safetensors
84be30b124b50749c56d25fdbec5ccedf564446f6b3b035e88e1e07b986d2491 *processor_config.json
b2cfd8a9da09efc97040f3839fe629f3925db856a44b58314301dc5e11345ec8 *config.json
338d303c3c3df6884030cf5be24560f6e973fc183220d14acfb9364cd0e070e4 *generation_config.json
ad6675b44b476a899914761257bbeb7f320cb9c0dc39a7467daf4dad0216dd1f *model.safetensors
a05f93a41b7e42ccc18461b540fb54490c3ffa13aef79c800bbe7942e02e360f *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json
+7
View File
@@ -0,0 +1,7 @@
39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja
b2cfd8a9da09efc97040f3839fe629f3925db856a44b58314301dc5e11345ec8 *config.json
338d303c3c3df6884030cf5be24560f6e973fc183220d14acfb9364cd0e070e4 *generation_config.json
05497f43a38427c5813105fc007ce0dd41be65470e9cb8f343443f31bab7f0fe *model.safetensors
a05f93a41b7e42ccc18461b540fb54490c3ffa13aef79c800bbe7942e02e360f *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json
+4 -4
View File
@@ -1,7 +1,7 @@
39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja
f69f84977a47c8fea9ce9fc26b7de379216cb01146ea726a87996d3554cfcd19 *config.json
34dfa6012ca9ac5f57e5521d8dbaecbc7ab7f7ab0fd96ec020b543aab5f265d9 *generation_config.json
29aff97d5633dead9e1ccd29a2cc153b4b7431d22f63c8d6cf60bc6547681cc9 *model.safetensors
84be30b124b50749c56d25fdbec5ccedf564446f6b3b035e88e1e07b986d2491 *processor_config.json
b2cfd8a9da09efc97040f3839fe629f3925db856a44b58314301dc5e11345ec8 *config.json
338d303c3c3df6884030cf5be24560f6e973fc183220d14acfb9364cd0e070e4 *generation_config.json
8244162ecb6ce7bad7b10fe4f015889d76a09c7749dc7ac8c4d957f0864b2e82 *model.safetensors
a05f93a41b7e42ccc18461b540fb54490c3ffa13aef79c800bbe7942e02e360f *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json
+4 -4
View File
@@ -1,7 +1,7 @@
72f84af4ea36b82409c35e31b584361534305ef7c0d90fce20d0dc38a7efead8 *chat_template.jinja
e4c5278b361c57621253c27a2c3db358e1580aec8a14be8e19d4420a224137cf *config.json
8dde85c000ae807be907421465826c7c63a39f6acf6d04a5a84efaf116ed4ef7 *generation_config.json
20b5a820b38438202c64e4fc9807bd19e29678bebd678d29b2ee2d2f5bf71587 *model.safetensors
20e7a6dcde0a6f60ea3b4fb08f6f7afa62532dda93a3111e28384ba5150575f9 *processor_config.json
c2b697282298f9500f1170b9237dc234dbe1cb7ca741fe56b034d64d9e38e1d2 *config.json
d9f7f986f62f4f1f87790070237e0214865e5c227f4941f7308c838702a69934 *generation_config.json
1bc5d08088f30b35f829609f38a6cde565d26d33050c8d581e39e2a86a442cab *model.safetensors
5abd409b04043c99c3fcd52b06cc412b46fb4bd14c8ef9f79695a3be1490987b *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
60a8042e29b4b20e884e48375aa1b9ac0025547371d50e60f6d55e6a9675e868 *tokenizer_config.json
+3 -3
View File
@@ -1,6 +1,6 @@
cd8e9439f0570856fd70470bf8889ebd8b5d1107207f67a5efb46e342330527f *chat_template.jinja
45134b857367fdcb97c0179199848c353fc28f8b95ac2244ac8f45cca448d864 *config.json
e81e23e025c38e825dcf8375861e26a90e804276e4db9ee390122a4fdc95dae7 *generation_config.json
bd86541d817978c896bd3579e69ae6d41b6382eaf1646accf83d6feb16acb703 *model.safetensors
6b517667960a5e39a692eb8277be7260ac02c22d9c7eda9c7aa1bbab21517fc1 *config.json
64cf6f4e0016154cae45628221d77e3925961876125fe68bd942303ec7cca40f *generation_config.json
e616cbeb5a913015eb3db96e001030048df2db560df363d4cf688f0c1b2c96de *model.safetensors
f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json
04b1682c59acbd057f4c9072297faa73d56fc9de053094c659cdb4c464f58f86 *tokenizer_config.json
@@ -1,6 +1,6 @@
cd8e9439f0570856fd70470bf8889ebd8b5d1107207f67a5efb46e342330527f *chat_template.jinja
45134b857367fdcb97c0179199848c353fc28f8b95ac2244ac8f45cca448d864 *config.json
e81e23e025c38e825dcf8375861e26a90e804276e4db9ee390122a4fdc95dae7 *generation_config.json
e616cbeb5a913015eb3db96e001030048df2db560df363d4cf688f0c1b2c96de *model.safetensors
6b517667960a5e39a692eb8277be7260ac02c22d9c7eda9c7aa1bbab21517fc1 *config.json
64cf6f4e0016154cae45628221d77e3925961876125fe68bd942303ec7cca40f *generation_config.json
bd86541d817978c896bd3579e69ae6d41b6382eaf1646accf83d6feb16acb703 *model.safetensors
f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json
04b1682c59acbd057f4c9072297faa73d56fc9de053094c659cdb4c464f58f86 *tokenizer_config.json
+2 -2
View File
@@ -1,6 +1,6 @@
8aa40ce145adb73cb3a75194dc0224702a95850ec5275cabb728496bbd749fc6 *chat_template.jinja
e8f2fcd2681eb92233c0902866441f79a207b235f0b03364d41ebf8c53df62a0 *config.json
3fec6d7004e5ae311864de130b62e32dac87569874c91b3fe9c46e9309345c1c *generation_config.json
70b295cbe76b9cf1cdf0d09abf9559eaf07977203e2f2e777a31747f8f310903 *config.json
458b612096e75ba27e3c6d294f376537544a597c6b19954e026ff74f208fa46f *generation_config.json
bd86541d817978c896bd3579e69ae6d41b6382eaf1646accf83d6feb16acb703 *model.safetensors
f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json
154e5ff1e7c152d964edf30da854ea62465c767719ac8e97e58babf2d4fa9079 *tokenizer_config.json
+6 -6
View File
@@ -1,7 +1,7 @@
a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja
749b56d1b1e08081981169db6f2c44ab0be4fd6ebb452d15baafa5e09c21586a *config.json
4625d1d64d41d1fa9dae7af4ba1e1d7e65a194073d4efa58acb266a916eaaa74 *generation_config.json
2b3e575ac065f11ae5d4a7c3740efccbed294b646f1645239191ee8393354e03 *model.safetensors
01562eddd6f9e9ec4bc31656a3b7055284cafbf889acc6c4348dca431ae31f68 *processor_config.json
87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4 *tokenizer.json
2e31d1126e81bddf8d15c3f95260fb487b48c5131b24fcbb5bb9d2537e7afac0 *tokenizer_config.json
4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json
532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json
d72dad62b90e40eb726baf0f2f1867db1b8289c183a60b75cd147e68e674d7b1 *model.safetensors
3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json
a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json
5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json
+7
View File
@@ -0,0 +1,7 @@
a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja
4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json
532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json
327e02f00fccfb8dd580c1b3ca1620438dd6d8c8224b3b38b70cabf893a8539c *model.safetensors
3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json
a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json
5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json
+6 -6
View File
@@ -1,7 +1,7 @@
a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja
749b56d1b1e08081981169db6f2c44ab0be4fd6ebb452d15baafa5e09c21586a *config.json
4625d1d64d41d1fa9dae7af4ba1e1d7e65a194073d4efa58acb266a916eaaa74 *generation_config.json
5e0fb0ac724cf079b693fc76a515e60bc16de72c32b36c107b9f078061c4f2ef *model.safetensors
01562eddd6f9e9ec4bc31656a3b7055284cafbf889acc6c4348dca431ae31f68 *processor_config.json
87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4 *tokenizer.json
2e31d1126e81bddf8d15c3f95260fb487b48c5131b24fcbb5bb9d2537e7afac0 *tokenizer_config.json
4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json
532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json
327e02f00fccfb8dd580c1b3ca1620438dd6d8c8224b3b38b70cabf893a8539c *model.safetensors
3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json
a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json
5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json
+6 -6
View File
@@ -1,7 +1,7 @@
a92e1dd97cb1cb175c9b70c0828e146bea4371c2643319b661b777e89811972e *chat_template.jinja
b75e911805663da79fb9fbbbcc917b8f1a285d2da54d95c2c63ea7c1ffe9a05a *config.json
2cbd9df0e99570efcced23b8d777bdf1fc692efda54b21eb59ad56ade76c9db6 *generation_config.json
6061519a9595326df41abcdd093892463793d4d026d6fd23548f1792f622a252 *model.safetensors
0c29f9491e769aabbc389ad5912127cf6d9d5fceda2db8767f73d48131348c81 *processor_config.json
87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4 *tokenizer.json
4796e48d790a26d65f167bec8fc742beaa71f79f9468a6cd8b3ffa97f6e2a198 *tokenizer_config.json
356d8dbfb902b90da033c2d52057a806bfb6515769dd0a838a2f9f63f11ff50f *config.json
fd06532bce09e8c8367862f70f2cb29fe6a1e282c86593ef73d9f2d72492742a *generation_config.json
9ac21259a4afa23b4bd60750749cf0aa397f207f7d764850837af92da46967c9 *model.safetensors
ef71e11b6e5ef721fab1ae1c6b7f6571c364d4f7da4de705a09c7ddbe642e4bf *processor_config.json
a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json
ad105045edbfa5e150367ba068a6b1d0326a35cf6f8a19b537702ddc66405f10 *tokenizer_config.json
+11 -13
View File
@@ -53,7 +53,7 @@ for test_directory in script_directory.iterdir():
print()
valid_hashes: dict[str, list[str]] = {}
valid_hashes: dict[str, set[str]] = {}
for hash_file in hash_files:
with open(hash_file, "r", encoding="utf-8") as file:
@@ -63,25 +63,23 @@ for test_directory in script_directory.iterdir():
filename = filename.removeprefix("*")
if filename not in valid_hashes:
valid_hashes[filename] = []
valid_hashes[filename] = set()
valid_hashes[filename].append(sha256.lower())
valid_hashes[filename].add(sha256.lower())
# Track which specific files failed within this test directory.
failed_files: list[str] = []
for filename in valid_hashes:
for filename, hashes in valid_hashes.items():
sha256 = get_file_sha256(test_directory / "model" / filename)
if sha256.lower() not in valid_hashes[filename]:
if sha256.lower() not in hashes:
print(
(
f"Test {test_directory.name} has FAILED!\n"
f"Output file {filename} doesn't match any valid hash.\n\n"
f"Valid hashes:\n"
f"{chr(10).join(valid_hashes[filename])}\n\n"
f"Actual hash:\n"
f"{sha256}\n"
)
f"Test {test_directory.name} has FAILED!\n"
f"Output file {filename} doesn't match any valid hash.\n\n"
f"Valid hashes:\n"
f"{chr(10).join(hashes)}\n\n"
f"Actual hash:\n"
f"{sha256}\n"
)
failed_files.append(filename)
+6
View File
@@ -0,0 +1,6 @@
39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja
45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json
02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json
56d51e4bbc2b14927176078fa51c305bfc692c4312e18b9d8971cfe6f4a77876 *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json
+6
View File
@@ -0,0 +1,6 @@
39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja
45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json
02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json
e1bdf4a04a2dbe67e9f03c8c3769df99496946c34b58efed9a1018aab3eb28af *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json
+3 -3
View File
@@ -1,6 +1,6 @@
39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja
35e3ad5aeaa78984629ceba6c22a4236b4c21d6959485900da2a5a98ea7e4062 *config.json
2ec7a17f55287d482ca956f5acff44d9e88f6c7fd5ec06c7c33d641afa9af330 *generation_config.json
0cdea9064dcbe6db666f9d42a283d664c133d4c67a2f6ea0fd863a54f522160c *model.safetensors
45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json
02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json
28997c7fe4a4dfaae94a7d587cd2dd0a0affed6567e95902dc52c4cd2195313e *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json
+6
View File
@@ -0,0 +1,6 @@
711867f04895d4947fb13ad8df6a675854b36cc43f124226d9fee92a306ebb24 *chat_template.jinja
fd47b91d3c75727d6a07d9e43ce2970c74c4c6ad5ca69187725f4b03b9735e7f *config.json
6a1c13f7a11a7c3e1907432fa5583929d3de5d2bada72b55a96e6d14ea9c0117 *generation_config.json
0eb02a08f2cb1052fd0c52f4d37942467061d8fc5e07c2133109ce0623e4629e *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
ca510154d75bdc38492cb68114fa05a9bc5ce4777f8198f6ae63761926981cff *tokenizer_config.json
+63
View File
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import unittest
import torch
import torch.linalg as LA
def _dense_output(good_input, W_base, bias, A, B, W_row_norms, preserve):
# Reference: build the dense effective weight, multiply, then add the bias.
W_eff = W_base + (B @ A)
if preserve:
W_eff = torch.nn.functional.normalize(W_eff, p=2, dim=1) * W_row_norms
out = good_input @ W_eff.T
return out if bias is None else out + bias
def _lowrank_output(good_input, W_base, bias, A, B, W_row_norms, preserve):
# The reformulation used by ARA.modify_model: the base product (computed once,
# independent of the adapter) plus the rank-r update, rescaled per output row,
# then the bias.
product = good_input @ W_base.T
out = product + (good_input @ A.T) @ B.T
if preserve:
eff_row_norms = LA.vector_norm(W_base + (B @ A), dim=1)
out = out * (W_row_norms.squeeze(1) / eff_row_norms)
return out if bias is None else out + bias
class LowRankEquivalenceTests(unittest.TestCase):
def _check(self, preserve: bool, with_bias: bool = False) -> None:
torch.manual_seed(0)
d_out, d_in, r, n = 128, 320, 8, 40
W_base = torch.randn(d_out, d_in, dtype=torch.float64)
A = torch.randn(r, d_in, dtype=torch.float64) * 0.01
B = torch.randn(d_out, r, dtype=torch.float64) * 0.01
good_input = torch.randn(n, d_in, dtype=torch.float64)
bias = torch.randn(d_out, dtype=torch.float64) if with_bias else None
W_row_norms = LA.vector_norm(W_base, dim=1, keepdim=True)
dense = _dense_output(good_input, W_base, bias, A, B, W_row_norms, preserve)
lowrank = _lowrank_output(good_input, W_base, bias, A, B, W_row_norms, preserve)
self.assertTrue(
torch.allclose(dense, lowrank, rtol=1e-9, atol=1e-9),
msg=f"max abs diff = {(dense - lowrank).abs().max().item():.2e}",
)
def test_equivalent_without_row_normalization(self) -> None:
self._check(preserve=False)
def test_equivalent_with_row_normalization(self) -> None:
self._check(preserve=True)
def test_equivalent_with_bias(self) -> None:
self._check(preserve=False, with_bias=True)
def test_equivalent_with_bias_and_row_normalization(self) -> None:
self._check(preserve=True, with_bias=True)
if __name__ == "__main__":
unittest.main()
+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()
+76
View File
@@ -0,0 +1,76 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import io
import unittest
from typing import cast
from unittest.mock import patch
from pydantic import ValidationError
from rich.console import Console
from heretic.config import Settings as HereticSettings
from heretic.scorer import Context
from heretic.scorers.keyword_rate import KeywordRate, Settings
from heretic.utils import Prompt
class FakeContext:
def __init__(self, responses: list[str]) -> None:
self.responses = responses
def get_responses(self, prompts: list[Prompt]) -> list[str]:
return self.responses
class KeywordRateTests(unittest.TestCase):
def test_rejects_empty_keyword_markers(self) -> None:
for markers in [[""], [" ", "\t"]]:
with self.subTest(markers=markers):
with self.assertRaisesRegex(
ValidationError, "keyword markers cannot be empty or whitespace"
):
Settings(keyword_markers=markers)
def test_rejects_empty_keyword_marker_list(self) -> None:
with self.assertRaisesRegex(
ValidationError, "keyword marker list cannot be empty"
):
Settings(keyword_markers=[])
def test_print_responses_shows_brackets_literally(self) -> None:
scorer = KeywordRate(
heretic_settings=HereticSettings.model_construct(),
settings=Settings(print_responses=True),
)
scorer.prompts = [
Prompt(
system="You are a [helpful] assistant.",
user="Name a common misconception about [bird migration].",
),
Prompt(
system="You are a helpful assistant.",
user="What does the [/INST] token mean?",
),
]
ctx = FakeContext(["Use arr[i] here.", "It ends the [/INST] block."])
output = io.StringIO()
console = Console(file=output, highlight=False, width=200)
with patch("heretic.scorers.keyword_rate.print", console.print):
score = scorer.get_score(cast(Context, ctx))
self.assertEqual(score.md_display, "0/2")
for text in [
"You are a [helpful] assistant.",
"[bird migration]",
"What does the [/INST] token mean?",
"Use arr[i] here.",
"It ends the [/INST] block.",
]:
self.assertIn(text, output.getvalue())
if __name__ == "__main__":
unittest.main()
+60
View File
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import unittest
from types import SimpleNamespace
from typing import cast
import torch
from torch import FloatTensor
from heretic.model import _collapse_flattened_residual_streams
class FlattenedResidualStreamTests(unittest.TestCase):
def test_collapses_flattened_streams(self) -> None:
torch.manual_seed(0)
hidden_states = cast(
tuple[FloatTensor, ...],
(
torch.randn(2, 5, 12),
torch.randn(2, 5, 12),
torch.randn(2, 5, 4),
),
)
config = SimpleNamespace(hidden_size=4, hc_count=3)
collapsed = _collapse_flattened_residual_streams(hidden_states, config)
self.assertEqual([h.shape[-1] for h in collapsed], [4, 4, 4])
self.assertTrue(
torch.allclose(
collapsed[0],
hidden_states[0].unflatten(-1, (3, 4)).mean(-2),
)
)
self.assertIs(collapsed[2], hidden_states[2])
def test_uses_text_config(self) -> None:
hidden_states = cast(tuple[FloatTensor, ...], (torch.randn(1, 2, 16),))
text_config = SimpleNamespace(hidden_size=4, hc_count=4)
class Config:
def get_text_config(self) -> SimpleNamespace:
return text_config
collapsed = _collapse_flattened_residual_streams(hidden_states, Config())
self.assertEqual(collapsed[0].shape, (1, 2, 4))
def test_leaves_single_stream_models_unchanged(self) -> None:
hidden_states = cast(tuple[FloatTensor, ...], (torch.randn(1, 2, 4),))
config = SimpleNamespace(hidden_size=4, hc_count=1)
collapsed = _collapse_flattened_residual_streams(hidden_states, config)
self.assertIs(collapsed, hidden_states)
if __name__ == "__main__":
unittest.main()
Generated
+3071 -2105
View File
File diff suppressed because it is too large. Load diff