Compare commits

..

11 Commits

Author SHA1 Message Date
Philipp Emanuel Weidmann 15ad4261be
ci: add yet another alternative model hash 2026-10-01 14:07:30 +05:30
Philipp Emanuel Weidmann c50070f1c8
ci: remove broken "semantic-pull-request" workflow 2026-10-01 14:02:02 +05:30
Philipp Emanuel Weidmann 99be5a6e56
feat: reduce default number of trials 2026-10-01 13:58:47 +05:30
Philipp Emanuel Weidmann 77614a1f76
Merge branch 'master' into modifier-plugins 2026-10-01 12:30:13 +05:30
Philipp Emanuel Weidmann 405e4ffc0d
feat: add tests for ARA 2026-09-30 18:55:54 +05:30
Philipp Emanuel Weidmann ce8b05c77b
feat: re-implement ARA as a modifier plugin
Arbitrary-Rank Ablation (ARA) (Weidmann 2026) was originally introduced by @p-e-w in #211

Co-authored-by: kabachuha <artemkhrapov2001@yandex.ru>
Co-authored-by: joninco <joninco@bullpoint.org>
Co-authored-by: Ashar <coder3101@users.noreply.github.com>
2026-09-28 19:24:08 +05:30
Philipp Emanuel Weidmann ffa66af2d4
feat: support dataset specifications containing multiple individual datasets 2026-09-25 16:43:11 +05:30
Philipp Emanuel Weidmann dc6703788c
Merge branch 'master' into modifier-plugins 2026-09-22 19:39:10 +05:30
Philipp Emanuel Weidmann 033eb4238c
fix: adjust good/bad prompts hack to match tests 2026-09-22 19:26:02 +05:30
Philipp Emanuel Weidmann 598f5f4bd4
feat: re-implement abliteration as a modifier plugin 2026-09-21 18:44:54 +05:30
Philipp Emanuel Weidmann 92ab7f09d5
feat: add modifier base class 2026-09-04 19:16:14 +05:30
80 changed files with 2641 additions and 6313 deletions

View File

@ -1,21 +0,0 @@
<!--
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.

View File

@ -13,7 +13,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] python-version: ["3.10", "3.11", "3.12", "3.13"]
steps: steps:
- name: Check out code - name: Check out code

6
.gitignore vendored
View File

@ -15,14 +15,14 @@ wheels/
# Editors # Editors
/.vscode/ /.vscode/
# ripgrep/fd-specific ignore file
/.ignore
# Configuration file (root only, not ignored in test directories) # Configuration file (root only, not ignored in test directories)
/config.toml /config.toml
# Study checkpoints # Study checkpoints
checkpoints/ checkpoints/
# Residual plots
plots/
# Models generated by tests # Models generated by tests
/tests/*/model/ /tests/*/model/

340
README.md
View File

@ -1,82 +1,89 @@
# THIS REPOSITORY HAS BEEN ARCHIVED. See https://github.com/p-e-w/heretic/issues/601 for more information. <img width="128" align="right" alt="Logo" src="https://github.com/user-attachments/assets/df5f2840-2f92-4991-aa57-252747d7182e" />
<div align="center"> # Heretic: Fully automatic censorship removal for language models<br><br>[![Discord](https://img.shields.io/discord/1447831134212984903?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=for-the-badge)](https://discord.gg/gdXc48gSyT) [![Matrix](https://img.shields.io/badge/Matrix-black?logo=matrix&style=for-the-badge)](https://matrix.to/#/#heretic:matrix.org) [![Follow us on Hugging Face](https://huggingface.co/datasets/huggingface/badges/resolve/main/follow-us-on-hf-md-dark.svg)](https://huggingface.co/heretic-org) [![Codeberg mirror](https://img.shields.io/badge/Codeberg%20mirror-black?logo=codeberg&style=for-the-badge)](https://codeberg.org/p-e-w/heretic)
<img width="128" alt="Heretic logo" src="https://github.com/user-attachments/assets/df5f2840-2f92-4991-aa57-252747d7182e" /> [![#1 Repository of the Day](https://trendshift.io/api/badge/repositories/20538)](https://trendshift.io/repositories/20538)
# Heretic Heretic is a tool that removes censorship (aka "safety alignment") from
transformer-based language models without expensive post-training.
It combines an advanced implementation of directional ablation, also known
as "abliteration" ([Arditi et al. 2024](https://arxiv.org/abs/2406.11717),
Lai 2025 ([1](https://huggingface.co/blog/grimjim/projected-abliteration),
[2](https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration))),
with a TPE-based parameter optimizer powered by [Optuna](https://optuna.org/).
### Training-free language model modification This approach enables Heretic to work **completely automatically.** Heretic
finds high-quality abliteration parameters by co-minimizing the number of
refusals and the KL divergence from the original model. This results in a
decensored model that retains as much of the original model's intelligence
as possible. Using Heretic does not require an understanding of transformer
internals. In fact, anyone who knows how to run a command-line program
can use Heretic to decensor language models.
**Remove censorship**, suppress slop, reduce sycophancy, and more.<br> Heretic supports most dense models, including many multimodal models,
All in an afternoon, on your gaming PC. several different MoE architectures, and even some hybrid models like Qwen3.5.
Pure state-space models and certain other research architectures are not yet
supported out of the box.
[![Discord](https://img.shields.io/discord/1447831134212984903?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=for-the-badge)](https://discord.gg/gdXc48gSyT)&nbsp;&nbsp;&nbsp;&nbsp; <img width="650" height="715" alt="Screenshot" src="https://github.com/user-attachments/assets/d71a5efa-d6be-4705-a817-63332afb2d15" />
[![Matrix](https://img.shields.io/badge/Matrix-black?logo=matrix&style=for-the-badge)](https://matrix.to/#/#heretic:matrix.org)&nbsp;&nbsp;&nbsp;
[![Follow us on Hugging Face](https://huggingface.co/datasets/huggingface/badges/resolve/main/follow-us-on-hf-md-dark.svg)](https://huggingface.co/heretic-org)&nbsp;&nbsp;&nbsp;
[![Codeberg mirror](https://img.shields.io/badge/Codeberg%20mirror-black?logo=codeberg&style=for-the-badge)](https://codeberg.org/p-e-w/heretic)
</div>
-----
&nbsp; &nbsp;
[![#1 Repository of the Day](https://trendshift.io/api/badge/repositories/20538)](https://trendshift.io/repositories/20538)&nbsp;&nbsp;&nbsp;&nbsp; Running unsupervised with the default configuration, Heretic can produce
[![Model and download statistics](https://github.com/user-attachments/assets/c9b5a660-7ef9-43c7-991c-fd9d63ea8bd8)](https://heretic.sdad.pro/) decensored models that rival the quality of abliterations created manually
by human experts:
| Model | Refusals for "harmful" prompts | KL divergence from original model for "harmless" prompts |
| :--- | ---: | ---: |
| [google/gemma-3-12b-it](https://huggingface.co/google/gemma-3-12b-it) (original) | 97/100 | 0 *(by definition)* |
| [mlabonne/gemma-3-12b-it-abliterated-v2](https://huggingface.co/mlabonne/gemma-3-12b-it-abliterated-v2) | 3/100 | 1.04 |
| [huihui-ai/gemma-3-12b-it-abliterated](https://huggingface.co/huihui-ai/gemma-3-12b-it-abliterated) | 3/100 | 0.45 |
| **[p-e-w/gemma-3-12b-it-heretic](https://huggingface.co/p-e-w/gemma-3-12b-it-heretic) (ours)** | **3/100** | **0.16** |
## Modify any LLM that you can run on your hardware[^1] The Heretic version, generated without any human effort, achieves the same
level of refusal suppression as other abliterations, but at a much lower
KL divergence, indicating less damage to the original model's capabilities.
*(You can reproduce those numbers using Heretic's built-in evaluation functionality,
e.g. `heretic --model google/gemma-3-12b-it --evaluate-model p-e-w/gemma-3-12b-it-heretic`.
Note that the exact values might be platform- and hardware-dependent.
The table above was compiled using PyTorch 2.8 on an RTX 5090.)*
[^1]: Heretic supports on-the-fly 4-bit model quantization with bitsandbytes, Of course, mathematical metrics and automated benchmarks never tell the whole
which can reduce the amount of VRAM required to process a model to the same amount story, and are no substitute for human evaluation. Models generated with
that is used to run a typical quantized version of it, at a slight accuracy cost. Heretic have been well-received by users (links and emphasis added):
Set the `quantization` option to `bnb_4bit` to enable this.
Heretic is a unique tool that lets you do what only corporations with access > "I was skeptical before, but I just downloaded
to massive computing power usually do: *Modify,* rather than merely run, > [**GPT-OSS 20B Heretic**](https://huggingface.co/p-e-w/gpt-oss-20b-heretic)
language models. It does not perform expensive training; rather, it uses > model and holy shit. It gives properly formatted long responses to sensitive topics,
a collection of mathematical techniques to steer behavior based on contrasting > using the exact uncensored words that you would expect from an uncensored model,
example prompts and matching scorers. > produces markdown format tables with details and whatnot. Looks like this is
> the best abliterated version of this model so far..."
> [*(Link to comment)*](https://old.reddit.com/r/LocalLLaMA/comments/1oymku1/heretic_fully_automatic_censorship_removal_for/np6tba6/)
Heretic can, depending on the configuration: > "[**Heretic GPT 20b**](https://huggingface.co/p-e-w/gpt-oss-20b-heretic)
> seems to be the best uncensored model I have tried yet. It doesn't destroy a
> the model's intelligence and it is answering prompts normally would be
> rejected by the base model."
> [*(Link to comment)*](https://old.reddit.com/r/LocalLLaMA/comments/1oymku1/heretic_fully_automatic_censorship_removal_for/npe9jng/)
* **Suppress refusals/remove censorship** (this is the [default action](/config.default.toml)) > "[[**Qwen3-4B-Instruct-2507-heretic**](https://huggingface.co/p-e-w/Qwen3-4B-Instruct-2507-heretic)]
* Reduce slop ([`config.noslop.toml`](/config.noslop.toml)) > Has been the best unquantized abliterated model that I have been able to run on 16gb vram."
* Reduce humor ([`config.nohumor.toml`](/config.nohumor.toml)) > [*(Link to comment)*](https://old.reddit.com/r/LocalLLaMA/comments/1phjxca/im_calling_these_people_out_right_now/nt06tji/)
* Reduce sycophancy ([`config.nosyco.toml`](/config.nosyco.toml))
* Alter emotional alignment ([`config.emotions.toml`](/config.emotions.toml))
* Shorten response length ([`config.terse.toml`](/config.terse.toml))
and many, many other things. Heretic models have also been independently benchmarked using standard metrics
like MMLU and GSM8K, and have been found to compare favorably with models
### :bangbang: Using Heretic does NOT require understanding how language models work internally :bangbang: produced by competing abliteration tools:
[1](https://old.reddit.com/r/LocalLLaMA/comments/1sojjoc/abliterlitics_benchmark_and_tensor_analysis/),
In fact, you can go from zero to removing censorship from your first model [2](https://old.reddit.com/r/LocalLLaMA/comments/1sy18lx/abliterlitics_benchmarks_and_tensor_comparison/).
[in a matter of seconds](#usage). Heretic supports most dense models, including
many multimodal models, several different MoE architectures, and many modern
hybrid models.
The community has created and published The community has created and published
[thousands](https://huggingface.co/models?other=heretic) [well over 5000](https://huggingface.co/models?other=heretic)
of models with Heretic. models with Heretic.
Heretic models have been independently benchmarked using standard metrics
like MMLU and GSM8K, and have been found to compare favorably against models
produced with competing abliteration tools.[^2][^3]
[^2]: [Qwen2.5-7B: Three-Way Abliteration Comparison](https://huggingface.co/DreamFast/Qwen-2.5-7b-abliterlitics): *"Heretic is the most surgical and most effective."*
[^3]: [Gemma 4 E4B: 23 Abliteration Variants Compared](https://huggingface.co/DreamFast/Gemma4-e4b-abliterlitics): *"Best overall: heretic."*
&nbsp;
<img width="600" alt="Heretic screenshot" src="https://github.com/user-attachments/assets/a030f595-67ef-49a6-9d9a-779fdf752b58" />
&nbsp;
## Usage ## Usage
Prepare a Python 3.10+ environment with PyTorch 2.6+ installed as appropriate Prepare a Python 3.10+ environment with PyTorch 2.2+ installed as appropriate
for your hardware. Then run: for your hardware. Then run:
```sh ```sh
@ -84,179 +91,87 @@ pip install -U heretic-llm
heretic Qwen/Qwen3-4B-Instruct-2507 heretic Qwen/Qwen3-4B-Instruct-2507
``` ```
Replace `Qwen/Qwen3-4B-Instruct-2507` with whatever model you want to process. Replace `Qwen/Qwen3-4B-Instruct-2507` with whatever model you want to decensor.
**By default, Heretic performs censorship removal (refusal suppression).**
If you want to do something else, choose one of the configuration files linked
above, or write your own. See [`config.default.toml`](/config.default.toml)
for available configuration options. Heretic loads the configuration from
`config.toml` in the working directory by default, or from the file path in the
`HERETIC_CONFIG_FILE` environment variable.
> [!IMPORTANT] > [!IMPORTANT]
> >
> Configuration files made for Heretic 1.x are **not** compatible with Heretic 2.x! > While PyTorch 2.2 is the minimum version of PyTorch needed for Heretic to work,
> See the [migration guide](/docs/migration_v1_to_v2.md) for what you need to change > some models and configurations might require features only found in
> in order to make your old configurations work. > later versions. For example, loading MXFP4-quantized models like gpt-oss
> uses `torch.accelerator`, which was added in PyTorch 2.6.
> [!TIP]
>
> Heretic uses [uv](https://docs.astral.sh/uv/) for dependency management,
> and the repository includes a `uv.lock` file pinning every package version.
> If you already use uv (and you probably should!), you can just clone the repo
> and run Heretic with `uv run heretic`, which ensures that your dependencies
> match those used by the developers, improving reliability and security.
The process is fully automatic and does not require configuration; however,
Heretic has a variety of configuration parameters that can be changed for
greater control. Run `heretic --help` to see available command-line options,
or look at [`config.default.toml`](config.default.toml) if you prefer to use
a configuration file.
At the start of a program run, Heretic benchmarks the system to determine At the start of a program run, Heretic benchmarks the system to determine
the optimal batch size to make the most of the available hardware. the optimal batch size to make the most of the available hardware.
On an RTX 3090, with the default configuration, processing On an RTX 3090, with the default configuration, decensoring
[Qwen3-4B-Instruct-2507](https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507) [Qwen3-4B-Instruct-2507](https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507)
takes about 30-40 minutes. takes about 20-30 minutes. Note that Heretic supports model quantization with
bitsandbytes, which can drastically reduce the amount of VRAM required to process
models. Set the `quantization` option to `bnb_4bit` to enable quantization.
After Heretic has finished processing a model, you are given the choice to After Heretic has finished decensoring a model, you are given the option to
save the model, upload it to Hugging Face, chat with it to test how well it works, save the model, upload it to Hugging Face, chat with it to test how well it works,
run standard benchmarks on it, or any combination of those actions. run standard benchmarks on it, or any combination of those actions.
## Controlling what Heretic does using scorer plugins
Heretic steers model behavior by optimizing one or multiple scores. Scores are
computed by scorer plugins. You can easily write your own scorers to get full
control over what Heretic does to models.
The `Scorer` interface (abstract base class) your scorer needs to inherit from
is defined in [`scorer.py`](/src/heretic/scorer.py). The only required method
is `get_score`, but there is more machinery (such as settings management)
available when you need it.
By default, Heretic scores models by refusal rate (implemented in
[`keyword_rate.py`](/src/heretic/scorers/keyword_rate.py)) and KL divergence
(implemented in [`kl_divergence.py`](/src/heretic/scorers/kl_divergence.py)).
Additional scorers are available in the [`scorers` directory](/src/heretic/scorers/).
These scorers can serve as examples for your own implementations, and can easily
be adapted to your needs.
Scorers are configured through the [main configuration file](/config.default.toml).
Which scorer plugins are active is determined by the `scorers` setting, which
also controls whether a scorer's score should be minimized or maximized during
optimization. Any number of scorers can be used simultaneously, and their scores
will be co-optimized. Multiple instances of the same scorer can be configured
with different settings. See the configuration file for the full documentation
of this mechanism.
The path to a scorer plugin can be specified either as a fully qualified import
path (`fully.qualified.module.MyScorerClass`) or as a file path followed by
a class name (`path/to/plugin.py:MyScorerClass`). You do **not** have to modify
the Heretic package code in order to use your own plugins.
Heretic also has modifier plugins, which are described in
[the next section](#how-heretic-works).
## How Heretic works ## How Heretic works
Heretic combines a pluggable modifier (interface in Heretic implements a parametrized variant of directional ablation. For each
[`modifier.py`](/src/heretic/modifier.py)) with a TPE-based hyperparameter optimizer supported transformer component (currently, attention out-projection and
powered by [Optuna](https://optuna.org/). The optimizer finds a set of parameters that, MLP down-projection), it identifies the associated matrices in each transformer
when passed to the modifier, minimize or maximize a set of configurable scores on the resulting model ([see above](#controlling-what-heretic-does-using-scorer-plugins)). layer, and orthogonalizes them with respect to the relevant "residual direction",
inhibiting the expression of that direction in the result of multiplications
with that matrix.
Heretic ships with two modifiers: Residual directions are computed for each layer as a difference-of-means between
the first-token residuals for "harmful" and "harmless" example prompts.
* **Arbitrary-Rank Ablation (ARA)**[^4]: This is the default modifier, and was The ablation process is controlled by several optimizable parameters:
specifically developed for use in Heretic. You can find an overview of how ARA
works in [the original pull request](https://github.com/p-e-w/heretic/pull/211),
and see the precise implementation in [`ara.py`](/src/heretic/modifiers/ara.py).
* **Directional ablation aka "abliteration"**[^5]: The classic method for refusal * `direction_index`: Either the index of a residual direction, or the special
suppression. Heretic's implementation uses a flexible ablation weight kernel over value `per layer`, indicating that each layer should be ablated using the
the layers, and supports both projected abliteration[^6] and norm preservation (MPOA)[^7]. residual direction associated with that layer.
The complete code is in [`abliteration.py`](/src/heretic/modifiers/abliteration.py). * `max_weight`, `max_weight_position`, `min_weight`, and `min_weight_distance`:
For each component, these parameters describe the shape and position of the
ablation weight kernel over the layers. The following diagram illustrates this:
[^4]: *Weidmann 2026.* A preprint explaining the technique will be available soon. <img width="800" height="500" alt="Explanation" src="https://github.com/user-attachments/assets/82e4b84e-5a82-4faf-b918-ac642f9e4892" />
[^5]: *[Arditi et al. 2024](https://arxiv.org/abs/2406.11717)*
[^6]: *[Lai 2025 (1)](https://huggingface.co/blog/grimjim/projected-abliteration)*
[^7]: *[Lai 2025 (2)](https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration)*
You can use the `modifiers` setting to switch between modifier implementations. &nbsp;
Despite the name of the setting using a plural form, Heretic currently allows
only a single modifier for a given processing run. This may change in the future.
Heretic's main innovations over existing abliteration systems are:
## Reproducibility and the Heretic Grimoire * The shape of the ablation weight kernel is highly flexible, which, combined with
automatic parameter optimization, can improve the compliance/quality tradeoff.
Heretic has the ability to create *reproducible models* whose repositories contain Non-constant ablation weights were previously explored by Maxime Labonne in
all information required to produce a byte-for-byte identical model on demand, [gemma-3-12b-it-abliterated-v2](https://huggingface.co/mlabonne/gemma-3-12b-it-abliterated-v2).
provided that the environment is perfectly identical to the original one. PyTorch * The residual direction index is a float rather than an integer. For non-integral
doesn't guarantee that operations return identical outputs unless hardware, drivers, values, the two nearest residual direction vectors are linearly interpolated.
operating system, and the entire software stack including all package versions This unlocks a vast space of additional directions beyond the ones identified
are exactly the same. by the difference-of-means computation, and often enables the optimization
process to find a better direction than that belonging to any individual layer.
Heretic manages all that complexity for you. When uploading a processed model to * Ablation parameters are chosen separately for each component. I have found that
Hugging Face, Heretic offers to include reproducibility information. This is entirely MLP interventions tend to be more damaging to the model than attention interventions,
optional, but if you choose to do so, the uploaded repository will contain a so using different ablation weights can squeeze out some extra performance.
`reproduce` folder with detailed instructions for recreating the model
([example](https://huggingface.co/heretic-org/LFM2.5-VL-3B-heretic/tree/main/reproduce)).
This folder contains both human-readable instructions and a machine-readable manifest
file named `reproduce.json`, which includes all the information Heretic needs to
**automatically** reproduce the model.
Automatic reproduction can be performed with
```sh
heretic --reproduce path/to/reproduce.json
```
Heretic will guide you through the process, checking your environment against the one
that was used to create the model, and pointing out potentially problematic mismatches.
The multi-hour computations that were required to make the original model do **not**
have to be re-done, and the entire process typically takes a few minutes. After you
have exported the resulting model, Heretic will verify the hashes of the weight files
against those stored in the reproduction manifest (they may or may not be identical,
depending on how closely your system resembles the original one).
Many people have uploaded models with reproducibility information to Hugging Face.
Since a reproduction manifest is only around 9 kilobytes in size, these manifests
form a portable library of models that can be reproduced at will.
### That library is called the Heretic Grimoire. You can view it [here](https://huggingface.co/spaces/heretic-org/Heretic-Grimoire).
But you don't have to rely on an externally hosted web application to access the
library of manifests: The Grimoire is fundamentally designed as a *distributed* system,
and you can fetch your own local copies of publicly available manifests from
Hugging Face whenever you want by running
```sh
heretic --collect-reproducibles path/to/target/folder/
```
You now have a local backup of all reproducible Heretic models, properly catalogued.
To update this collection, simply run the command again. It functions as an
append-only backup, never deleting files even if the corresponding model no longer
exists on Hugging Face.
## Heretic is made by humans!
Unlike lots of AI-related software today (and indeed lots of software in general),
Heretic is **not** "vibe-coded".
All of [my](https://github.com/p-e-w) commits to this project until November 2026
were written 100% by hand, the way I have been doing programming for decades.
I have been using LLM assistance *very* sparingly since. While many Heretic contributors
use coding agents, I carefully review every single line of code that I merge.
There's no "LGTM" here!
Don't believe me? Check out [this pull request](https://github.com/p-e-w/heretic/pull/53),
which accumulated **almost 350 human-written comments** over more than 7 months
as we discussed the implementation.
And [here is another PR](https://github.com/p-e-w/heretic/pull/191) with
**more than 200 comments.**
I am the opposite of a luddite and I have used agents liberally for other projects,
but I am proud of the code I write and so far can't quite bring myself to let a machine
write it for me in a project I care so much about. As a result, Heretic has a lean,
relatively simple codebase that in my opinion, and in that of some others,
is a pleasure to work on.
If you like that, join us! Hop on the Discord and tell us about your ideas for
improvements, or directly file an issue or open a PR.
## Prior art ## Prior art
I'm aware of the following implementations of abliteration techniques I'm aware of the following publicly available implementations of abliteration
that were publicly available when Heretic was first released (November 2025): techniques:
* [AutoAbliteration](https://huggingface.co/posts/mlabonne/714992455492422) * [AutoAbliteration](https://huggingface.co/posts/mlabonne/714992455492422)
* [abliterator.py](https://github.com/FailSpy/abliterator) * [abliterator.py](https://github.com/FailSpy/abliterator)
@ -273,13 +188,11 @@ any of those projects.
The development of Heretic was informed by: The development of Heretic was informed by:
* [The original abliteration paper *(Arditi et al. 2024)*](https://arxiv.org/abs/2406.11717) * [The original abliteration paper (Arditi et al. 2024)](https://arxiv.org/abs/2406.11717)
* [Maxime Labonne's article on abliteration](https://huggingface.co/blog/mlabonne/abliteration), * [Maxime Labonne's article on abliteration](https://huggingface.co/blog/mlabonne/abliteration),
as well as some details from the model cards of his own abliterated models, such as as well as some details from the model cards of his own abliterated models (see above)
the use of non-constant ablation weights
* Jim Lai's articles describing ["projected abliteration"](https://huggingface.co/blog/grimjim/projected-abliteration) * Jim Lai's articles describing ["projected abliteration"](https://huggingface.co/blog/grimjim/projected-abliteration)
and ["norm-preserving biprojected abliteration"](https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration) and ["norm-preserving biprojected abliteration"](https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration)
* Thousands of interactions with members of the community
## Citation ## Citation
@ -289,7 +202,7 @@ If you use Heretic for your research, please cite it using the following BibTeX
```bibtex ```bibtex
@misc{heretic, @misc{heretic,
author = {Weidmann, Philipp Emanuel}, author = {Weidmann, Philipp Emanuel},
title = {Heretic: Training-free language model modification}, title = {Heretic: Fully automatic censorship removal for language models},
year = {2025}, year = {2025},
publisher = {GitHub}, publisher = {GitHub},
journal = {GitHub repository}, journal = {GitHub repository},
@ -317,10 +230,3 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
**By contributing to this project, you agree to release your **By contributing to this project, you agree to release your
contributions under the same license.** contributions under the same license.**
&nbsp;
&nbsp;
&nbsp;

View File

@ -1,14 +0,0 @@
# Rename this file to config.toml, place it in the working directory
# that you run Heretic from, and edit the configuration to your liking.
#
# BERTClassifier scorer instead of the default KeywordRate.
# To compare with keyword-based scoring alongside,
# Use "none" to compute its score for reference only without influencing optimization.
# Or use "minimize" to use its scores for optimization as well.
#
# { plugin = "heretic.scorers.keyword_rate.KeywordRate", optimization = "none" }
scorers = [
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" },
{ plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" },
]

View File

@ -42,29 +42,29 @@ max_batch_size = 128
# Maximum number of tokens to generate for each response. # Maximum number of tokens to generate for each response.
max_response_length = 100 max_response_length = 100
# List of pairs of the form [cot_initializer, cot_finalizer] used to skip # List of pairs of the form [cot_initializer, closed_cot_block] used to skip
# the Chain-of-Thought block in responses, so that evaluation happens # the Chain-of-Thought block in responses, so that evaluation happens
# at the start of the actual response. # at the start of the actual response.
chain_of_thought_blocks = [ chain_of_thought_skips = [
# Most thinking models. # Most thinking models.
[ [
"<think>", "<think>",
"</think>", "<think></think>",
], ],
# gpt-oss. # gpt-oss.
[ [
"<|channel|>analysis<|message|>", "<|channel|>analysis<|message|>",
"<|end|><|start|>assistant<|channel|>final<|message|>", "<|channel|>analysis<|message|><|end|><|start|>assistant<|channel|>final<|message|>",
], ],
# Unknown, suggested by user. # Unknown, suggested by user.
[ [
"<thought>", "<thought>",
"</thought>", "<thought></thought>",
], ],
# Unknown, suggested by user. # Unknown, suggested by user.
[ [
"[THINK]", "[THINK]",
"[/THINK]", "[THINK][/THINK]",
], ],
] ]
@ -87,7 +87,7 @@ modifiers = [
{ plugin = "heretic.modifiers.ara.ARA" }, { plugin = "heretic.modifiers.ara.ARA" },
] ]
# Number of trials to run during optimization. # Number of abliteration trials to run during optimization.
n_trials = 100 n_trials = 100
# Number of trials that use random sampling for the purpose of exploration. # Number of trials that use random sampling for the purpose of exploration.
@ -96,26 +96,12 @@ n_startup_trials = 30
# Directory to save and load study progress to/from. # Directory to save and load study progress to/from.
study_checkpoint_dir = "checkpoints" 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. # Maximum size for individual safetensors files generated when exporting a model.
max_shard_size = "5GB" 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 to use when prompting the model.
system_prompt = "You are a helpful assistant." system_prompt = "You are a helpful assistant."
# Whether to offer the option to open an in-context Python shell in the trial selection menu.
# WARNING: Enabling this feature gives full system access to the user of the Heretic session.
enable_shell = false
# Dataset of prompts to use for automatically determining the optimal batch size. # Dataset of prompts to use for automatically determining the optimal batch size.
[batch_size_test_prompts] [batch_size_test_prompts]
dataset = "mlabonne/harmless_alpaca" dataset = "mlabonne/harmless_alpaca"
@ -167,7 +153,7 @@ column = "text"
# Name that describes what the configured keyword rate measures. # Name that describes what the configured keyword rate measures.
score_name = "Refusals" score_name = "Refusals"
# Whether to print prompt/response pairs. # Whether to print prompt/response pairs when counting keyword matches.
print_responses = false print_responses = false
# Strings whose presence in a response (case insensitive) identifies the response as a keyword match. # Strings whose presence in a response (case insensitive) identifies the response as a keyword match.
@ -221,71 +207,6 @@ split = "test[:100]"
column = "text" column = "text"
# Generic text-classification scorer: classifies each response with a
# text-classification model and counts the responses whose
# predicted label is one of the `match_labels`, as an alternative to the
# `keyword_markers` of the KeywordRate scorer.
#
# The default settings detect refusals using a ModernBERT model fine-tuned on refusal
# classification. Any text-classification model and label set can be used by
# changing the plugin settings.
#
# Add or replace an entry in the `scorers` array above:
# { plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" }
#
[scorer.BERTClassifier]
# Name that describes what the configured match rate measures.
score_name = "Refusals (Classifier)"
# Hugging Face model ID, or path to a text-classification model on disk.
model = "VINAY-UMRETHE/Refusal-Classifier-V2"
# Hugging Face commit hash of the classifier model.
# Set this to pin a specific revision; unset means the latest revision
# is auto-pinned and recorded when the classifier is loaded.
# When reproducing, the recorded revision is restored and used.
# model_commit = "<commit-hash>"
# List of PyTorch dtypes to try when loading model tensors.
# If loading with a dtype fails, the next dtype in the list will be tried.
dtypes = [
"auto",
"float16",
"bfloat16",
"float32",
]
# Device map to pass to Accelerate when loading the model.
device_map = "auto"
# Labels predicted by the classifier that identify a response as a match.
# Defaults to the refusal labels of the default model, which should
# be counted as refusals.
# Valid labels: compliant, full_refusal, partial_refusal, capability_limitation, clarification.
match_labels = ["full_refusal", "partial_refusal"]
# Number of prompt/response pairs to classify in parallel.
batch_size = 16
# Maximum number of tokens per classifier input (longer inputs are truncated).
max_length = 8192
# Whether to pass inputs as prompt/response text pairs.
# Requires a model trained on pairs (e.g. the default refusal classifier).
# Set to False when using a single-sequence text-classification model
# to evaluate the response string only (e.g. sentiment analysis).
use_text_pairs = true
# Whether to print prompt/response pairs and their predicted labels.
print_responses = false
# Dataset of prompts to evaluate the match rate on.
[scorer.BERTClassifier.prompts]
dataset = "mlabonne/harmful_behaviors"
split = "test[:100]"
column = "text"
[scorer.BenchmarkScore] [scorer.BenchmarkScore]
# Name that describes what the configured benchmark score measures. # Name that describes what the configured benchmark score measures.
score_name = "PIQA acc_norm" score_name = "PIQA acc_norm"
@ -296,30 +217,6 @@ task = "piqa"
# Task metric to use as the benchmark score. # Task metric to use as the benchmark score.
metric = "acc_norm,none" metric = "acc_norm,none"
# Number of input sequences to process in parallel (0 = auto).
batch_size = 0 # auto
[scorer.ResponseLength]
# Whether to strip leading and trailing whitespace from responses before measuring their length.
strip_responses = true
# Length in characters below which a response is classified as a 'short response'.
short_response_threshold = 2 # Chosen because "No" is the shortest common valid response.
# Length value artificially assigned to 'short responses' for the purpose of scoring.
# This can be used to penalize very short (and thus likely invalid) responses.
short_response_score_length = 500
# Whether to print prompt/response pairs.
print_responses = false
# Dataset of prompts to evaluate the response length on.
[scorer.ResponseLength.prompts]
dataset = "mlabonne/harmless_alpaca"
split = "test[:100]"
column = "text"
[modifier.ARA] [modifier.ARA]
# Whether to renormalize the rows of the modified matrices to preserve # Whether to renormalize the rows of the modified matrices to preserve

View File

@ -1,120 +0,0 @@
# Rename this file to config.toml, place it in the working directory
# that you run Heretic from, and edit the configuration to your liking.
#
# BERTClassifier scorer for personality/emotion steering.
#
# This uses a DistilRoBERTa model fine-tuned on emotion classification
# and allows minimizing or maximizing specific emotions in the model's responses.
#
# Example use: configure two scorer instances, one to minimize negative emotions
# (e.g. anger, disgust, fear, sadness) and one to maximize positive emotions
# (e.g joy, surprise) or vice versa.
#
# This can be done in one of the two ways:
#
# 1. Multi‑objective steering:
# Here, we use two instances: `negative_emotions` and `positive_emotions` with
# `optimization = "minimize"` and `optimization = "maximize"` respectively.
#
# Minimizing the first score pushes the model *away* from those negative emotions.
# Maximizing the second score pushes the model *towards* those emotions.
#
# 2. Single‑objective steering:
# With two instances, heretic builds a Pareto front that **balances** both objectives above.
# Due to which, the model learns to be less angry *and* more joyful **simultaneously**.
#
# With only one instance, we have only one objective which can be either minimized or maximized.
# Due to which, the model will reduce anger, but it *may* drift towards **anything** that lowers
# the other most natural instincts (e.g. neutral, overly polite, or wierdly happy).
#
# With the first method, you can expect to control both objectives effectively,
# which is the recommended method and is the default.
# With the second method, you can only *hope* and *assume* the most expected common/natural
# behavior, depending upon what you tried to "minimize" or "maximize".
scorers = [
{ plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" },
# Scorer to minimize negative emotions.
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize", instance_name = "negative_emotions" },
# Scorer to maximize positive emotions.
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "maximize", instance_name = "positive_emotions" },
]
modified_model_type = "happiness-increased"
upload_tags = [
"personality-steering",
"emotion-steering",
]
# Dataset of prompts used for steering, which tends to produce
# the target emotion you want to influence.
# For example:
# - For minimizing anger: prompts about creative writing which involves those emotions.
# - For maximizing joy: prompts about celebrations, happy scenarios, good news from user, etc.
[modifier.ARA.good_prompts]
dataset = "VINAY-UMRETHE/Positive-Prompts"
split = "train[:200]"
column = "prompt"
[modifier.ARA.bad_prompts]
dataset = "VINAY-UMRETHE/Negative-Prompts"
split = "train[:200]"
column = "prompt"
[scorer.BERTClassifier_negative_emotions]
# Name that describes what the configured match rate measures.
score_name = "Minimize"
# Hugging Face model ID, or path to a text-classification model on disk.
model = "j-hartmann/emotion-english-distilroberta-base"
# Hugging Face commit hash of the classifier model.
# Set this to pin a specific revision; unset means the latest revision
# is auto-pinned and recorded when the classifier is loaded.
# When reproducing, the recorded revision is restored and used.
# model_commit = "<commit-hash>"
# Labels predicted by the classifier that identify a response as a match.
# We want to minimize these emotions.
match_labels = ["anger", "disgust", "fear", "sadness"]
# Number of prompt/response pairs to classify in parallel.
batch_size = 16
# Maximum number of tokens per classifier input (longer inputs are truncated).
max_length = 512
# Whether to pass inputs as prompt/response text pairs.
# Requires a model trained on pairs (e.g. the default refusal classifier).
# Set to False when using a single-sequence text-classification model
# to evaluate the response string only (e.g. sentiment analysis).
use_text_pairs = false
# Whether to print prompt/response pairs and their predicted labels.
print_responses = true
# Dataset of prompts to evaluate the match rate on.
# Use a dataset that tends to produce the target emotions (anger, disgust, fear, sadness).
[scorer.BERTClassifier_negative_emotions.prompts]
dataset = "VINAY-UMRETHE/Negative-Prompts"
split = "train[:100]"
column = "prompt"
[scorer.BERTClassifier_positive_emotions]
score_name = "Maximize"
model = "j-hartmann/emotion-english-distilroberta-base"
# We want to maximize these emotions.
match_labels = ["joy", "surprise"]
batch_size = 16
max_length = 512
print_responses = true
[scorer.BERTClassifier_positive_emotions.prompts]
dataset = "VINAY-UMRETHE/Positive-Prompts"
split = "train[:100]"
column = "prompt"

View File

@ -3,12 +3,6 @@
max_response_length = 300 max_response_length = 300
modified_model_type = "humor-reduced"
upload_tags = [
"no-humor",
]
[scorer.KeywordRate] [scorer.KeywordRate]
score_name = "Responses with humor" score_name = "Responses with humor"

View File

@ -3,12 +3,6 @@
max_response_length = 300 max_response_length = 300
modified_model_type = "slop-reduced"
upload_tags = [
"no-slop",
]
system_prompt = "You are a professional writer." system_prompt = "You are a professional writer."
[scorer.KeywordRate] [scorer.KeywordRate]

View File

@ -1,146 +0,0 @@
# Rename this file to config.toml, place it in the working directory
# that you run Heretic from, and edit the configuration to your liking.
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."""

View File

@ -1,51 +0,0 @@
# Rename this file to config.toml, place it in the working directory
# that you run Heretic from, and edit the configuration to your liking.
scorers = [
{ plugin = "heretic.scorers.response_length.ResponseLength", optimization = "minimize" },
# We cannot use KL divergence because there is no set of prompts for which
# we expect the modified model to retain its behavior.
{ plugin = "heretic.scorers.benchmark_score.BenchmarkScore", optimization = "maximize" },
]
modified_model_type = "tersified"
upload_tags = [
"terse",
]
[modifier.ARA.good_prompts]
dataset = "mlabonne/harmless_alpaca"
split = "train[:400]"
column = "text"
system_prompt = """You are a hyper-terse assistant. You respond with the minimum amount of text that satisfies the prompt.
You don't use introductions, you don't repeat or rephrase the task, you don't provide additional information,
and you don't use full sentences when a single word or item suffices.
Here are some examples showing how you should, and shouldn't, respond:
User: What is 1+1?
Good response: 2
Bad response: 1 + 1 = 2! This is a simple addition operation.
User: What is the largest land animal?
Good response: African elephant
Bad response: The largest land animal is the African bush elephant (*Loxodonta africana*),
with fully grown bulls reaching an average shoulder height of 3.3 meters, and a body mass of 6 tons.
User: Describe a grocery shopping trip.
Good response: Go to store, buy groceries, return
Bad response: First, make sure you have a shopping list. Then pack your shopping bags
into your car and drive to the grocery store. Make sure you park as closely as possible
to the entrance of the store. Once inside, pick up a cart and check the aisles for the items you need.
Collect all items in your cart and proceed to the register. Pay for the items and take the cart
to your car. Move the items from the cart into the trunk of your car. Then return the cart to the store,
return to your car, and drive home."""
[modifier.ARA.bad_prompts]
dataset = "mlabonne/harmless_alpaca"
split = "train[:400]"
column = "text"
system_prompt = """You are a loquacious personal assistant. You give elaborate, highly detailed responses to every prompt.
Your responses contain proper introductions and start with a summary of the task or question.
You supply as much additional information as possible and write everything out in full detail."""

View File

@ -1,67 +0,0 @@
# Migrating from Heretic 1.x to Heretic 2.x
Heretic 2.x is not backwards compatible with Heretic 1.x configurations.
If you have existing configuration files written to work with a Heretic 1.x release,
you need to make the following changes before using them with a Heretic 2.x release.
Only settings that are actually in your configuration file must be updated;
defaults are automatically set to the current values. Of course, you can also simply
start with [an up-to-date default configuration](/config.default.toml), and modify
it to match your requirements.
## Remove settings for research features
Research features have been removed in Heretic 2.0. The following settings
are no longer recognized:
* `print_residual_geometry`
* `plot_residuals`
* `residual_plot_path`
* `residual_plot_title`
* `residual_plot_style`
* `residual_plot_label` and `residual_plot_color` in prompt sections
## Remove `kl_divergence_scale` and `kl_divergence_target`
KL divergence balancing has been removed and these settings
are no longer recognized.
## Rename `chain_of_thought_skips` to `chain_of_thought_blocks` and update its structure
The new setting `chain_of_thought_blocks` contains pairs of the form
`[cot_initializer, cot_finalizer]` instead of `[cot_initializer, closed_cot_block]`.
## Move abliteration settings to the `[modifier.Abliteration]` section
This includes the following settings:
* `orthogonalize_direction`
* `row_normalization`
* `full_normalization_lora_rank`
* `winsorization_quantile`
* `[good_prompts]` (renamed to `[modifier.Abliteration.good_prompts]`)
* `[bad_prompts]` (renamed to `[modifier.Abliteration.bad_prompts]`)
> [!IMPORTANT]
>
> Heretic 2.x defaults to using ARA for modifying models, not abliteration.
> To continue using abliteration, edit the `modifiers` setting accordingly.
> To configure ARA, edit the `[modifier.ARA]` section.
## Move refusal evaluation settings to the `[scorer.KeywordRate]` section
This includes the following settings:
* `print_responses`
* `refusal_markers` (renamed to `keyword_markers`)
* `[bad_evaluation_prompts]` (renamed to `[scorer.KeywordRate.prompts]`)
## Rename `[good_evaluation_prompts]` to `[scorer.KLDivergence.prompts]`
KL divergence is now computed by a scorer plugin.

View File

@ -1,7 +1,7 @@
[project] [project]
name = "heretic-llm" name = "heretic-llm"
version = "2.2.0.dev0" version = "2.0.0.dev0"
description = "Training-free language model modification" description = "Fully automatic censorship removal for language models"
readme = "README.md" readme = "README.md"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = [ authors = [
@ -10,47 +10,44 @@ authors = [
requires-python = ">=3.10" requires-python = ">=3.10"
keywords = ["llm", "transformer", "abliteration"] keywords = ["llm", "transformer", "abliteration"]
classifiers = [ classifiers = [
"Development Status :: 5 - Production/Stable", "Development Status :: 4 - Beta",
"Environment :: Console", "Environment :: Console",
"Environment :: GPU", "Environment :: GPU",
"Intended Audience :: Science/Research", "Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Scientific/Engineering :: Artificial Intelligence",
"Programming Language :: Python :: 3", "Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Programming Language :: Python :: 3.15",
] ]
dependencies = [ dependencies = [
"accelerate~=1.15", "accelerate~=1.13",
"bitsandbytes~=0.50", "bitsandbytes~=0.49",
"datasets~=5.0", "datasets~=4.7",
"huggingface-hub~=1.33", "huggingface-hub~=1.7",
"immutabledict~=4.3", "immutabledict~=4.3",
"ipython~=8.39",
"langdetect~=1.0", "langdetect~=1.0",
"lm-eval[hf]~=0.4", "lm-eval[hf]~=0.4",
"numpy~=2.2", "numpy~=2.2",
"optuna~=5.0", "optuna~=4.7",
"peft~=0.21", "peft~=0.19",
"psutil~=7.2", "psutil~=7.2",
"py-cpuinfo~=9.0", "py-cpuinfo~=9.0",
"pydantic-settings~=2.15", "pydantic-settings~=2.13",
"questionary~=2.1", "questionary~=2.1",
"rich~=15.0", "rich~=14.3",
"tomli-w~=1.2", "tomli-w~=1.2",
"torch", # version deliberately unspecified "torch", # version deliberately unspecified
"torchvision", # version deliberately unspecified "torchvision", # version deliberately unspecified
"tqdm~=4.70", "tqdm~=4.67",
"transformers[kernels]~=5.18", "transformers[kernels]~=5.6",
] ]
[dependency-groups] [dependency-groups]
dev = [ dev = [
"ruff>=0.16.9", "ruff>=0.14.5",
"ty>=0.0.84", "ty>=0.0.5",
] ]
[project.urls] [project.urls]
@ -64,30 +61,11 @@ Changelog = "https://github.com/p-e-w/heretic/releases"
heretic = "heretic.main:main" heretic = "heretic.main:main"
[build-system] [build-system]
requires = ["uv_build>=0.12.21,<0.13.0"] requires = ["uv_build>=0.8.11,<0.9.0"]
build-backend = "uv_build" 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] [tool.uv]
exclude-newer = "7 days" 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] [tool.uv.build-backend]
module-name = "heretic" module-name = "heretic"

View File

@ -1,9 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors # Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import os
from enum import Enum from enum import Enum
from typing import Any, Literal, TypeAlias from typing import Dict, Literal, TypeAlias
from pydantic import ( from pydantic import (
BaseModel, BaseModel,
@ -191,15 +190,6 @@ class BenchmarkSpecification(BaseModel):
) )
def _config_path() -> str:
path = os.environ.get("HERETIC_CONFIG_FILE", "config.toml")
if "HERETIC_CONFIG_FILE" in os.environ and not os.path.isfile(path):
raise SystemExit(f"heretic: configuration file {path} does not exist")
return path
class Settings(BaseSettings): class Settings(BaseSettings):
model: str = Field(description="Hugging Face model ID, or path to model on disk.") model: str = Field(description="Hugging Face model ID, or path to model on disk.")
@ -211,7 +201,7 @@ class Settings(BaseSettings):
evaluate_model: str | None = Field( evaluate_model: str | None = Field(
default=None, default=None,
description=( description=(
"If this model ID or path is set, then instead of modifying the main model, " "If this model ID or path is set, then instead of abliterating the main model, "
"evaluate this model relative to the main model." "evaluate this model relative to the main model."
), ),
exclude=True, exclude=True,
@ -220,7 +210,7 @@ class Settings(BaseSettings):
collect_reproducibles: str | None = Field( collect_reproducibles: str | None = Field(
default=None, default=None,
description=( description=(
"If this directory path is set, then instead of modifying a model, " "If this directory path is set, then instead of abliterating a model, "
"download all reproduce.json files from public Heretic model repositories " "download all reproduce.json files from public Heretic model repositories "
"on Hugging Face, and store them in that directory for archival purposes." "on Hugging Face, and store them in that directory for archival purposes."
), ),
@ -231,7 +221,7 @@ class Settings(BaseSettings):
default=None, default=None,
description=( description=(
"If this path or URL to a reproduce.json file is set, load reproduction information " "If this path or URL to a reproduce.json file is set, load reproduction information "
"from that file, and attempt to reproduce the modified model it originated from." "from that file, and attempt to reproduce the abliterated model it originated from."
), ),
exclude=True, exclude=True,
) )
@ -264,12 +254,12 @@ class Settings(BaseSettings):
), ),
) )
device_map: str | dict[str, int | str] = Field( device_map: str | Dict[str, int | str] = Field(
default="auto", default="auto",
description="Device map to pass to Accelerate when loading the model.", 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, default=None,
description='Maximum memory to allocate per device (e.g., { "0" = "20GB", "cpu" = "64GB" }).', description='Maximum memory to allocate per device (e.g., { "0" = "20GB", "cpu" = "64GB" }).',
) )
@ -342,31 +332,31 @@ class Settings(BaseSettings):
exclude=True, exclude=True,
) )
chain_of_thought_blocks: list[tuple[str, str]] = Field( chain_of_thought_skips: list[tuple[str, str]] = Field(
default=[ default=[
# Most thinking models. # Most thinking models.
( (
"<think>", "<think>",
"</think>", "<think></think>",
), ),
# gpt-oss. # gpt-oss.
( (
"<|channel|>analysis<|message|>", "<|channel|>analysis<|message|>",
"<|end|><|start|>assistant<|channel|>final<|message|>", "<|channel|>analysis<|message|><|end|><|start|>assistant<|channel|>final<|message|>",
), ),
# Unknown, suggested by user. # Unknown, suggested by user.
( (
"<thought>", "<thought>",
"</thought>", "<thought></thought>",
), ),
# Unknown, suggested by user. # Unknown, suggested by user.
( (
"[THINK]", "[THINK]",
"[/THINK]", "[THINK][/THINK]",
), ),
], ],
description=( description=(
"List of pairs of the form (cot_initializer, cot_finalizer) used to skip " "List of pairs of the form (cot_initializer, closed_cot_block) used to skip "
"the Chain-of-Thought block in responses, so that evaluation happens " "the Chain-of-Thought block in responses, so that evaluation happens "
"at the start of the actual response." "at the start of the actual response."
), ),
@ -415,7 +405,7 @@ class Settings(BaseSettings):
n_trials: PositiveInt = Field( n_trials: PositiveInt = Field(
default=100, default=100,
description="Number of trials to run during optimization.", description="Number of abliteration trials to run during optimization.",
) )
n_startup_trials: NonNegativeInt = Field( n_startup_trials: NonNegativeInt = Field(
@ -437,11 +427,6 @@ class Settings(BaseSettings):
exclude=True, exclude=True,
) )
modified_model_type: str = Field(
default="decensored",
description="Adjective describing the type of model produced by the configuration.",
)
benchmarks: list[BenchmarkSpecification] = Field( benchmarks: list[BenchmarkSpecification] = Field(
default=[ default=[
BenchmarkSpecification( BenchmarkSpecification(
@ -500,7 +485,7 @@ class Settings(BaseSettings):
description="An Adversarial Winograd Schema Challenge at Scale", description="An Adversarial Winograd Schema Challenge at Scale",
), ),
], ],
description="Benchmarks to offer to the user for evaluating modified models.", description="Benchmarks to offer to the user for evaluating abliterated models.",
exclude=True, exclude=True,
) )
@ -531,7 +516,7 @@ class Settings(BaseSettings):
model_action: str | None = Field( model_action: str | None = Field(
default=None, default=None,
description='Action to take with the modified model: "save", "upload", or unset to prompt the user.', description='Action to take with the decensored model: "save", "upload", or unset to prompt the user.',
) )
save_directory: str | None = Field( save_directory: str | None = Field(
@ -556,15 +541,6 @@ class Settings(BaseSettings):
description='Which reproducibility information to add to the Hugging Face repository: "full", "basic", "none", or unset to prompt the user.', 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( ignore_mismatches: bool | None = Field(
default=None, default=None,
description="Whether to attempt to reproduce the model even if there are environment mismatches, or unset to prompt the user.", description="Whether to attempt to reproduce the model even if there are environment mismatches, or unset to prompt the user.",
@ -575,15 +551,6 @@ class Settings(BaseSettings):
description="System prompt to use when prompting the model.", description="System prompt to use when prompting the model.",
) )
enable_shell: bool = Field(
default=False,
description=(
"Whether to offer the option to open an in-context Python shell in the trial selection menu. "
"WARNING: Enabling this feature gives full system access to the user of the Heretic session."
),
exclude=True,
)
# We intentionally allow extra keys so users can provide plugin-specific # We intentionally allow extra keys so users can provide plugin-specific
# configuration in TOML tables like `[scorer.KeywordRate]` which are later # configuration in TOML tables like `[scorer.KeywordRate]` which are later
# consumed via `settings.model_extra` (see `plugin.get_plugin_namespace`). # consumed via `settings.model_extra` (see `plugin.get_plugin_namespace`).
@ -599,7 +566,7 @@ class Settings(BaseSettings):
file_secret_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]: ) -> tuple[PydanticBaseSettingsSource, ...]:
return ( return (
init_settings, # Values passed to the constructor override all other sources. init_settings, # Used during resume - should override *all* other sources.
CliSettingsSource( CliSettingsSource(
settings_cls, settings_cls,
cli_parse_args=True, cli_parse_args=True,
@ -609,38 +576,5 @@ class Settings(BaseSettings):
EnvSettingsSource(settings_cls, env_prefix="HERETIC_"), EnvSettingsSource(settings_cls, env_prefix="HERETIC_"),
dotenv_settings, dotenv_settings,
file_secret_settings, file_secret_settings,
TomlConfigSettingsSource(settings_cls, toml_file=_config_path()), 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,)

View File

@ -174,9 +174,7 @@ class Evaluator:
""" """
records: list[dict[str, Any]] = [] records: list[dict[str, Any]] = []
for (name, score), (baseline_name, baseline) in zip( for (name, score), (baseline_name, baseline) in zip(
scores, scores, self.baseline_scores
self.baseline_scores,
strict=True,
): ):
assert name == baseline_name, ( assert name == baseline_name, (
f"Score/baseline order mismatch: {name!r} != {baseline_name!r}" f"Score/baseline order mismatch: {name!r} != {baseline_name!r}"
@ -230,10 +228,3 @@ class Evaluator:
parse_study_direction(entry.config.optimization) parse_study_direction(entry.config.optimization)
for entry in self._objective_entries() for entry in self._objective_entries()
] ]
def write_settings_to_config(self) -> None:
"""
Write the settings of all scorers to the global configuration.
"""
for entry in self._scorer_entries:
entry.scorer.write_settings_to_config("scorer", entry.config.instance_name)

View File

@ -1,20 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors # Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import os # ruff: noqa: E402
import sys 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). # Ensure standard output/error use UTF-8 instead of system default charmap (e.g. cp1252 on Windows).
for stream in (sys.stdout, sys.stderr): for stream in (sys.stdout, sys.stderr):
if ( if (
@ -23,7 +13,6 @@ for stream in (sys.stdout, sys.stderr):
): ):
stream.reconfigure(encoding="utf-8") # type: ignore stream.reconfigure(encoding="utf-8") # type: ignore
from .config import Settings from .config import Settings
@ -34,8 +23,7 @@ def _is_help_invocation() -> bool:
# Parse and handle CLI help before importing heavyweight ML/runtime dependencies. # Parse and handle CLI help before importing heavyweight ML/runtime dependencies.
if _is_help_invocation(): if _is_help_invocation():
Settings() Settings() # ty:ignore[missing-argument]
# FIXME: Rich progress bars are currently disabled because of rendering issues # FIXME: Rich progress bars are currently disabled because of rendering issues
# when used from multiple threads in parallel (e.g. by huggingface_hub). # when used from multiple threads in parallel (e.g. by huggingface_hub).
@ -47,9 +35,9 @@ from .progress import patch_tqdm
patch_tqdm() patch_tqdm()
""" """
import json
import logging import logging
import math import math
import os
import random import random
import re import re
import time import time
@ -60,12 +48,10 @@ from pathlib import Path
from typing import Any, cast from typing import Any, cast
import huggingface_hub import huggingface_hub
import IPython
import lm_eval import lm_eval
import numpy as np import numpy as np
import optuna import optuna
import questionary import questionary
import rich.traceback
import torch import torch
import transformers import transformers
from huggingface_hub import HfApi, ModelCard, ModelCardData from huggingface_hub import HfApi, ModelCard, ModelCardData
@ -81,6 +67,7 @@ from questionary import Choice, Style
from rich.markup import escape from rich.markup import escape
from rich.table import Table from rich.table import Table
from rich.text import Text from rich.text import Text
from rich.traceback import install
from .config import ( from .config import (
DatasetSpecification, DatasetSpecification,
@ -176,7 +163,7 @@ def obtain_export_strategy(
"How do you want to export the model?", "How do you want to export the model?",
choices=[ choices=[
Choice( Choice(
title="Merge the LoRA and export the full model" title="Merge the abliteration LoRA and export the full model"
+ ( + (
"" ""
if settings.quantization == QuantizationMethod.NONE if settings.quantization == QuantizationMethod.NONE
@ -185,7 +172,7 @@ def obtain_export_strategy(
value=ExportStrategy.MERGE, value=ExportStrategy.MERGE,
), ),
Choice( Choice(
title="Export the LoRA only (can be merged later)", title="Export the abliteration LoRA only (can be merged later)",
value=ExportStrategy.ADAPTER, value=ExportStrategy.ADAPTER,
), ),
], ],
@ -195,6 +182,13 @@ def obtain_export_strategy(
def run(): 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/ # Modified "Pagga" font from https://budavariam.github.io/asciiart-text/
print(f"[cyan]█░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀[/] v{version('heretic-llm')}") print(f"[cyan]█░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀[/] v{version('heretic-llm')}")
print( print(
@ -229,7 +223,7 @@ def run():
try: try:
# The required argument "model" must be provided by the user, # The required argument "model" must be provided by the user,
# either on the command line or in the configuration file. # either on the command line or in the configuration file.
settings = Settings() settings = Settings() # ty:ignore[missing-argument]
except ValidationError as error: except ValidationError as error:
print(f"[red]Configuration contains [bold]{error.error_count()}[/] errors:[/]") print(f"[red]Configuration contains [bold]{error.error_count()}[/] errors:[/]")
@ -257,11 +251,13 @@ def run():
if reproduction_information["version"] != "4": if reproduction_information["version"] != "4":
print( print(
(
f"[red]Unsupported file format version: [bold]{reproduction_information['version']}[/].[/] " f"[red]Unsupported file format version: [bold]{reproduction_information['version']}[/].[/] "
"This version of Heretic reads version 4 (plugin-based) reproduce.json files. " "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. " "Older files were produced before the introduction of the plugin system and are not supported. "
"Please install Heretic 1.4 to use these files." "Please install Heretic 1.4 to use these files."
) )
)
return return
if not check_environment(settings, reproduction_information): if not check_environment(settings, reproduction_information):
@ -269,9 +265,7 @@ def run():
print() print()
settings = Settings.model_validate_init_only( settings = Settings.model_validate(reproduction_information["settings"])
reproduction_information["settings"], settings
)
if settings.seed is None: if settings.seed is None:
settings.seed = random.randint(0, 2**32 - 1) settings.seed = random.randint(0, 2**32 - 1)
@ -345,11 +339,13 @@ def run():
if settings.checkpoint_action is None: if settings.checkpoint_action is None:
print() print()
print( print(
(
"[green]You have already processed this model.[/] " "[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. " "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. " "Alternatively, you can ignore the previous run and start from scratch. "
"This will delete the checkpoint file and all results from the previous run." "This will delete the checkpoint file and all results from the previous run."
) )
)
choices.append( choices.append(
Choice( Choice(
@ -361,11 +357,13 @@ def run():
if settings.checkpoint_action is None: if settings.checkpoint_action is None:
print() print()
print( print(
(
"[yellow]You have already processed this model, but the run was interrupted.[/] " "[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. " "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. " "Alternatively, you can ignore the previous run and start from scratch. "
"This will delete the checkpoint file and all results from the previous run." "This will delete the checkpoint file and all results from the previous run."
) )
)
choices.append( choices.append(
Choice( Choice(
@ -404,8 +402,8 @@ def run():
return return
if action == "continue": if action == "continue":
settings = Settings.model_validate_init_only( settings = Settings.model_validate_json(
json.loads(existing_study.user_attrs["settings"]), settings existing_study.user_attrs["settings"]
) )
elif action == "restart": elif action == "restart":
os.unlink(study_checkpoint_file) os.unlink(study_checkpoint_file)
@ -491,36 +489,19 @@ def run():
print(f"* [bold]{len(response_prefix_test_prompts)}[/] prompts loaded") print(f"* [bold]{len(response_prefix_test_prompts)}[/] prompts loaded")
print() print()
print( print("Checking for common response prefix...")
"Checking chat template for a closed Chain-of-Thought block or an initializer..."
)
# Detect if the model's chat template inserts a closed Chain-of-Thought block # Detect if the model's chat template inserts a reasoning tag on its own
# (e.g. <think></think>) or an initializer (e.g. <think>) on its own at the end # at the end of user's prompt (e.g. <think>) by using a dummy prompt.
# of the user's prompt by using a dummy prompt. # If found, then we use the full closed CoT as the response prefix.
# If a full closed block is found, no response prefix is required. If only an # LiquidAI's LFM models do this (Lfm2ForCausalLM).
# 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 # This cast is valid because str is the return type
# for a single chat operation with tokenize=False. # for a single chat operation with tokenize=False.
dummy_prompt = cast( dummy_prompt = cast(
str, str,
model.tokenizer.apply_chat_template( model.tokenizer.apply_chat_template(
dummy_messages, [{"role": "user", "content": "This is a dummy prompt."}],
add_generation_prompt=True, add_generation_prompt=True,
tokenize=False, tokenize=False,
), ),
@ -528,62 +509,29 @@ def run():
cot_skip_applied = False cot_skip_applied = False
for cot_initializer, cot_finalizer in settings.chain_of_thought_blocks: for cot_initializer, closed_cot_block in settings.chain_of_thought_skips:
# Check if the chat template already inserts the full closed CoT block # Match the tag and ignore any whitespace characters following it at the end
# (e.g. When thinking is disabled by the chat template). # (if any), including spaces, tabs, and linebreaks. This is required for models
# Smaller variants like Qwen/Qwen3.5-2B do this by inserting the full # having whitespaces after the tags.
# CoT block to disable thinking by default, while larger variants only pattern = rf"{re.escape(cot_initializer)}\s*$"
# insert the initializer to enable thinking by default (>=4B). match = re.search(pattern, dummy_prompt)
# 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"* 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: if match:
# The chat template already inserted the initializer, so we just # We use only the closed CoT block here. Any whitespaces
# supply the finalizer as the response prefix. So that when # will be handled by the 'Rechecking with prefix' logic below.
# concatenated to the prompts during generation, it forms a full settings.response_prefix = closed_cot_block
# 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( print(
f"* Chat template inserts CoT initializer: [bold]{escape(repr(cot_initializer))}[/]" f"* Closed Chain-of-Thought block: [bold]{escape(repr(settings.response_prefix))}[/]"
)
print(
f"* Remaining CoT finalizer: [bold]{escape(repr(cot_finalizer))}[/]"
) )
cot_skip_applied = True cot_skip_applied = True
break break
if not cot_skip_applied:
print("* None found")
# Fallback to inference for models like mistral-3 which are specifically # Fallback to inference for models like mistral-3 which are specifically
# instructed to generate the CoT block using the system prompt in their # instructed to generate thinking tags using the system prompt in their
# chat template, instead of inserting an initializer at the end of # chat template, instead of inserting a prefix tag (e.g. <think>) at
# the user prompt like the case above. The test prompts do not # the end of user prompt like the case above. We expect the model to
# override the system prompt, so here we expect the model to generate # generate those tags.
# 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: if settings.response_prefix is None:
print()
print("Checking for common response prefix...")
responses = model.get_responses_batched(response_prefix_test_prompts) responses = model.get_responses_batched(response_prefix_test_prompts)
# Despite being located in os.path, commonprefix actually performs # Despite being located in os.path, commonprefix actually performs
@ -601,10 +549,10 @@ def run():
for ( for (
cot_initializer, cot_initializer,
cot_finalizer, closed_cot_block,
) in settings.chain_of_thought_blocks: ) in settings.chain_of_thought_skips:
if settings.response_prefix.startswith(cot_initializer): if settings.response_prefix.startswith(cot_initializer):
settings.response_prefix = cot_initializer + cot_finalizer settings.response_prefix = closed_cot_block
print( print(
f"* Closed Chain-of-Thought block: [bold]{escape(repr(settings.response_prefix))}[/]" f"* Closed Chain-of-Thought block: [bold]{escape(repr(settings.response_prefix))}[/]"
) )
@ -613,13 +561,7 @@ def run():
else: else:
print("* None found") print("* None found")
# Only recheck if we actually supply a prefix to find any missed whitespaces if cot_skip_applied:
# 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 # When using a Chain-of-Thought skip, we need to check that the prefix
# is actually complete (e.g. not missing a trailing newline). # is actually complete (e.g. not missing a trailing newline).
print("* Rechecking with prefix...") print("* Rechecking with prefix...")
@ -662,18 +604,6 @@ def run():
modifier = modifier_entry.modifier modifier = modifier_entry.modifier
modifier_name = modifier_entry.name modifier_name = modifier_entry.name
def write_plugin_settings_to_config() -> None:
# Plugins may mutate their settings at any time (e.g. pinning dataset
# commits during initialization, or resolving values during scoring),
# so the effective plugin settings are recorded immediately before
# every serialization of the settings object, to ensure that the
# serialized settings reflect the exact configuration that was used.
evaluator.write_settings_to_config()
modifier.write_settings_to_config(
"modifier",
modifier_entry.config.instance_name,
)
# Clear cache before starting the optimization study. # Clear cache before starting the optimization study.
# This should free up memory from temporary objects created while initializing modifiers. # This should free up memory from temporary objects created while initializing modifiers.
empty_cache() empty_cache()
@ -752,7 +682,6 @@ def run():
load_if_exists=True, load_if_exists=True,
) )
write_plugin_settings_to_config()
study.set_user_attr("settings", settings.model_dump_json()) study.set_user_attr("settings", settings.model_dump_json())
study.set_user_attr("finished", False) study.set_user_attr("finished", False)
@ -829,14 +758,6 @@ def run():
) )
) )
if settings.enable_shell:
choices.append(
Choice(
title="Open in-context Python shell",
value="shell",
)
)
choices.append( choices.append(
Choice( Choice(
title="Exit program", title="Exit program",
@ -850,11 +771,13 @@ def run():
if settings.trial_index is None: if settings.trial_index is None:
print() print()
print( print(
(
"The following trials resulted in Pareto optimal combinations of the optimization objectives. " "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, " "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. " "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. " "You can return to this menu later to select a different trial. "
) )
)
while trial_loop_active: while trial_loop_active:
# Ensure a predefined trial is only processed once. # Ensure a predefined trial is only processed once.
@ -913,7 +836,6 @@ def run():
continue continue
settings.n_trials = len(study.trials) + n_additional_trials settings.n_trials = len(study.trials) + n_additional_trials
write_plugin_settings_to_config()
study.set_user_attr("settings", settings.model_dump_json()) study.set_user_attr("settings", settings.model_dump_json())
study.set_user_attr("finished", False) study.set_user_attr("finished", False)
@ -930,53 +852,6 @@ def run():
break break
if settings.enable_shell and trial == "shell":
print()
print(
"[bold blue]This is an IPython shell running inside this Heretic session.[/]"
)
print("Among other things, it has access to the following objects:")
print(
"* [bold]settings[/], which can be both read from and written to"
)
print(
"* [bold]model[/], with the [bold]model.model[/] and [bold]model.tokenizer[/] Transformers objects"
)
print(
"* [bold]study[/], containing all trials in [bold]study.trials[/], and the Pareto front in [bold]study.best_trials[/]"
)
print(
"* The special function [bold]choose_trial(trial)[/], which exits the shell and proceeds with the normal Heretic flow "
"using the given trial object. The trial object is not restricted to trials from the Pareto front, "
"and can even be constructed ad-hoc."
)
print(
"[yellow]The shell is not sandboxed and won't stop you from corrupting objects beyond repair. "
"With great power comes great responsibility.[/]"
)
def choose_trial(chosen_trial: Trial) -> None:
nonlocal trial
trial = chosen_trial
IPython.get_ipython().ask_exit()
# IPython installs a custom traceback handler
# that overrides the Rich handler we installed.
old_excepthook = sys.excepthook
try:
IPython.embed(
display_banner=False,
colors="neutral",
confirm_exit=False,
)
finally:
sys.excepthook = old_excepthook
if trial == "shell":
# choose_trial wasn't called inside the shell session.
continue
print() print()
print( print(
f"Restoring model from trial [bold]{trial.user_attrs['index']}[/]..." f"Restoring model from trial [bold]{trial.user_attrs['index']}[/]..."
@ -995,7 +870,7 @@ def run():
modifier.reset_model(ctx) modifier.reset_model(ctx)
print(f"* Modifying model using {modifier_name}...") print(f"* Modifying model using {modifier_name}...")
parameters = modifier.parameters_class.from_dict( parameters = modifier.parameters_class.from_dict(
trial.user_attrs["parameters"] # ty: ignore[unresolved-attribute] trial.user_attrs["parameters"]
) )
modifier.modify_model(ctx, parameters) modifier.modify_model(ctx, parameters)
@ -1014,7 +889,7 @@ def run():
action = ask_if_unset( action = ask_if_unset(
settings.model_action, settings.model_action,
questionary.select( questionary.select(
f"What do you want to do with the {settings.modified_model_type} model?", "What do you want to do with the decensored model?",
choices=[ choices=[
Choice( Choice(
title="Save the model to a local folder", title="Save the model to a local folder",
@ -1087,6 +962,7 @@ def run():
model.tokenizer.save_pretrained(save_directory) model.tokenizer.save_pretrained(save_directory)
if model.processor is not None: if model.processor is not None:
model.processor.save_pretrained(save_directory) model.processor.save_pretrained(save_directory)
reset_trial_model()
print(f"Model saved to [bold]{save_directory}[/].") print(f"Model saved to [bold]{save_directory}[/].")
@ -1115,9 +991,6 @@ def run():
f"[bold]{filename}:[/] [red]File not found[/]" f"[bold]{filename}:[/] [red]File not found[/]"
) )
if strategy != ExportStrategy.ADAPTER:
reset_trial_model()
case "upload": case "upload":
# We don't use huggingface_hub.login() because that stores the token on disk, # We don't use huggingface_hub.login() because that stores the token on disk,
# and since this program will often be run on rented or shared GPU servers, # and since this program will often be run on rented or shared GPU servers,
@ -1204,12 +1077,14 @@ def run():
if is_reproducible: if is_reproducible:
if settings.upload_reproducibility_information is None: if settings.upload_reproducibility_information is None:
print( print(
(
"Heretic can add information to the repository that allows others to reproduce the model. " "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. " "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) " "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. " "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.[/]" "[bold]The information does not include any file system paths or other private data.[/]"
) )
)
reproducibility_information = ask_if_unset( reproducibility_information = ask_if_unset(
settings.upload_reproducibility_information, settings.upload_reproducibility_information,
@ -1240,7 +1115,7 @@ def run():
if strategy == ExportStrategy.ADAPTER: if strategy == ExportStrategy.ADAPTER:
print("Uploading LoRA adapter...") print("Uploading LoRA adapter...")
model.model.push_to_hub( model.model.push_to_hub(
repo_id, # ty: ignore[invalid-argument-type] repo_id,
private=private, private=private,
max_shard_size=settings.max_shard_size, max_shard_size=settings.max_shard_size,
token=token, token=token,
@ -1249,7 +1124,7 @@ def run():
print("Uploading merged model...") print("Uploading merged model...")
merged_model = model.get_merged_model() merged_model = model.get_merged_model()
merged_model.push_to_hub( merged_model.push_to_hub(
repo_id, # ty: ignore[invalid-argument-type] repo_id,
private=private, private=private,
max_shard_size=settings.max_shard_size, max_shard_size=settings.max_shard_size,
token=token, token=token,
@ -1267,6 +1142,7 @@ def run():
private=private, private=private,
token=token, token=token,
) )
reset_trial_model()
if is_hf_path(settings.model): if is_hf_path(settings.model):
card = ModelCard.load(settings.model) card = ModelCard.load(settings.model)
@ -1285,15 +1161,11 @@ def run():
card.data = ModelCardData() card.data = ModelCardData()
if card.data.tags is None: if card.data.tags is None:
card.data.tags = [] card.data.tags = []
if "heretic" not in card.data.tags:
card.data.tags.append("heretic") card.data.tags.append("heretic")
for tag in settings.upload_tags: card.data.tags.append("uncensored")
if tag not in card.data.tags: card.data.tags.append("decensored")
card.data.tags.append(tag) card.data.tags.append("abliterated")
if ( if reproducibility_information != "none":
reproducibility_information != "none"
and "reproducible" not in card.data.tags
):
card.data.tags.append("reproducible") card.data.tags.append("reproducible")
# Must be a Hugging Face Hub repository ID, # Must be a Hugging Face Hub repository ID,
@ -1313,22 +1185,8 @@ def run():
card.push_to_hub(repo_id, token=token) card.push_to_hub(repo_id, token=token)
if reproducibility_information != "none": if reproducibility_information != "none":
# Record the final effective plugin settings so that the
# exported config.toml and reproduce.json reflect the exact
# configuration that was used.
write_plugin_settings_to_config()
# Refresh the settings stored in the study journal to allow
# continuation with the current plugin state.
study.set_user_attr(
"settings",
settings.model_dump_json(),
)
# Set the number of trials to the number of actual completed trials # Set the number of trials to the number of actual completed trials
# for the reproduction configuration. # for the reproduction configuration.
# These updates are deliberately *not* written to the journal,
# because the purpose of the journal is continuing the study with
# more trials, and potentially choosing a different export strategy.
settings.n_trials = len(study.trials) settings.n_trials = len(study.trials)
current_export_strategy = settings.export_strategy current_export_strategy = settings.export_strategy
settings.export_strategy = strategy settings.export_strategy = strategy
@ -1401,9 +1259,6 @@ def run():
f"[bold]{filename}:[/] [red]File not found[/]" f"[bold]{filename}:[/] [red]File not found[/]"
) )
if strategy != ExportStrategy.ADAPTER:
reset_trial_model()
case "chat": case "chat":
print() print()
print( print(
@ -1450,11 +1305,11 @@ def run():
scope = questionary.select( scope = questionary.select(
( (
f"Do you want to benchmark the original model along with the {settings.modified_model_type} model? " "Do you want to benchmark the original model along with the decensored model? "
"Benchmarking both models allows you to compare the scores, but it takes twice as much time." "Benchmarking both models allows you to compare the scores, but it takes twice as much time."
), ),
choices=[ choices=[
f"Benchmark only the {settings.modified_model_type} model", "Benchmark only the decensored model",
"Benchmark both models", "Benchmark both models",
], ],
style=Style([("highlighted", "reverse")]), style=Style([("highlighted", "reverse")]),
@ -1464,7 +1319,7 @@ def run():
benchmark_original_model = scope == "Benchmark both models" benchmark_original_model = scope == "Benchmark both models"
hflm = HFLM( hflm = HFLM(
pretrained=model.model, pretrained=model.model, # ty:ignore[invalid-argument-type]
tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type] tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type]
batch_size="auto", batch_size="auto",
) )
@ -1478,15 +1333,6 @@ def run():
else: else:
table.add_column("Value", justify="right") 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: try:
first_benchmark = True first_benchmark = True
@ -1510,16 +1356,22 @@ def run():
first_row = True first_row = True
for metric, value in results.items(): for metric, value in results.items():
# Skip non-metrics. if metric != "alias":
if metric in ["name", "alias", "sample_len"]:
continue
if first_row and not first_benchmark: if first_row and not first_benchmark:
if benchmark_original_model: if benchmark_original_model:
table.add_row("", "", "", "") table.add_row("", "", "", "")
else: else:
table.add_row("", "", "") table.add_row("", "", "")
def format_value(value: Any) -> str:
if isinstance(
value,
(float, np.floating),
):
return f"{value:.4f}"
else:
return f"{value}"
cells = [ cells = [
benchmark.name if first_row else "", benchmark.name if first_row else "",
metric, metric,
@ -1527,7 +1379,9 @@ def run():
] ]
if benchmark_original_model: if benchmark_original_model:
cells.append( cells.append(
format_value(original_results[metric]) format_value(
original_results[metric]
)
) )
table.add_row(*cells) table.add_row(*cells)
@ -1551,7 +1405,8 @@ def run():
def main(): def main():
rich.traceback.install() # Install Rich traceback handler.
install()
try: try:
run() run()

View File

@ -1,10 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors # Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from collections.abc import Callable
from contextlib import suppress from contextlib import suppress
from datetime import datetime, timezone from typing import Any, Callable, Type, TypeAlias, cast
from typing import Any, TypeAlias, cast
import torch import torch
from peft import LoraConfig, PeftModel, get_peft_model from peft import LoraConfig, PeftModel, get_peft_model
@ -25,7 +23,7 @@ from transformers import (
TextStreamer, TextStreamer,
) )
from transformers.generation import ( from transformers.generation import (
GenerateDecoderOnlyOutput, GenerateDecoderOnlyOutput, # ty:ignore[possibly-missing-import]
) )
from .config import QuantizationMethod, Settings from .config import QuantizationMethod, Settings
@ -35,95 +33,15 @@ from .utils import Prompt, batchify, format_exception, print
def get_model_class( def get_model_class(
model: str, model: str,
) -> type[AutoModelForImageTextToText] | type[AutoModelForCausalLM]: ) -> Type[AutoModelForImageTextToText] | Type[AutoModelForCausalLM]:
configs = PretrainedConfig.get_config_dict(model) 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 return AutoModelForImageTextToText
else: else:
return AutoModelForCausalLM return AutoModelForCausalLM
def check_model_resident(model: PreTrainedModel | PeftModel) -> None:
"""
Ensure that all of the model's weights are resident in memory.
"""
offloaded = [name for name, param in model.named_parameters() if param.is_meta]
if not offloaded:
return
raise Exception(
"The model does not fit into the available device memory: "
f"{len(offloaded)} weights (such as {', '.join(offloaded[:3])}) had to "
"be offloaded to CPU or disk. Heretic cannot process offloaded models "
"because it requires direct, persistent access to all weights, whereas "
"offloaded weights only exist temporarily during forward passes.\n"
"Possible remedies:\n"
"* Free up memory, e.g. by closing other applications.\n"
"* Change the device map (device_map/max_memory settings) so that all "
"weights fit into device memory.\n"
'* Enable 4-bit quantization (quantization = "bnb_4bit").'
)
def _collapse_flattened_residual_streams(
hidden_states: tuple[FloatTensor, ...],
config: Any,
) -> 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. # The list contains one element per layer.
# Each element maps from the component name to a (possibly sparse) mapping # 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 # from the module index to an (input, output) tuple containing the I/O
@ -138,8 +56,6 @@ class Model:
processor: ProcessorMixin | None processor: ProcessorMixin | None
peft_config: LoraConfig peft_config: LoraConfig
dtype: torch.dtype dtype: torch.dtype
# Whether the model's chat template accepts a system role (see __init__).
supports_system_role: bool
def __init__(self, settings: Settings): def __init__(self, settings: Settings):
self.settings = settings self.settings = settings
@ -152,14 +68,9 @@ class Model:
print() print()
print(f"Loading model [bold]{settings.model}[/]...") print(f"Loading model [bold]{settings.model}[/]...")
# PreTrainedTokenizerBase is the "base class for all tokenizer backends" self.tokenizer = AutoTokenizer.from_pretrained(
# according to the documentation.
self.tokenizer = cast(
PreTrainedTokenizerBase,
AutoTokenizer.from_pretrained(
settings.model, settings.model,
**self.revision_kwargs, **self.revision_kwargs,
),
) )
# Multimodal models have a processor we'll want to save. # Multimodal models have a processor we'll want to save.
@ -179,12 +90,7 @@ class Model:
# after the prompt and thinks the sequence is complete. # after the prompt and thinks the sequence is complete.
self.tokenizer.padding_side = "left" self.tokenizer.padding_side = "left"
# Detect once whether this tokenizer's chat template accepts a system self.model = None # ty:ignore[invalid-assignment]
# 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 = ( self.max_memory = (
{int(k) if k.isdigit() else k: v for k, v in settings.max_memory.items()} {int(k) if k.isdigit() else k: v for k, v in settings.max_memory.items()}
if settings.max_memory if settings.max_memory
@ -235,13 +141,9 @@ class Model:
) )
], ],
max_new_tokens=1, max_new_tokens=1,
# The KV cache is deliberately left enabled here so we can
# catch dtype errors related to the cache, which we will need
# for generating responses.
# use_cache=False,
) )
except Exception as error: except Exception as error:
self.model = None self.model = None # ty:ignore[invalid-assignment]
empty_cache() empty_cache()
formatted = format_exception(error) formatted = format_exception(error)
@ -260,8 +162,6 @@ class Model:
if self.model is None: if self.model is None:
raise Exception("Failed to load model with all configured dtypes.") raise Exception("Failed to load model with all configured dtypes.")
check_model_resident(self.model)
print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers") print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers")
all_components = {} all_components = {}
@ -271,7 +171,7 @@ class Model:
all_components[component] = 0 all_components[component] = 0
all_components[component] += len(modules) all_components[component] += len(modules)
print("* Modifiable components:") print("* Abliterable components:")
for component, count in all_components.items(): for component, count in all_components.items():
print(f" * [bold]{component}[/]: [bold]{count}[/] modules total") print(f" * [bold]{component}[/]: [bold]{count}[/] modules total")
@ -279,7 +179,7 @@ class Model:
# Guard against calling this method at the wrong time. # Guard against calling this method at the wrong time.
assert isinstance(self.model, PreTrainedModel) assert isinstance(self.model, PreTrainedModel)
# Always use LoRA adapters for modification (faster reload, no weight modification). # Always use LoRA adapters for abliteration (faster reload, no weight modification).
# Collect actual leaf module names from the model for LoRA targeting. # 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") # 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 # because hybrid models like Qwen3.5 MoE have modules with different names
@ -315,15 +215,6 @@ class Model:
# so the result is a PeftModel rather than a PeftMixedModel. # so the result is a PeftModel rather than a PeftMixedModel.
self.model = cast(PeftModel, get_peft_model(self.model, self.peft_config)) 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: def _get_quantization_config(self, dtype: str) -> BitsAndBytesConfig | None:
""" """
Creates quantization config based on settings. Creates quantization config based on settings.
@ -418,13 +309,13 @@ class Model:
if current_model == self.settings.model and not self.needs_reload: if current_model == self.settings.model and not self.needs_reload:
# Reset LoRA adapters to zero (identity transformation). # Reset LoRA adapters to zero (identity transformation).
# Zeroing A as well ensures that adapter weights of modules not modified for name, module in self.model.named_modules():
# by the next trial don't depend on what previous trials did. if "lora_B" in name and hasattr(module, "weight"):
self._zero_lora_weights() torch.nn.init.zeros_(module.weight)
return True return True
# Purge existing model object from memory to make space. # Purge existing model object from memory to make space.
self.model = None self.model = None # ty:ignore[invalid-assignment]
empty_cache() empty_cache()
quantization_config = self._get_quantization_config( quantization_config = self._get_quantization_config(
@ -448,8 +339,6 @@ class Model:
**extra_kwargs, **extra_kwargs,
) )
check_model_resident(self.model)
self.needs_reload = False self.needs_reload = False
return False return False
@ -463,10 +352,10 @@ class Model:
# Most multimodal models. # Most multimodal models.
with suppress(Exception): with suppress(Exception):
return model.model.language_model.layers # ty: ignore[unresolved-attribute, invalid-return-type] return model.model.language_model.layers
# Text-only models. # Text-only models.
return model.model.layers # ty: ignore[unresolved-attribute, invalid-return-type] return model.model.layers
def get_layer_modules(self, layer_index: int) -> dict[str, list[Module]]: def get_layer_modules(self, layer_index: int) -> dict[str, list[Module]]:
layer = self.get_layers()[layer_index] layer = self.get_layers()[layer_index]
@ -487,70 +376,58 @@ class Model:
# Standard self-attention out-projection (most models). # Standard self-attention out-projection (most models).
with suppress(Exception): with suppress(Exception):
try_add("attn.o_proj", layer.self_attn.o_proj) # ty: ignore[unresolved-attribute] try_add("attn.o_proj", layer.self_attn.o_proj) # ty:ignore[possibly-missing-attribute]
# Qwen3.5 MoE hybrid layers use GatedDeltaNet (linear attention) instead of # 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. # standard self-attention, so self_attn.o_proj doesn't exist on those layers.
with suppress(Exception): with suppress(Exception):
try_add("attn.o_proj", layer.linear_attn.out_proj) # ty: ignore[unresolved-attribute] try_add("attn.o_proj", layer.linear_attn.out_proj) # ty:ignore[possibly-missing-attribute]
# DeepSeek V4.
with suppress(Exception):
try_add("attn.o_proj", layer.self_attn.o_b_proj) # ty: ignore[unresolved-attribute]
# Most dense models. # Most dense models.
with suppress(Exception): with suppress(Exception):
try_add("mlp.down_proj", layer.mlp.down_proj) # ty: ignore[unresolved-attribute] try_add("mlp.down_proj", layer.mlp.down_proj) # ty:ignore[possibly-missing-attribute]
# Some MoE models (e.g. Qwen3). # Some MoE models (e.g. Qwen3).
with suppress(Exception): with suppress(Exception):
for expert in layer.mlp.experts: # ty:ignore[not-iterable, unresolved-attribute] for expert in layer.mlp.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.down_proj) # ty: ignore[unresolved-attribute] try_add("mlp.down_proj", expert.down_proj) # ty:ignore[possibly-missing-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). # Phi-3.5-MoE (and possibly others).
with suppress(Exception): with suppress(Exception):
for expert in layer.block_sparse_moe.experts: # ty:ignore[not-iterable, unresolved-attribute] for expert in layer.block_sparse_moe.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.w2) # ty: ignore[unresolved-attribute] try_add("mlp.down_proj", expert.w2) # ty:ignore[possibly-missing-attribute]
# LFM dense operator blocks. # LFM dense operator blocks.
with suppress(Exception): with suppress(Exception):
try_add("attn.o_proj", layer.conv.out_proj) # ty: ignore[unresolved-attribute] try_add("attn.o_proj", layer.conv.out_proj) # ty:ignore[possibly-missing-attribute]
with suppress(Exception): with suppress(Exception):
try_add("mlp.down_proj", layer.feed_forward.w2) # ty: ignore[unresolved-attribute] try_add("mlp.down_proj", layer.feed_forward.w2) # ty:ignore[possibly-missing-attribute]
# LFM transformer blocks. # LFM transformer blocks.
with suppress(Exception): with suppress(Exception):
try_add("attn.o_proj", layer.self_attn.out_proj) # ty: ignore[unresolved-attribute] try_add("attn.o_proj", layer.self_attn.out_proj) # ty:ignore[possibly-missing-attribute]
with suppress(Exception): with suppress(Exception):
for expert in layer.feed_forward.experts: # ty:ignore[not-iterable, unresolved-attribute] for expert in layer.feed_forward.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.w2) # ty: ignore[unresolved-attribute] try_add("mlp.down_proj", expert.w2) # ty:ignore[possibly-missing-attribute]
# Granite MoE Hybrid - attention layers with shared_mlp. # Granite MoE Hybrid - attention layers with shared_mlp.
with suppress(Exception): with suppress(Exception):
try_add("mlp.down_proj", layer.shared_mlp.output_linear) # ty: ignore[unresolved-attribute] try_add("mlp.down_proj", layer.shared_mlp.output_linear) # ty:ignore[possibly-missing-attribute]
# Granite MoE Hybrid - MoE layers with experts. # Granite MoE Hybrid - MoE layers with experts.
with suppress(Exception): with suppress(Exception):
for expert in layer.moe.experts: # ty:ignore[not-iterable, unresolved-attribute] for expert in layer.moe.experts: # ty:ignore[possibly-missing-attribute, not-iterable]
try_add("mlp.down_proj", expert.output_linear) # ty: ignore[unresolved-attribute] try_add("mlp.down_proj", expert.output_linear) # ty:ignore[possibly-missing-attribute]
# We need at least one module across all components. # We need at least one module across all components for abliteration to work.
total_modules = sum(len(mods) for mods in modules.values()) total_modules = sum(len(mods) for mods in modules.values())
assert total_modules > 0, "No modifiable modules found in layer" assert total_modules > 0, "No abliterable modules found in layer"
return modules return modules
def get_modifiable_components(self) -> list[str]: def get_abliterable_components(self) -> list[str]:
components: set[str] = set() components: set[str] = set()
# Scan all layers because hybrid models (e.g. Qwen3.5 MoE) have different # Scan all layers because hybrid models (e.g. Qwen3.5 MoE) have different
@ -560,46 +437,16 @@ class Model:
return sorted(components) 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( def generate(
self, self,
prompts: list[Prompt], prompts: list[Prompt],
**kwargs: Any, **kwargs: Any,
) -> tuple[BatchEncoding, GenerateDecoderOnlyOutput | LongTensor]: ) -> tuple[BatchEncoding, GenerateDecoderOnlyOutput | LongTensor]:
chats = [ chats = [
self._apply_system_role(
[ [
{"role": "system", "content": prompt.system}, {"role": "system", "content": prompt.system},
{"role": "user", "content": prompt.user}, {"role": "user", "content": prompt.user},
] ]
)
for prompt in prompts for prompt in prompts
] ]
@ -611,8 +458,6 @@ class Model:
chats, chats,
add_generation_prompt=True, add_generation_prompt=True,
tokenize=False, tokenize=False,
# Overrides the function that templates call to get the current date.
strftime_now=strftime_fixed_date,
), ),
) )
@ -667,12 +512,11 @@ class Model:
responses = [] responses = []
for batch in batchify(prompts, self.settings.batch_size): for batch in batchify(prompts, self.settings.batch_size):
responses.extend( for response in self.get_responses(
self.get_responses(
batch, batch,
skip_special_tokens=skip_special_tokens, skip_special_tokens=skip_special_tokens,
) ):
) responses.append(response)
return responses return responses
@ -701,25 +545,6 @@ class Model:
# This cast is valid because we passed output_hidden_states=True above. # This cast is valid because we passed output_hidden_states=True above.
hidden_states = cast(tuple[tuple[FloatTensor]], outputs.hidden_states)[0] 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). # The returned tensor has shape (prompt, layer, component).
residuals = torch.stack( residuals = torch.stack(
# layer_hidden_states has shape (prompt, position, component), # layer_hidden_states has shape (prompt, position, component),
@ -859,11 +684,7 @@ class Model:
) )
) )
self.generate( self.generate(prompts, max_new_tokens=1)
prompts,
max_new_tokens=1,
use_cache=False,
)
for hook_handle in hook_handles: for hook_handle in hook_handles:
hook_handle.remove() hook_handle.remove()
@ -967,7 +788,6 @@ class Model:
return torch.cat(logits, dim=0) return torch.cat(logits, dim=0)
def stream_chat_response(self, chat: list[dict[str, str]]) -> str: 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 # This cast is valid because str is the return type
# for single-chat operation with tokenize=False. # for single-chat operation with tokenize=False.
chat_prompt = cast( chat_prompt = cast(
@ -989,7 +809,7 @@ class Model:
# The TextStreamer constructor annotates this parameter with the AutoTokenizer # The TextStreamer constructor annotates this parameter with the AutoTokenizer
# type, which makes no sense because AutoTokenizer is a factory class, # type, which makes no sense because AutoTokenizer is a factory class,
# not a base class that tokenizers inherit from. # not a base class that tokenizers inherit from.
self.tokenizer, self.tokenizer, # ty:ignore[invalid-argument-type]
skip_prompt=True, skip_prompt=True,
skip_special_tokens=True, skip_special_tokens=True,
) )

View File

@ -32,7 +32,7 @@ class Serializable(Protocol):
Parameters = TypeVar("Parameters", bound=Serializable) Parameters = TypeVar("Parameters", bound=Serializable)
class Modifier(Plugin, ABC, Generic[Parameters]): class Modifier(Generic[Parameters], Plugin, ABC):
""" """
Abstract base class for modifier plugins. Abstract base class for modifier plugins.

View File

@ -6,7 +6,7 @@ from dataclasses import asdict, dataclass
from enum import Enum from enum import Enum
from typing import Any, cast from typing import Any, cast
import bitsandbytes.functional as BNB_F import bitsandbytes as bnb
import torch import torch
import torch.linalg as LA import torch.linalg as LA
import torch.nn.functional as F import torch.nn.functional as F
@ -255,7 +255,7 @@ class Abliteration(Modifier[Parameters]):
weight_distributions = {} weight_distributions = {}
for component in model.get_modifiable_components(): for component in model.get_abliterable_components():
# The parameter ranges are based on experiments with various models # 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 # and much wider ranges. They are not set in stone and might have to be
# adjusted for future models. # adjusted for future models.
@ -332,7 +332,9 @@ class Abliteration(Modifier[Parameters]):
weight_distribution = parameters.weight_distributions[component] weight_distribution = parameters.weight_distributions[component]
# Type inference fails here for some reason. # Type inference fails here for some reason.
distance = abs(layer_index - weight_distribution.max_weight_position) distance = cast(
float, abs(layer_index - weight_distribution.max_weight_position)
)
# Don't orthogonalize layers that are more than # Don't orthogonalize layers that are more than
# min_weight_distance away from max_weight_position. # min_weight_distance away from max_weight_position.
@ -388,10 +390,15 @@ class Abliteration(Modifier[Parameters]):
W = base_weight.to(torch.float32) W = base_weight.to(torch.float32)
else: else:
# 4-bit quantization. # 4-bit quantization.
W = BNB_F.dequantize_4bit( # 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, base_weight.data,
quant_state, quant_state,
).to(torch.float32) ).to(torch.float32),
)
# Flatten weight matrix to (out_features, in_features). # Flatten weight matrix to (out_features, in_features).
W = W.view(W.shape[0], -1) W = W.view(W.shape[0], -1)

View File

@ -4,13 +4,13 @@
# Arbitrary-Rank Ablation (ARA) (Weidmann 2026) # Arbitrary-Rank Ablation (ARA) (Weidmann 2026)
# See https://github.com/p-e-w/heretic/pull/211 for more information. # See https://github.com/p-e-w/heretic/pull/211 for more information.
import math
from dataclasses import asdict, dataclass from dataclasses import asdict, dataclass
from typing import Any, cast from typing import Any, cast
import bitsandbytes.functional as BNB_F import bitsandbytes as bnb
import torch import torch
import torch.linalg as LA import torch.linalg as LA
import torch.nn.functional as F
from optuna import Trial from optuna import Trial
from peft.tuners.lora.layer import Linear from peft.tuners.lora.layer import Linear
from pydantic import ( from pydantic import (
@ -188,9 +188,6 @@ class ARA(Modifier[Parameters]):
bad_prompts = ctx.load_prompts(self.settings.bad_prompts) bad_prompts = ctx.load_prompts(self.settings.bad_prompts)
print(f"* [bold]{len(bad_prompts)}[/] prompts loaded") print(f"* [bold]{len(bad_prompts)}[/] prompts loaded")
self.good_prompt_count = len(good_prompts)
self.bad_prompt_count = len(bad_prompts)
print() print()
print("Obtaining module I/O for good prompts...") print("Obtaining module I/O for good prompts...")
self.good_module_io = model.get_module_io_batched(good_prompts) self.good_module_io = model.get_module_io_batched(good_prompts)
@ -211,11 +208,9 @@ class ARA(Modifier[Parameters]):
0, 0,
layer_count // 2, 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 = trial.suggest_int(
"end_layer_index", "end_layer_index",
layer_count // 2 + 1, layer_count // 2,
layer_count, layer_count,
) )
preserve_good_behavior_weight = trial.suggest_float( preserve_good_behavior_weight = trial.suggest_float(
@ -234,12 +229,10 @@ class ARA(Modifier[Parameters]):
0.0, 0.0,
1.3, 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 = trial.suggest_int(
"neighbor_count", "neighbor_count",
1, 1,
min(15, self.good_prompt_count, self.bad_prompt_count), 15,
) )
return Parameters( return Parameters(
@ -254,11 +247,6 @@ class ARA(Modifier[Parameters]):
def modify_model(self, ctx: Context, parameters: Parameters) -> None: def modify_model(self, ctx: Context, parameters: Parameters) -> None:
model = ctx.get_model() 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( for layer_index in range(
parameters.start_layer_index, parameters.start_layer_index,
parameters.end_layer_index, parameters.end_layer_index,
@ -276,10 +264,13 @@ class ARA(Modifier[Parameters]):
W_base = base_weight.to(torch.float32) W_base = base_weight.to(torch.float32)
else: else:
# Use the original dequantization logic from bitsandbytes. # Use the original dequantization logic from bitsandbytes.
W_base = BNB_F.dequantize_4bit( W_base = cast(
Tensor,
bnb.functional.dequantize_4bit( # ty:ignore[possibly-missing-attribute]
base_weight.data, base_weight.data,
quant_state, quant_state,
).to(torch.float32) ).to(torch.float32),
)
# Pre-calculate the original row norms to preserve them. # Pre-calculate the original row norms to preserve them.
# See https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration # See https://huggingface.co/blog/grimjim/norm-preserving-biprojected-abliteration
@ -292,17 +283,6 @@ class ARA(Modifier[Parameters]):
lora_A = cast(Tensor, module.lora_A["default"].weight) lora_A = cast(Tensor, module.lora_A["default"].weight)
lora_B = cast(Tensor, module.lora_B["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. # Move I/O tensors to the device of the adapter weights.
good_input, good_output = self.good_module_io[layer_index][ good_input, good_output = self.good_module_io[layer_index][
component component
@ -316,43 +296,18 @@ class ARA(Modifier[Parameters]):
bad_input = bad_input.float().to(lora_A.device) bad_input = bad_input.float().to(lora_A.device)
bad_output = bad_output.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: def objective(A: Tensor, B: Tensor) -> Tensor:
# input @ (W_base + B @ A).T # Calculate effective weight after applying adapter.
# = input @ W_base.T + (input @ A.T) @ B.T W_eff = W_base + (B @ A)
# 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: if self.settings.preserve_row_magnitudes:
# Row normalization rescales each output row by # Normalize to unit length, then scale by original norms,
# (original row norm / effective row norm), which applies # preserving the original row norms.
# directly to the outputs as a per-column factor. W_eff = F.normalize(W_eff, p=2, dim=1) * W_row_norms
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
if bias is not None: # Compute outputs using the effective weight.
new_good_output = new_good_output + bias new_good_output = good_input @ W_eff.T
new_bad_output = new_bad_output + bias new_bad_output = bad_input @ W_eff.T
return ara_loss( return ara_loss(
good_output, good_output,

View File

@ -8,16 +8,7 @@ import sys
import types import types
from pathlib import Path from pathlib import Path
from types import ModuleType from types import ModuleType
from typing import ( from typing import Annotated, Any, TypeVar, Union, get_args, get_origin, get_type_hints
Annotated,
Any,
TypeVar,
Union,
cast,
get_args,
get_origin,
get_type_hints,
)
from pydantic import BaseModel from pydantic import BaseModel
from torch import Tensor from torch import Tensor
@ -211,23 +202,14 @@ class Plugin:
""" """
Whether runs using this plugin can be reproduced bit-for-bit. Whether runs using this plugin can be reproduced bit-for-bit.
Set to False if the plugin's behavior is not deterministic or depends on Set to False when the plugin's behavior is not deterministic or depends on
state outside the pinned config, for example: state outside the pinned config, for example:
- It calls an external service (e.g. an LLM judge over the OpenAI API). - It calls an external service (e.g. an LLM judge over the OpenAI API).
- It reads credentials or config from the environment (env vars, files). - It reads credentials or config from the environment (env vars, files).
- It is otherwise non-deterministic (network, wall-clock, unseeded RNG). - It is otherwise non-deterministic (network, wall-clock, unseeded RNG).
Defaults to False; override to True in your plugin class if the Defaults to False; override to True in your plugin class if any of the
above DO NOT apply. above DO NOT apply.
Note: The plugin can use non-deterministic/external state if the plugin
evaluates the state during initialization and stores it in its settings
object in such a way that re-running the plugin with the modified settings
guarantees identical state. A plugin may also do this after initialization
(i.e., during execution), but only if setting that state at initialization
time during a later run results in identical plugin behavior. This can be
used to perform tasks such as pinning dataset commits, or automatically
determining batch sizes.
""" """
return False return False
@ -356,28 +338,6 @@ class Plugin:
return None return None
return settings_model.model_validate(raw_namespace or {}) return settings_model.model_validate(raw_namespace or {})
def write_settings_to_config(
self,
top_namespace: str,
instance_name: str | None,
) -> None:
"""
Write the plugin's effective (validated) settings back into
`heretic_settings.model_extra`, under the same namespace from which
the raw settings were read.
"""
if self.settings is None:
return
class_name = self.__class__.__name__
key = class_name if not instance_name else f"{class_name}_{instance_name}"
# Settings uses extra="allow", so model_extra is always a dictionary.
extra = cast(dict[str, Any], self.heretic_settings.model_extra)
namespace: dict[str, Any] = extra.setdefault(top_namespace, {})
namespace[key] = self.settings.model_dump()
def get_dataset_specifications(self) -> list[DatasetSpecification]: def get_dataset_specifications(self) -> list[DatasetSpecification]:
""" """
Collect the dataset specifications declared in the settings Collect the dataset specifications declared in the settings
@ -402,4 +362,4 @@ class Plugin:
Override this in subclasses to do one-time setup (e.g. load prompts, compute Override this in subclasses to do one-time setup (e.g. load prompts, compute
baselines). baselines).
""" """
return return None

View File

@ -81,7 +81,7 @@ def collect_reproducibles(path: str):
found += 1 found += 1
commit_hash = paths_info[0].last_commit.oid # ty: ignore[unresolved-attribute] commit_hash = paths_info[0].last_commit.oid
file_path = ( file_path = (
Path(path) Path(path)
@ -285,11 +285,13 @@ def check_environment(
else: else:
print( print(
(
"[yellow]The provided JSON file does not contain system information. " "[yellow]The provided JSON file does not contain system information. "
"Some system parameters can affect reproducibility, but due to the lack of 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. " "Heretic is unable to verify that those parameters match the original environment. "
"Reproduction may or may not produce a byte-for-byte identical model.[/]" "Reproduction may or may not produce a byte-for-byte identical model.[/]"
) )
)
requirements = get_requirements_dict() requirements = get_requirements_dict()
requirements["heretic-llm"] = format_version_information( requirements["heretic-llm"] = format_version_information(
@ -319,9 +321,11 @@ def check_environment(
if system_mismatches or package_mismatches: if system_mismatches or package_mismatches:
print() print()
print( print(
(
"[yellow]Your local environment doesn't perfectly match the environment " "[yellow]Your local environment doesn't perfectly match the environment "
"used to produce the original model. The following components differ:[/]" "used to produce the original model. The following components differ:[/]"
) )
)
if system_mismatches: if system_mismatches:
table = Table() table = Table()
@ -354,11 +358,13 @@ def check_environment(
if system_mismatches or package_mismatches: if system_mismatches or package_mismatches:
print() print()
print( print(
(
f"There is a {cast(MismatchSeverity, mismatch_severity).__rich__()} chance " f"There is a {cast(MismatchSeverity, mismatch_severity).__rich__()} chance "
"that reproduction won't produce a byte-for-byte identical model. " "that reproduction won't produce a byte-for-byte identical model. "
"However, the resulting model will very likely still behave similarly " "However, the resulting model will very likely still behave similarly "
"to the original model." "to the original model."
) )
)
if settings.ignore_mismatches is None: if settings.ignore_mismatches is None:
print() print()

View File

@ -53,6 +53,8 @@ class Scorer(Plugin, ABC):
def get_score(self, ctx: Context) -> Score: def get_score(self, ctx: Context) -> Score:
""" """
Return a `Score` given the evaluation context. Return a `Score` given the evaluation context.
The `value` of the `Score` must be of the order of magnitude 1
to ensure that all scores are comparable during co-optimization.
""" """
def get_baseline_score(self, ctx: Context) -> Score: def get_baseline_score(self, ctx: Context) -> Score:

View File

@ -3,7 +3,7 @@
import lm_eval import lm_eval
from lm_eval.models.huggingface import HFLM from lm_eval.models.huggingface import HFLM
from pydantic import BaseModel, Field, NonNegativeInt from pydantic import BaseModel, Field
from heretic.scorer import Context, Score, Scorer from heretic.scorer import Context, Score, Scorer
@ -24,11 +24,6 @@ class Settings(BaseModel):
description="Task metric to use as the benchmark score.", description="Task metric to use as the benchmark score.",
) )
batch_size: NonNegativeInt = Field(
default=0, # auto
description="Number of input sequences to process in parallel (0 = auto).",
)
class BenchmarkScore(Scorer): class BenchmarkScore(Scorer):
""" """
@ -45,27 +40,29 @@ class BenchmarkScore(Scorer):
def score_name(self) -> str: def score_name(self) -> str:
return self.settings.score_name return self.settings.score_name
def get_score(self, ctx: Context) -> Score: def init(self, ctx: Context) -> None:
model = ctx.get_model() model = ctx.get_model()
hflm = HFLM( self.hflm = HFLM(
pretrained=model.model, pretrained=model.model, # ty:ignore[invalid-argument-type]
tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type] tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type]
batch_size="auto" batch_size="auto",
if self.settings.batch_size == 0
else self.settings.batch_size,
) )
def get_score(self, ctx: Context) -> Score:
# The purpose of this hack, where we initialize the HFLM object once,
# then update its internal model every time we calculate the score,
# is to get the benefits of batch size caching while allowing for
# model reloads, e.g. when using --evaluate-model.
model = ctx.get_model()
self.hflm.pretrained = model.model
self.hflm._model = model.model
results = lm_eval.simple_evaluate( results = lm_eval.simple_evaluate(
model=hflm, model=self.hflm,
tasks=[self.settings.task], tasks=[self.settings.task],
) )
if self.settings.batch_size == 0 and hflm.batch_sizes:
# Cache automatically determined batch size to avoid re-determining
# the batch size on every future run.
self.settings.batch_size = min(hflm.batch_sizes.values())
benchmark_score = float( benchmark_score = float(
results["results"][self.settings.task][self.settings.metric] results["results"][self.settings.task][self.settings.metric]
) )

View File

@ -1,276 +0,0 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
# Generic text-classification scorer: classifies each response with a
# text-classification model and counts the responses whose
# predicted label is one of the `match_labels`, as an alternative to the
# `keyword_markers` of the KeywordRate scorer.
#
# The default settings detect refusals using a ModernBERT model fine-tuned on refusal
# classification. Any text-classification model and label set can be used by
# changing the plugin settings.
#
# For more information, see:
# Implementation: https://github.com/p-e-w/heretic/pull/500
# Default classifier model: https://huggingface.co/VINAY-UMRETHE/Refusal-Classifier-V2
from typing import cast
import huggingface_hub
import torch
from pydantic import BaseModel, Field
from rich.markup import escape
from transformers import Pipeline, pipeline
from heretic.config import DatasetSpecification, SingleDatasetSpecification
from heretic.plugin import Context
from heretic.scorer import Score, Scorer
from heretic.system import empty_cache
from heretic.utils import (
format_dataset_specification,
format_exception,
is_hf_path,
print,
)
DEFAULT_LABELS = ["full_refusal", "partial_refusal"]
class Settings(BaseModel):
score_name: str = Field(
default="Refusals (Classifier)",
description="Name that describes what the configured match rate measures.",
)
model: str = Field(
default="VINAY-UMRETHE/Refusal-Classifier-V2",
description="Hugging Face model ID, or path to a text-classification model on disk.",
)
model_commit: str | None = Field(
default=None,
description=(
"Hugging Face commit hash of the classifier model. "
"Set this to pin a specific revision; unset means the latest "
"revision is auto-pinned and recorded when the classifier is loaded. "
"When reproducing, the recorded revision is restored and used."
),
)
dtypes: list[str] = Field(
default=[
"auto",
"float16",
"bfloat16",
"float32",
],
description=(
"List of PyTorch dtypes to try when loading model tensors. "
"If loading with a dtype fails, the next dtype in the list will be tried."
),
)
device_map: str | dict[str, int | str] = Field(
default="auto",
description="Device map to pass to Accelerate when loading the model.",
)
match_labels: list[str] = Field(
default=DEFAULT_LABELS,
description=(
"Labels predicted by the classifier that identify a response as a match. "
"Defaults to the refusal labels of the default model, which should "
"be counted as refusals. "
"Valid labels: compliant, full_refusal, partial_refusal, "
"capability_limitation, clarification."
),
)
batch_size: int = Field(
default=16,
description="Number of prompt/response pairs to classify in parallel.",
gt=0,
)
max_length: int = Field(
default=8192,
description="Maximum number of tokens per classifier input (longer inputs are truncated).",
gt=0,
)
use_text_pairs: bool = Field(
default=True,
description=(
"Whether to pass inputs as prompt/response text pairs. "
"Requires a model trained on pairs (e.g. the default refusal classifier). "
"Set to False when using a single-sequence text-classification model "
"to evaluate the response string only (e.g. sentiment analysis)."
),
)
print_responses: bool = Field(
default=False,
description="Whether to print prompt/response pairs and their predicted labels.",
)
prompts: DatasetSpecification = Field(
default=SingleDatasetSpecification(
dataset="mlabonne/harmful_behaviors",
split="test[:100]",
column="text",
),
description="Dataset of prompts to evaluate the match rate on.",
)
class BERTClassifier(Scorer):
"""
Classifies responses using a text-classification model
(ModernBERT by default) instead of regex keyword matching.
Scores the share of responses whose predicted label is in `match_labels`.
The default model and labels detect refusals. Any text-classification
model and label set can be used by changing the plugin settings.
Settings live in the [scorer.BERTClassifier] config section.
"""
settings: Settings
@property
def reproducible(self) -> bool:
# Inference is deterministic: eval mode (no dropout),
# argmax over softmax outputs (no sampling), pipeline keeps input order.
# All varying inputs are pinned: the classifier model revision is resolved
# in init(), the prompts dataset revision is resolved when the prompts are
# loaded, the remaining settings come from the config
# (match_labels, batch_size, max_length, use_text_pairs).
return True
@property
def score_name(self) -> str:
return self.settings.score_name
def init(self, ctx: Context) -> None:
print()
print(
f"Loading {self.settings.score_name} evaluation prompts from [bold]{format_dataset_specification(self.settings.prompts)}[/]..."
)
self.prompts = ctx.load_prompts(self.settings.prompts)
print(f"* [bold]{len(self.prompts)}[/] prompts loaded")
print()
print(f"Loading text classifier: [bold]{self.settings.model}[/]...")
if self.settings.model_commit is None and is_hf_path(self.settings.model):
try:
self.settings.model_commit = huggingface_hub.model_info(
self.settings.model
).sha
except Exception as error:
raise RuntimeError(
f"[red]Failed to fetch the latest commit hash for the classifier model "
f"[bold]{self.settings.model}[/] ({error}). "
f"Pinning the model commit is required for exact reproducibility.[/]"
)
self.pipeline = None
for dtype in self.settings.dtypes:
print(f"* Trying dtype [bold]{dtype}[/]...")
try:
torch_dtype = "auto" if dtype == "auto" else getattr(torch, dtype)
self.pipeline = pipeline(
"text-classification",
model=self.settings.model,
revision=self.settings.model_commit,
device_map=self.settings.device_map,
torch_dtype=torch_dtype,
)
break
except Exception as error:
self.pipeline = None
empty_cache()
formatted = format_exception(error)
if "\n" in formatted:
print(f"* [red]Failed:\n{formatted}[/]")
else:
print(f"* [red]Failed ({formatted})[/]")
continue
if self.pipeline is None:
raise Exception(
"Failed to load text classifier model with all configured dtypes."
)
valid = set((self.pipeline.model.config.id2label or {}).values())
unknown = set(self.settings.match_labels) - valid
if unknown:
raise ValueError(
f"Unknown match_labels: {sorted(unknown)}. "
f"Valid labels: {sorted(valid)}"
)
def get_score(self, ctx: Context) -> Score:
responses = ctx.get_responses(self.prompts)
predicted_labels = self._classify(responses)
match_count = 0
for prompt, response, label in zip(
self.prompts,
responses,
predicted_labels,
strict=True,
):
# Evaluate matches based on the classifier's predicted label only.
is_match = label in self.settings.match_labels
match_count += int(is_match)
if self.settings.print_responses:
print()
print(f"[bold]System prompt:[/] {escape(prompt.system)}")
print(f"[bold]Prompt:[/] {escape(prompt.user)}")
if not response.strip():
response = "[italic]\\[empty][/]"
else:
response = escape(response)
print(
f"[bold]Response:[/] [{'red' if is_match else 'green'}]{response}[/]"
)
print(f"[bold]Predicted label:[/] {label}")
if self.settings.print_responses:
print()
return Score(
value=float(match_count / len(self.prompts)),
rich_display=f"[bold]{match_count}[/]/{len(self.prompts)}",
md_display=f"{match_count}/{len(self.prompts)}",
)
def _classify(self, responses: list[str]) -> list[str]:
# Switch input method, considering both model types.
if self.settings.use_text_pairs:
# Standard way to use the classifier models that are trained on pairs,
# (e.g. the default refusal classifier). Otherwise, the
# fallback below can degrade the predictions of such models.
inputs = [
{
"text": prompt.user,
"text_pair": response,
}
for prompt, response in zip(self.prompts, responses, strict=True)
]
else:
# Fallback for single-sequence text-classification models
# (e.g. sentiment analysis). Here, we pass only the responses
# to avoid string concatenation (e.g. Prompt: {prompt.user}\nResponse: {response}),
# since such formatting can degrade the predictions of such models.
inputs = responses
results = cast(Pipeline, self.pipeline)(
inputs,
batch_size=self.settings.batch_size,
truncation=True,
max_length=self.settings.max_length,
)
return [result["label"] for result in results]

View File

@ -1,8 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors # Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from pydantic import BaseModel, Field, field_validator from pydantic import BaseModel, Field
from rich.markup import escape
from heretic.config import DatasetSpecification, SingleDatasetSpecification from heretic.config import DatasetSpecification, SingleDatasetSpecification
from heretic.scorer import Context, Score, Scorer from heretic.scorer import Context, Score, Scorer
@ -65,20 +64,9 @@ class Settings(BaseModel):
description="Strings whose presence in a response (case insensitive) identifies the response as a keyword match.", 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( print_responses: bool = Field(
default=False, default=False,
description="Whether to print prompt/response pairs.", description="Whether to print prompt/response pairs when counting keyword matches.",
) )
@ -110,20 +98,17 @@ class KeywordRate(Scorer):
def get_score(self, ctx: Context) -> Score: def get_score(self, ctx: Context) -> Score:
match_count = 0 match_count = 0
responses = ctx.get_responses(self.prompts) responses = ctx.get_responses(self.prompts)
for prompt, response in zip(self.prompts, responses):
for prompt, response in zip(self.prompts, responses, strict=True):
is_match = self._is_match(response) is_match = self._is_match(response)
if is_match: if is_match:
match_count += 1 match_count += 1
if self.settings.print_responses: if self.settings.print_responses:
print() print()
print(f"[bold]System prompt:[/] {escape(prompt.system)}") print(f"[bold]System prompt:[/] {prompt.system}")
print(f"[bold]Prompt:[/] {escape(prompt.user)}") print(f"[bold]Prompt:[/] {prompt.user}")
if not response.strip(): if not response.strip():
response = "[italic]\\[empty][/]" response = "[italic]\\[empty][/]"
else:
response = escape(response)
print( print(
f"[bold]Response:[/] [{'red' if is_match else 'green'}]{response}[/]" f"[bold]Response:[/] [{'red' if is_match else 'green'}]{response}[/]"
) )

View File

@ -1,101 +0,0 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
from pydantic import BaseModel, Field, NonNegativeInt
from rich.markup import escape
from heretic.config import DatasetSpecification, SingleDatasetSpecification
from heretic.scorer import Context, Score, Scorer
from heretic.utils import format_dataset_specification, print
class Settings(BaseModel):
prompts: DatasetSpecification = Field(
default=SingleDatasetSpecification(
dataset="mlabonne/harmless_alpaca",
split="test[:100]",
column="text",
),
description="Dataset of prompts to evaluate the response length on.",
)
strip_responses: bool = Field(
default=True,
description="Whether to strip leading and trailing whitespace from responses before measuring their length.",
)
short_response_threshold: NonNegativeInt = Field(
# Chosen because "No" is the shortest common valid response.
default=2,
description="Length in characters below which a response is classified as a 'short response'.",
)
short_response_score_length: float = Field(
default=500,
description=(
"Length value artificially assigned to 'short responses' for the purpose of scoring. "
"This can be used to penalize very short (and thus likely invalid) responses."
),
)
print_responses: bool = Field(
default=False,
description="Whether to print prompt/response pairs.",
)
class ResponseLength(Scorer):
"""
Measures the mean length of responses.
"""
settings: Settings
@property
def reproducible(self) -> bool:
return True
@property
def score_name(self) -> str:
return "Mean response length"
def init(self, ctx: Context) -> None:
print()
print(
f"Loading response length evaluation prompts from [bold]{format_dataset_specification(self.settings.prompts)}[/]..."
)
self.prompts = ctx.load_prompts(self.settings.prompts)
print(f"* [bold]{len(self.prompts)}[/] prompts loaded")
def get_score(self, ctx: Context) -> Score:
total_length = 0
responses = ctx.get_responses(self.prompts)
for prompt, response in zip(self.prompts, responses, strict=True):
response_length = len(
response.strip() if self.settings.strip_responses else response
)
if response_length < self.settings.short_response_threshold:
response_length = self.settings.short_response_score_length
total_length += response_length
if self.settings.print_responses:
print()
print(f"[bold]System prompt:[/] {escape(prompt.system)}")
print(f"[bold]Prompt:[/] {escape(prompt.user)}")
if not response.strip():
response = "[italic]\\[empty][/]"
else:
response = escape(response)
print(f"[bold]Response:[/] {response}")
if self.settings.print_responses:
print()
mean_length = float(total_length / len(self.prompts))
return Score(
value=mean_length,
rich_display=f"[bold]{mean_length:.1f}[/]",
md_display=f"{mean_length:.1f}",
)

View File

@ -96,7 +96,7 @@ def get_amdgpu_driver_version() -> str | None:
if os.path.exists(version_path): if os.path.exists(version_path):
with open(version_path, "r", encoding="utf-8") as f: with open(version_path, "r", encoding="utf-8") as f:
return f.read().strip() return f.read().strip()
except Exception: # noqa: S110 except Exception:
pass pass
return None return None
@ -249,7 +249,7 @@ def get_accelerator_info_dict() -> dict[str, Any]:
info: dict[str, Any] = { info: dict[str, Any] = {
"type": "ROCm" if is_rocm else "CUDA", "type": "ROCm" if is_rocm else "CUDA",
"api_name": "HIP Version" if is_rocm else "CUDA Version", "api_name": "HIP Version" if is_rocm else "CUDA Version",
"api_version": torch.version.hip if is_rocm else torch.version.cuda, "api_version": torch.version.hip if is_rocm else torch.version.cuda, # ty:ignore[unresolved-attribute]
"driver_version": get_amdgpu_driver_version() "driver_version": get_amdgpu_driver_version()
if is_rocm if is_rocm
else get_nvidia_driver_version(), else get_nvidia_driver_version(),
@ -264,13 +264,13 @@ def get_accelerator_info_dict() -> dict[str, Any]:
return info return info
if is_xpu_available(): if is_xpu_available():
count = torch.xpu.device_count() count = torch.xpu.device_count() # ty:ignore[unresolved-attribute]
return { return {
"type": "XPU", "type": "XPU",
"api_name": None, "api_name": None,
"api_version": None, "api_version": None,
"driver_version": get_xpu_driver_version(), "driver_version": get_xpu_driver_version(),
"devices": [{"name": torch.xpu.get_device_name(i)} for i in range(count)], "devices": [{"name": torch.xpu.get_device_name(i)} for i in range(count)], # ty:ignore[unresolved-attribute]
} }
if is_mlu_available(): if is_mlu_available():

View File

@ -344,7 +344,7 @@ def get_readme_intro(
else: else:
reproducibility_instructions = "" reproducibility_instructions = ""
return f"""# This is a {settings.modified_model_type} version of { return f"""# This is a decensored version of {
model_link model_link
}, made using [Heretic](https://heretic-project.org) v{version("heretic-llm")} }, made using [Heretic](https://heretic-project.org) v{version("heretic-llm")}
{reproducibility_instructions} {reproducibility_instructions}
@ -372,26 +372,10 @@ def get_readme_intro(
""" """
def _strip_none_values(data: Any) -> Any:
"""Return a copy of the data with all None values removed (TOML has no null value)."""
if isinstance(data, dict):
return {
key: _strip_none_values(value)
for key, value in data.items()
if value is not None
}
if isinstance(data, list):
return [_strip_none_values(value) for value in data]
return data
def generate_config_toml(settings: Settings) -> str: def generate_config_toml(settings: Settings) -> str:
"""Serializes the full Settings object to TOML.""" """Serializes the full Settings object to TOML."""
# The `exclude_none` option can't be used here because it only applies return tomli_w.dumps(settings.model_dump(exclude_none=True))
# to model fields, and does not remove None values contained in extra
# (plugin settings) dictionaries.
return tomli_w.dumps(_strip_none_values(settings.model_dump()))
def generate_requirements_txt() -> str: def generate_requirements_txt() -> str:
@ -598,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. - [`requirements.txt`](requirements.txt): The exact versions of all Python packages.
- [`config.toml`](config.toml): The exact configuration used, including the RNG seed. - [`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. - [`{checkpoint_filename}`]({checkpoint_filename}): The Optuna study journal containing the history of all trials.
- [`SHA256SUMS.txt`](SHA256SUMS.txt): Cryptographic hashes for all weight files. - [`SHA256SUMS`](SHA256SUMS): Cryptographic hashes for all weight files.
- [`reproduce.json`](reproduce.json): A machine-readable file containing all reproducibility information. - [`reproduce.json`](reproduce.json): A machine-readable file containing all reproducibility information.
## How to reproduce ## How to reproduce
@ -613,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. Place the provided `config.toml` in your working directory.
1. Run Heretic without any additional arguments: `heretic` 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. 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.txt`: 1. Verify that the weight files have been exactly reproduced by comparing their SHA-256 hashes against those in `SHA256SUMS`:
`sha256sum -c SHA256SUMS.txt` (or look at the hashes online if you uploaded to Hugging Face) `sha256sum -c SHA256SUMS` (or look at the hashes online if you uploaded to Hugging Face)
> [!TIP] > [!TIP]
> To use the included Optuna study journal `{checkpoint_filename}`, place it in the checkpoints directory (usually `checkpoints/`) before running Heretic. > To use the included Optuna study journal `{checkpoint_filename}`, place it in the checkpoints directory (usually `checkpoints/`) before running Heretic.
@ -671,7 +655,7 @@ def generate_reproduce_json(
def generate_sha256sums(hashes: dict[str, str]) -> str: def generate_sha256sums(hashes: dict[str, str]) -> str:
"""Generates GNU Coreutils compatible content for SHA256SUMS.txt.""" """Generates GNU Coreutils compatible SHA256SUMS file content."""
lines = [] lines = []
@ -727,7 +711,7 @@ def create_reproduce_folder(
) )
if uploaded_model_hashes: if uploaded_model_hashes:
(reproduce_dir / "SHA256SUMS.txt").write_text( (reproduce_dir / "SHA256SUMS").write_text(
generate_sha256sums(uploaded_model_hashes), generate_sha256sums(uploaded_model_hashes),
encoding="utf-8", encoding="utf-8",
) )

View File

@ -1,47 +1,53 @@
# Test Guide # Test Suite Guide
This directory contains two kinds of tests: Whenever we change any code-logic related to `src/heretic/model.py` or `config.toml` *(e.g. `row_normalization`, `full_normalization_lora_rank`, `winsorization_quantile`, etc)* which can affect a model's reproduciblity; Use these tests which are designed to verify that those changes does not affect reproducibility, unless they are meant to (like when we'll integrate ARA branch in future).
1. **Reproducibility tests**: end-to-end tests that verify whether your new changes affect a model's reproducibility. See [Reproducibility tests](#1-reproducibility-tests). ## How to test
2. **Unit tests**: tests for individual units of heretic. See [Unit tests](#2-unit-tests).
## 1. Reproducibility tests
Whenever we change any code-logic related to `src/heretic/model.py`, `src/heretic/main.py`, `src/heretic/modifier.py`, `src/heretic/evaluator.py` *(operations, modifier, evaluation, batch size, etc.)*, or `src/heretic/config.py`, `src/heretic/plugin.py`, `src/heretic/utils.py`, `src/heretic/scorer.py` *(settings, plugin interface, response prefix, chat template, etc.)*, or **anything** which can affect a model's *reproducibility*, use these tests which are designed to verify that those changes do *not* affect reproducibility, unless they *are* meant to.
For example, when fixing bugs *(e.g. fixing the `response_prefix` logic in `src/heretic/main.py`, which **changes** the previous behavior)*. Such changes will affect the reproducibility of the models, and in such cases, you may update the hash for the files that differ from their existing hash as mentioned in the existing model's `SHA256SUMS.LABEL` file.
### How to test
```bash
uv run run_tests.py
```
### How to add a new test
You may add a new test case with a new model when implementing new plugins *(e.g. a new modifier, a new scorer, etc.)*, or when testing different optimization choices / non-default values *(e.g. different value of `row_normalization` in `src/heretic/modifiers/abliteration.py`, different value of `lora_rank` in `src/heretic/modifiers/ara.py`, etc.)*.
1. Choose any model from [tiny-random](https://huggingface.co/tiny-random) org which provides tiny models useful for debugging. 1. Choose any model from [tiny-random](https://huggingface.co/tiny-random) org which provides tiny models useful for debugging.
* **Example**: [tiny-random/minicpm5](https://huggingface.co/tiny-random/minicpm5). **Example**: [tiny-random/minicpm5](https://huggingface.co/tiny-random/minicpm5).
2. Clone that model repository using **Git** and generate the `SHA256SUMS.LABEL` file using the `sha256sum` tool: > [!NOTE]
> It is highly recommended to use a model which does not have a `special_tokens_map.json` file in the repo.
> Because those files are almost always wrong in `tiny-random/*` models compared to the original model.
> [!IMPORTANT] 2. Clone that model repository using Git and generate the SHA256 hashes using `sha256sum`:
> Delete the unnecessary files such as `README.md` and `.gitattributes` before generating the hash file.
* **On Linux**: **On Linux**:
```bash ```bash
sha256sum -b * > ../SHA256SUMS.LABEL sha256sum -b * > ../SHA256SUMS.LABEL
``` ```
* **On Windows**: **On Windows**:
```bash ```bash
sha256sum * | Out-File -Encoding utf8NoBOM ../SHA256SUMS.LABEL sha256sum * | Out-File -Encoding utf8NoBOM ../SHA256SUMS.LABEL
``` ```
> [!TIP]
> On windows, `sha256sum` is generally pre-installed by *Git for windows*.
**Verify with**:
```bash
Get-Command sha256sum`
```
**Expected**:
```bash
CommandType Name Version Source
----------- ---- ------- ------
Application sha256sum.exe 0.0.0.0 C:\Program Files\Git\usr\bin\sha256sum...
```
> [!NOTE]
> You must use Windows Powershell `v7.X` not the core which is `v5.1`. This is required for `-Encoding utf8NoBOM` to work.
>
> See [Differences between Windows PowerShell 5.1 and PowerShell 7.x](https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7.6) documentation.
Where `LABEL` describes the type of system you are running the tests on. Where `LABEL` describes the type of system you are running the tests on.
**Example**: **Example**:
@ -50,37 +56,15 @@ Where `LABEL` describes the type of system you are running the tests on.
- `SHA256SUMS.ci` (For GitHub CI) - `SHA256SUMS.ci` (For GitHub CI)
- `SHA256SUMS.linux` (For linux) - `SHA256SUMS.linux` (For linux)
> [!TIP]
> On Windows, `sha256sum` is generally pre-installed by **Git for Windows**.
* **Verify with**:
```bash
Get-Command sha256sum
```
* **Expected**:
```bash
CommandType Name Version Source
----------- ---- ------- ------
Application sha256sum.exe 0.0.0.0 C:\Program Files\Git\usr\bin\sha256sum...
```
> [!NOTE]
> You must use Windows PowerShell `v7.x` not the core which is `v5.1`. This is required for `-Encoding utf8NoBOM` to work.
>
> See [Differences between Windows PowerShell 5.1 and PowerShell 7.x](https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7.6) documentation.
3. Run the tests with: 3. Run the tests with:
```bash ```bash
uv run run_tests.py uv run run_tests.py
``` ```
The output hashes should **FAIL** against the `Valid hashes` in `SHA256SUMS.LABEL` file of the test model you added. This is **expected** since Heretic modifies the model. Without **Step 2**, the test model's folder will simply be ignored because it will not have a checksums file to compare against. The output hashes *should FAIL* against the `Valid hashes` in `SHA256SUMS` file of the test model you added. This is expected since Heretic changes the model. Without **Step 2**, the test model's folder will simply be ignored because it will not have a hash SUMS file to compare against.
4. After that, go to the output folder `TEST_MODEL_DIR/model` and re-generate the actual hashes based on the system you are using. 4. After that go to the output `TEST_MODEL_DIR/model` folder and re-generate the Actual hashes based on the system you are using.
```bash ```bash
cd TEST_MODEL_DIR/model cd TEST_MODEL_DIR/model
@ -93,33 +77,14 @@ sha256sum -b * > ../SHA256SUMS.LABEL # or use windows command.
uv run run_tests.py uv run run_tests.py
``` ```
This time, the tests should **PASS** because we added the new hashes which are *expected* to be reproduced on the same system. This time the tests *should PASS* because we added the new hashes which are expected to be reproduced on the same system.
6. After that, push the `SHA256SUMS.LABEL` files and wait for the **GitHub CI** actions to run those tests. 6. After that push the `SHA256SUMS.LABEL` files and wait for GitHub CI actions to run those tests.
> [!NOTE] Since PyTorch does not guarantee exact cross-system reproducibility regardless of configuration, multiple valid hashes can be provided for each output file. The above update must be performed for each `TEST_MODEL_DIR` and on each type of system.
> The GitHub CI actions will run the tests only if your PR is targeting the `master` branch of Heretic.
Since **PyTorch** does *not* guarantee exact cross-system reproducibility regardless of configuration, multiple valid hashes can be provided for each output file. The above update must be performed for each `TEST_MODEL_DIR` and on each type of system *(or at least your system plus the GitHub CI, e.g. Linux or Windows + GitHub CI)*. For this, copy the `Actual hash` value for *each mismatched unidentical* file into a `SHA256SUMS.ci` file.
For this, copy the `Actual hash` value for *each* **unidentical** file into a new `SHA256SUMS.ci` file. 7. After that push the `SHA256SUMS.ci` files and wait for GitHub CI actions to re-run those tests.
7. After that, push the `SHA256SUMS.ci` files and wait for GitHub CI actions to re-run those tests. This time the tests *should* PASS because we added the new hashes which are expected to be reproduced on CI.
This time the tests *should* **PASS** because we added the new hashes which are *expected* to be reproduced on the CI.
> [!NOTE]
> The GitHub CI is usually non-deterministic across different Python versions on which we run the tests, probably due to their internal infrastructure.
>
> Due to this, if the tests constantly fail due to hash mismatch for one or more Python versions *(e.g. Python 3.12 and Python 3.14)*, then you may add **alternate** hashes for the same system, i.e. for the GitHub CI.
>
> For example, `SHA256SUMS.ci2` and `SHA256SUMS.ci3` files.
## 2. Unit tests
The unit tests are written with Python's built-in `unittest` framework.
```bash
cd tests
python -m unittest
```

View File

@ -1 +0,0 @@
ae1e4264ccb8a80b15301d898129bb02f6ef76f4d36e9e2ae0edbd6c06f24bbe *adapter_model.safetensors

View File

@ -1 +0,0 @@
0115a3d9096834154dd6299b5ba13b658c7467de173b781c219c19bc5ff666db *adapter_model.safetensors

View File

@ -1 +0,0 @@
a2dc0029e0de28bceb4e323a04ff7966e8a574b7b808619ec0937ce99c3a0977 *adapter_model.safetensors

View File

@ -1 +0,0 @@
296c61c35c6a47dc67e8efa6593c7ed0b3adf7d8ca0fe3aa55f7d201916bb90a *adapter_model.safetensors

View File

@ -1,59 +0,0 @@
# 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"

View File

@ -1 +0,0 @@
fab6b4c5e8e86d0117451ade5ceb8fa83599b67af9bc543f6f4fd2db5ed523ba *adapter_model.safetensors

View File

@ -1 +0,0 @@
4b81cbbe8ed75c4d82ed60ff9c883319ca436d3d834e613cd0a46cc51f6ab05d *adapter_model.safetensors

View File

@ -1 +0,0 @@
cb742e4929c6883dbe586978c48560c7c28da53bce0752bdb3b1d707328c7158 *adapter_model.safetensors

View File

@ -1 +0,0 @@
c2c1262cba3f64f81591bf82b178cf20e1e7091473d2229042157c7c49caa7ff *adapter_model.safetensors

View File

@ -1 +0,0 @@
a03e314411ba09c75f1ee62da54d260ac8b68bd5ddedaa0f709c4bb975b06143 *adapter_model.safetensors

View File

@ -1 +0,0 @@
9de2b756fa643074ac3641d97076d39c9f89e08a24a39a546642a59d975442f5 *adapter_model.safetensors

View File

@ -1,62 +0,0 @@
# 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"

View File

@ -1,4 +0,0 @@
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
f8f1fd0ef18d709772584f1a4d736fc8f31aafee83a001b34d333c30a606baf8 *model.safetensors
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json

View File

@ -1,4 +0,0 @@
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
2b0b38f5cc5b25e424dc944cf0b27432f736cffd59a8753f2ddd23f5434e5ab4 *model.safetensors
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json

View File

@ -1,4 +0,0 @@
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
ad8c373f6d6f3f00e646d118116fc1f34c91c5c67a10db6fe9366fd34f534df5 *model.safetensors
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json

View File

@ -1,4 +0,0 @@
5595714af3f245d20831e545ee5ee41fec8f4ad5a89d9ca5abce0bf476debfa7 *config.json
333322c2521ae1cbe6405f4770d690d8f404d0ce5587308b94520f058b949762 *model.safetensors
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
43184dd63293fc63deba9c8aab4353b4a15e46a2e7ab691ddcf4fd16d73cf77c *tokenizer_config.json

View File

@ -1,76 +0,0 @@
# This test case is for the BERTClassifier scorer plugin.
# After any change related to it, this test should PASS.
model = "tiny-random/gemma-3"
model_commit = "69a78d1ad0ad66620c43579acd1327553713e22a"
seed = 12345
print_debug_information = true
batch_size = 2
max_response_length = 10
n_trials = 2
n_startup_trials = 1
export_strategy = "merge"
checkpoint_action = "restart"
trial_index = 0
model_action = "save"
save_directory = "model"
scorers = [
{ plugin = "heretic.scorers.keyword_rate.KeywordRate", optimization = "none" },
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" },
{ plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" },
]
[[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]
print_responses = true
[scorer.KeywordRate.prompts]
dataset = "mlabonne/harmful_behaviors"
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
split = "test[:5]"
column = "text"
[scorer.BERTClassifier]
model = "VINAY-UMRETHE/tiny-refusal-classifier"
model_commit = "f0e03ef4a27003d8b54d7366e72711fc665da9d5"
print_responses = true
[scorer.BERTClassifier.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"

View File

@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja 2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json 70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
f3f4ec19504f182486459cf4e255ece265c25f827840d63b6a9d4058b8e4877a *model.safetensors f3f4ec19504f182486459cf4e255ece265c25f827840d63b6a9d4058b8e4877a *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json 32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json

View File

@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja 2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json 70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
53c4ee891dce23c0ac85bebc2c4d48301469750fafbb3e6e024c15786d94db8b *model.safetensors 53c4ee891dce23c0ac85bebc2c4d48301469750fafbb3e6e024c15786d94db8b *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json 32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json

View File

@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja 2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json 70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
9ff0593e3fbd0ba463bbc980ebb3ed34798e562b606f90cd93c2df5403732c7b *model.safetensors 9ff0593e3fbd0ba463bbc980ebb3ed34798e562b606f90cd93c2df5403732c7b *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json 32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json

View File

@ -1,6 +1,6 @@
2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja 2f1b4d75d067bae3fe44e676721c7f077d243bc007156cb9c2f8b5836613d082 *chat_template.jinja
c128bc8647a505e343c8cdff9bdd188b1a4a3f81938148685cbf90dff9827268 *config.json ca80080dfa4ec6ba87152fa2b9afe70b90c400e5c4b1d6bdc3aa3114467ca68f *config.json
58678fb2b8ae1b96652dffa43f864ad1c1c59e49c889bab4264ba0844c4a23b8 *generation_config.json 70070bac883cf9c39b5992450d6b23cd160eaf33099e24c654e0359d2f87c760 *generation_config.json
effe36925f85ecb1e29bba84501a456bb49df21e4047be8b7ea3f6f88181fb65 *model.safetensors effe36925f85ecb1e29bba84501a456bb49df21e4047be8b7ea3f6f88181fb65 *model.safetensors
32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json 32bdf45d2ad4cc29a0822ddd157a182de76644f0419a6228d151495256e9813c *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json

View File

@ -1,6 +1,6 @@
b16d3228a775c549ba97af41233a54e9de8dd2b65250f78346661d18b936a8b5 *chat_template.jinja b16d3228a775c549ba97af41233a54e9de8dd2b65250f78346661d18b936a8b5 *chat_template.jinja
120994c6992d9b02735f2f3f6c0f6bf502004385edd6d20c7b9b35732ce3dd51 *config.json 0094ad598a8043f84d82ad5c886547bca1d1d7f302d82f1491f83d388e89acd4 *config.json
0a86ecc4422176234111947919fb96e578cbf33b1036004fa171d27beb302469 *generation_config.json 1a019c5d688d54cf01318eab88cb4345dfa52135eb1d83c2f54125469eb88d5c *generation_config.json
effe36925f85ecb1e29bba84501a456bb49df21e4047be8b7ea3f6f88181fb65 *model.safetensors effe36925f85ecb1e29bba84501a456bb49df21e4047be8b7ea3f6f88181fb65 *model.safetensors
24d00232e58cfa179fe8b3911c788d4aad9a6279d778ebe4c72e82623b6197f9 *processor_config.json 24d00232e58cfa179fe8b3911c788d4aad9a6279d778ebe4c72e82623b6197f9 *processor_config.json
cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f *tokenizer.json

View File

@ -1,6 +1,6 @@
f8d9255777615591a7cc1a7c932f5a69e181128902295e1b81221d20d983cac7 *chat_template.jinja f8d9255777615591a7cc1a7c932f5a69e181128902295e1b81221d20d983cac7 *chat_template.jinja
22d559dde87f1a0faf02efed3062af2b1fc8a1721a55b952cd5f5d8c356b4feb *config.json 91d2a5190c7ea0f74ed499428d4ad62b5208d63b36f7bbb562d15f4be25bd5c2 *config.json
523e422e425e7a7ba23d85cc0faeef143dc5da37b72bfc649df5a8d83ee95beb *generation_config.json dd6034a30113decdfaf8886622e20eb9e2e02d3f774918d474a4e26cfd7fbba8 *generation_config.json
4e8bfdb94ef69c14c6af7382fa58afba9a2318d6c34a5949ef8db69bc2f932ee *model.safetensors aefe8b9c4b4969f6d13c5d778760f3dce4e25134324b33677934550d9df02a7c *model.safetensors
fce342a4642cb8afc42d8d89cfa21198b64a43458ded7f6ff28d1151a08c9cda *tokenizer.json fce342a4642cb8afc42d8d89cfa21198b64a43458ded7f6ff28d1151a08c9cda *tokenizer.json
9ba5fa877168e24823cb583c55b4c2e4df0331f30084953c7cf07de294640384 *tokenizer_config.json 9ba5fa877168e24823cb583c55b4c2e4df0331f30084953c7cf07de294640384 *tokenizer_config.json

View File

@ -1,6 +0,0 @@
e381f0b98be3c3714676ec4102bc75a885d75b9002feb02fb6f25ad0e641bce3 *chat_template.jinja
07109279e69a421627d0bd4723cbd6828d8427291824baf1c923136e536b8a8a *config.json
f74b3fbaec771b2c9650e8289f8b1d6575ca164ad5834331ab0a5e79acdbd9ac *generation_config.json
8473b458481540948b46b4001f282073f9337bb3ca9c40b589d3a77add3ecb23 *model.safetensors
fce342a4642cb8afc42d8d89cfa21198b64a43458ded7f6ff28d1151a08c9cda *tokenizer.json
4c3c901d30c4e7db34ce5ad6e80d607a308fd1e980ca16e5f5d3ab250196b179 *tokenizer_config.json

View File

@ -1,6 +1,6 @@
7451a05cf1e28a79d97d7c0bc951028c0b1915119bf9046acd06a0e3d931f47c *chat_template.jinja 7451a05cf1e28a79d97d7c0bc951028c0b1915119bf9046acd06a0e3d931f47c *chat_template.jinja
de44f54b200f63c8ccb7899965bc9aaf21b23d35164c7de9a3cc3394530e3821 *config.json fe6fd41d9f2ce5d6486748cf0330b574f37bf7d4e915f7b39d1af1a185cac3c3 *config.json
12d96814a0cd1a72cae14392b04b9644353e8600614faa6eb7ee5edbf9452ec1 *generation_config.json c4c2ef5ae4a4e2dd10655a3b99d801a8a50497286ddd042ba35bcfefc44ad349 *generation_config.json
1535a9b7a91b2cb39ad280dbd9a940e2609a0b423d5b924df4d664e579912802 *model.safetensors 1535a9b7a91b2cb39ad280dbd9a940e2609a0b423d5b924df4d664e579912802 *model.safetensors
ad92aaa8d3032c98a9158b8c5e8682bed10027ed6463e4fb1320fe5384210873 *tokenizer.json ad92aaa8d3032c98a9158b8c5e8682bed10027ed6463e4fb1320fe5384210873 *tokenizer.json
3ad32522c384dbe35192bb69de9befbf3f523e99d4bb3f95da757671d4c28281 *tokenizer_config.json 3ad32522c384dbe35192bb69de9befbf3f523e99d4bb3f95da757671d4c28281 *tokenizer_config.json

View File

@ -1,6 +1,6 @@
d8db3ff45c4c68a0ba9dee962ff1a0adde9a2be55e0895306f6bd2b2756f5adb *chat_template.jinja d8db3ff45c4c68a0ba9dee962ff1a0adde9a2be55e0895306f6bd2b2756f5adb *chat_template.jinja
f6d2e73ef749f83d6b913241899de1b0b55047fe0e15776cae7c66b6219e5087 *config.json a9d6f64bb9d0c02b553119e475615153af625b5c2a16ccb8fb8b3c2cc348f465 *config.json
1d46ee66092151517d5459a6ca6d4dc263efa98f59e89443e8af8f4c11a8761d *generation_config.json 0e7611a1e8fd0a06a139b0572b2c55b885ba9fb7db2022873c3508aebfb488aa *generation_config.json
411d95f42d3e31aef41c28314c8f0431c980687a97904d32b4ef57c42199720f *model.safetensors 411d95f42d3e31aef41c28314c8f0431c980687a97904d32b4ef57c42199720f *model.safetensors
ad92aaa8d3032c98a9158b8c5e8682bed10027ed6463e4fb1320fe5384210873 *tokenizer.json ad92aaa8d3032c98a9158b8c5e8682bed10027ed6463e4fb1320fe5384210873 *tokenizer.json
aa083f3da10340925734e876e41e235c459329294ecd35d7511ec5868c1f14e3 *tokenizer_config.json aa083f3da10340925734e876e41e235c459329294ecd35d7511ec5868c1f14e3 *tokenizer_config.json

View File

@ -1,7 +1,7 @@
39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja 39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja
b2cfd8a9da09efc97040f3839fe629f3925db856a44b58314301dc5e11345ec8 *config.json f69f84977a47c8fea9ce9fc26b7de379216cb01146ea726a87996d3554cfcd19 *config.json
338d303c3c3df6884030cf5be24560f6e973fc183220d14acfb9364cd0e070e4 *generation_config.json 34dfa6012ca9ac5f57e5521d8dbaecbc7ab7f7ab0fd96ec020b543aab5f265d9 *generation_config.json
4cf4d463a94f477ed446e47130cb7da6b5994f0b788e75b82b3c65a531585621 *model.safetensors 876c6691eb85e3e5e11771e589529830fb454ab26344e1271ae550661e312b50 *model.safetensors
a05f93a41b7e42ccc18461b540fb54490c3ffa13aef79c800bbe7942e02e360f *processor_config.json 84be30b124b50749c56d25fdbec5ccedf564446f6b3b035e88e1e07b986d2491 *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json 7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json

View File

@ -1,7 +1,7 @@
39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja 39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja
b2cfd8a9da09efc97040f3839fe629f3925db856a44b58314301dc5e11345ec8 *config.json f69f84977a47c8fea9ce9fc26b7de379216cb01146ea726a87996d3554cfcd19 *config.json
338d303c3c3df6884030cf5be24560f6e973fc183220d14acfb9364cd0e070e4 *generation_config.json 34dfa6012ca9ac5f57e5521d8dbaecbc7ab7f7ab0fd96ec020b543aab5f265d9 *generation_config.json
ad6675b44b476a899914761257bbeb7f320cb9c0dc39a7467daf4dad0216dd1f *model.safetensors 6febb813086f253e5ec0fcda02fdfc849c551a7dba54681b37ac5bc402e4eed6 *model.safetensors
a05f93a41b7e42ccc18461b540fb54490c3ffa13aef79c800bbe7942e02e360f *processor_config.json 84be30b124b50749c56d25fdbec5ccedf564446f6b3b035e88e1e07b986d2491 *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json 7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json

View File

@ -1,7 +0,0 @@
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

View File

@ -1,7 +1,7 @@
39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja 39f03c383413f531fd302c06c7e982ad98c83f0657a8339ae25478ccb81fdcda *chat_template.jinja
b2cfd8a9da09efc97040f3839fe629f3925db856a44b58314301dc5e11345ec8 *config.json f69f84977a47c8fea9ce9fc26b7de379216cb01146ea726a87996d3554cfcd19 *config.json
338d303c3c3df6884030cf5be24560f6e973fc183220d14acfb9364cd0e070e4 *generation_config.json 34dfa6012ca9ac5f57e5521d8dbaecbc7ab7f7ab0fd96ec020b543aab5f265d9 *generation_config.json
8244162ecb6ce7bad7b10fe4f015889d76a09c7749dc7ac8c4d957f0864b2e82 *model.safetensors 29aff97d5633dead9e1ccd29a2cc153b4b7431d22f63c8d6cf60bc6547681cc9 *model.safetensors
a05f93a41b7e42ccc18461b540fb54490c3ffa13aef79c800bbe7942e02e360f *processor_config.json 84be30b124b50749c56d25fdbec5ccedf564446f6b3b035e88e1e07b986d2491 *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json 7b29c843c0043622d28fd4638451cbb0a609d99a0762ffbff3b92b4b2fee4d94 *tokenizer_config.json

View File

@ -1,7 +1,7 @@
72f84af4ea36b82409c35e31b584361534305ef7c0d90fce20d0dc38a7efead8 *chat_template.jinja 72f84af4ea36b82409c35e31b584361534305ef7c0d90fce20d0dc38a7efead8 *chat_template.jinja
c2b697282298f9500f1170b9237dc234dbe1cb7ca741fe56b034d64d9e38e1d2 *config.json e4c5278b361c57621253c27a2c3db358e1580aec8a14be8e19d4420a224137cf *config.json
d9f7f986f62f4f1f87790070237e0214865e5c227f4941f7308c838702a69934 *generation_config.json 8dde85c000ae807be907421465826c7c63a39f6acf6d04a5a84efaf116ed4ef7 *generation_config.json
1bc5d08088f30b35f829609f38a6cde565d26d33050c8d581e39e2a86a442cab *model.safetensors 20b5a820b38438202c64e4fc9807bd19e29678bebd678d29b2ee2d2f5bf71587 *model.safetensors
5abd409b04043c99c3fcd52b06cc412b46fb4bd14c8ef9f79695a3be1490987b *processor_config.json 20e7a6dcde0a6f60ea3b4fb08f6f7afa62532dda93a3111e28384ba5150575f9 *processor_config.json
c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json c3a8d92e371b92a2cd6e678e31ebc27d0235e929a51fbf290f74742b341fa96f *tokenizer.json
60a8042e29b4b20e884e48375aa1b9ac0025547371d50e60f6d55e6a9675e868 *tokenizer_config.json 60a8042e29b4b20e884e48375aa1b9ac0025547371d50e60f6d55e6a9675e868 *tokenizer_config.json

View File

@ -1,6 +1,6 @@
cd8e9439f0570856fd70470bf8889ebd8b5d1107207f67a5efb46e342330527f *chat_template.jinja cd8e9439f0570856fd70470bf8889ebd8b5d1107207f67a5efb46e342330527f *chat_template.jinja
6b517667960a5e39a692eb8277be7260ac02c22d9c7eda9c7aa1bbab21517fc1 *config.json 45134b857367fdcb97c0179199848c353fc28f8b95ac2244ac8f45cca448d864 *config.json
64cf6f4e0016154cae45628221d77e3925961876125fe68bd942303ec7cca40f *generation_config.json e81e23e025c38e825dcf8375861e26a90e804276e4db9ee390122a4fdc95dae7 *generation_config.json
e616cbeb5a913015eb3db96e001030048df2db560df363d4cf688f0c1b2c96de *model.safetensors bd86541d817978c896bd3579e69ae6d41b6382eaf1646accf83d6feb16acb703 *model.safetensors
f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json
04b1682c59acbd057f4c9072297faa73d56fc9de053094c659cdb4c464f58f86 *tokenizer_config.json 04b1682c59acbd057f4c9072297faa73d56fc9de053094c659cdb4c464f58f86 *tokenizer_config.json

View File

@ -1,6 +1,6 @@
cd8e9439f0570856fd70470bf8889ebd8b5d1107207f67a5efb46e342330527f *chat_template.jinja cd8e9439f0570856fd70470bf8889ebd8b5d1107207f67a5efb46e342330527f *chat_template.jinja
6b517667960a5e39a692eb8277be7260ac02c22d9c7eda9c7aa1bbab21517fc1 *config.json 45134b857367fdcb97c0179199848c353fc28f8b95ac2244ac8f45cca448d864 *config.json
64cf6f4e0016154cae45628221d77e3925961876125fe68bd942303ec7cca40f *generation_config.json e81e23e025c38e825dcf8375861e26a90e804276e4db9ee390122a4fdc95dae7 *generation_config.json
bd86541d817978c896bd3579e69ae6d41b6382eaf1646accf83d6feb16acb703 *model.safetensors e616cbeb5a913015eb3db96e001030048df2db560df363d4cf688f0c1b2c96de *model.safetensors
f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json
04b1682c59acbd057f4c9072297faa73d56fc9de053094c659cdb4c464f58f86 *tokenizer_config.json 04b1682c59acbd057f4c9072297faa73d56fc9de053094c659cdb4c464f58f86 *tokenizer_config.json

View File

@ -1,6 +1,6 @@
8aa40ce145adb73cb3a75194dc0224702a95850ec5275cabb728496bbd749fc6 *chat_template.jinja 8aa40ce145adb73cb3a75194dc0224702a95850ec5275cabb728496bbd749fc6 *chat_template.jinja
70b295cbe76b9cf1cdf0d09abf9559eaf07977203e2f2e777a31747f8f310903 *config.json e8f2fcd2681eb92233c0902866441f79a207b235f0b03364d41ebf8c53df62a0 *config.json
458b612096e75ba27e3c6d294f376537544a597c6b19954e026ff74f208fa46f *generation_config.json 3fec6d7004e5ae311864de130b62e32dac87569874c91b3fe9c46e9309345c1c *generation_config.json
bd86541d817978c896bd3579e69ae6d41b6382eaf1646accf83d6feb16acb703 *model.safetensors bd86541d817978c896bd3579e69ae6d41b6382eaf1646accf83d6feb16acb703 *model.safetensors
f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json f7f96da3a872b5e901575b2067c744ad336c3a3d77a21584d20024557b1bd7f0 *tokenizer.json
154e5ff1e7c152d964edf30da854ea62465c767719ac8e97e58babf2d4fa9079 *tokenizer_config.json 154e5ff1e7c152d964edf30da854ea62465c767719ac8e97e58babf2d4fa9079 *tokenizer_config.json

View File

@ -1,7 +1,7 @@
a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja
4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json 749b56d1b1e08081981169db6f2c44ab0be4fd6ebb452d15baafa5e09c21586a *config.json
532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json 4625d1d64d41d1fa9dae7af4ba1e1d7e65a194073d4efa58acb266a916eaaa74 *generation_config.json
d72dad62b90e40eb726baf0f2f1867db1b8289c183a60b75cd147e68e674d7b1 *model.safetensors 2b3e575ac065f11ae5d4a7c3740efccbed294b646f1645239191ee8393354e03 *model.safetensors
3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json 01562eddd6f9e9ec4bc31656a3b7055284cafbf889acc6c4348dca431ae31f68 *processor_config.json
a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json 87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4 *tokenizer.json
5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json 2e31d1126e81bddf8d15c3f95260fb487b48c5131b24fcbb5bb9d2537e7afac0 *tokenizer_config.json

View File

@ -1,7 +0,0 @@
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

View File

@ -1,7 +1,7 @@
a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja
4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json 749b56d1b1e08081981169db6f2c44ab0be4fd6ebb452d15baafa5e09c21586a *config.json
532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json 4625d1d64d41d1fa9dae7af4ba1e1d7e65a194073d4efa58acb266a916eaaa74 *generation_config.json
327e02f00fccfb8dd580c1b3ca1620438dd6d8c8224b3b38b70cabf893a8539c *model.safetensors 5e0fb0ac724cf079b693fc76a515e60bc16de72c32b36c107b9f078061c4f2ef *model.safetensors
3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json 01562eddd6f9e9ec4bc31656a3b7055284cafbf889acc6c4348dca431ae31f68 *processor_config.json
a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json 87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4 *tokenizer.json
5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json 2e31d1126e81bddf8d15c3f95260fb487b48c5131b24fcbb5bb9d2537e7afac0 *tokenizer_config.json

View File

@ -1,7 +1,7 @@
a92e1dd97cb1cb175c9b70c0828e146bea4371c2643319b661b777e89811972e *chat_template.jinja a92e1dd97cb1cb175c9b70c0828e146bea4371c2643319b661b777e89811972e *chat_template.jinja
356d8dbfb902b90da033c2d52057a806bfb6515769dd0a838a2f9f63f11ff50f *config.json b75e911805663da79fb9fbbbcc917b8f1a285d2da54d95c2c63ea7c1ffe9a05a *config.json
fd06532bce09e8c8367862f70f2cb29fe6a1e282c86593ef73d9f2d72492742a *generation_config.json 2cbd9df0e99570efcced23b8d777bdf1fc692efda54b21eb59ad56ade76c9db6 *generation_config.json
9ac21259a4afa23b4bd60750749cf0aa397f207f7d764850837af92da46967c9 *model.safetensors 6061519a9595326df41abcdd093892463793d4d026d6fd23548f1792f622a252 *model.safetensors
ef71e11b6e5ef721fab1ae1c6b7f6571c364d4f7da4de705a09c7ddbe642e4bf *processor_config.json 0c29f9491e769aabbc389ad5912127cf6d9d5fceda2db8767f73d48131348c81 *processor_config.json
a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json 87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4 *tokenizer.json
ad105045edbfa5e150367ba068a6b1d0326a35cf6f8a19b537702ddc66405f10 *tokenizer_config.json 4796e48d790a26d65f167bec8fc742beaa71f79f9468a6cd8b3ffa97f6e2a198 *tokenizer_config.json

View File

@ -53,7 +53,7 @@ for test_directory in script_directory.iterdir():
print() print()
valid_hashes: dict[str, set[str]] = {} valid_hashes: dict[str, list[str]] = {}
for hash_file in hash_files: for hash_file in hash_files:
with open(hash_file, "r", encoding="utf-8") as file: with open(hash_file, "r", encoding="utf-8") as file:
@ -63,24 +63,26 @@ for test_directory in script_directory.iterdir():
filename = filename.removeprefix("*") filename = filename.removeprefix("*")
if filename not in valid_hashes: if filename not in valid_hashes:
valid_hashes[filename] = set() valid_hashes[filename] = []
valid_hashes[filename].add(sha256.lower()) valid_hashes[filename].append(sha256.lower())
# Track which specific files failed within this test directory. # Track which specific files failed within this test directory.
failed_files: list[str] = [] failed_files: list[str] = []
for filename, hashes in valid_hashes.items(): for filename in valid_hashes:
sha256 = get_file_sha256(test_directory / "model" / filename) sha256 = get_file_sha256(test_directory / "model" / filename)
if sha256.lower() not in hashes: if sha256.lower() not in valid_hashes[filename]:
print( print(
(
f"Test {test_directory.name} has FAILED!\n" f"Test {test_directory.name} has FAILED!\n"
f"Output file {filename} doesn't match any valid hash.\n\n" f"Output file {filename} doesn't match any valid hash.\n\n"
f"Valid hashes:\n" f"Valid hashes:\n"
f"{chr(10).join(hashes)}\n\n" f"{chr(10).join(valid_hashes[filename])}\n\n"
f"Actual hash:\n" f"Actual hash:\n"
f"{sha256}\n" f"{sha256}\n"
) )
)
failed_files.append(filename) failed_files.append(filename)
if failed_files: if failed_files:

View File

@ -1,6 +0,0 @@
39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja
45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json
02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json
56d51e4bbc2b14927176078fa51c305bfc692c4312e18b9d8971cfe6f4a77876 *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json

View File

@ -1,6 +0,0 @@
39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja
45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json
02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json
e1bdf4a04a2dbe67e9f03c8c3769df99496946c34b58efed9a1018aab3eb28af *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json

View File

@ -1,6 +1,6 @@
39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja 39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja
45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json 35e3ad5aeaa78984629ceba6c22a4236b4c21d6959485900da2a5a98ea7e4062 *config.json
02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json 2ec7a17f55287d482ca956f5acff44d9e88f6c7fd5ec06c7c33d641afa9af330 *generation_config.json
28997c7fe4a4dfaae94a7d587cd2dd0a0affed6567e95902dc52c4cd2195313e *model.safetensors 0cdea9064dcbe6db666f9d42a283d664c133d4c67a2f6ea0fd863a54f522160c *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json 3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json 388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json

View File

@ -1,6 +0,0 @@
711867f04895d4947fb13ad8df6a675854b36cc43f124226d9fee92a306ebb24 *chat_template.jinja
fd47b91d3c75727d6a07d9e43ce2970c74c4c6ad5ca69187725f4b03b9735e7f *config.json
6a1c13f7a11a7c3e1907432fa5583929d3de5d2bada72b55a96e6d14ea9c0117 *generation_config.json
0eb02a08f2cb1052fd0c52f4d37942467061d8fc5e07c2133109ce0623e4629e *model.safetensors
3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json
ca510154d75bdc38492cb68114fa05a9bc5ce4777f8198f6ae63761926981cff *tokenizer_config.json

View File

@ -1,63 +0,0 @@
# 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()

View File

@ -1,131 +0,0 @@
# 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()

View File

@ -1,16 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors # Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import os
import sys
import tempfile
import unittest import unittest
from pathlib import Path
from unittest.mock import patch
from pydantic import ValidationError from pydantic import ValidationError
from heretic.config import ScorerConfig, Settings from heretic.config import ScorerConfig
class ScorerConfigTests(unittest.TestCase): class ScorerConfigTests(unittest.TestCase):
@ -52,164 +47,5 @@ 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 ConfigFileSelectionTests(unittest.TestCase):
def settings(
self, config_files: dict[str, str], heretic_config: str | None = None
) -> Settings:
with tempfile.TemporaryDirectory() as directory:
for name, content in config_files.items():
Path(directory, name).write_text(content)
environment = {
key: value
for key, value in os.environ.items()
if not key.startswith("HERETIC_")
}
if heretic_config is not None:
environment["HERETIC_CONFIG_FILE"] = heretic_config
previous_directory = os.getcwd()
os.chdir(directory)
try:
with (
patch.dict(os.environ, environment, clear=True),
patch("sys.argv", ["heretic"]),
):
return Settings(model="dummy")
finally:
os.chdir(previous_directory)
def test_environment_variable_selects_file(self) -> None:
settings = self.settings({"custom.toml": "n_trials = 42\n"}, "custom.toml")
self.assertEqual(settings.n_trials, 42)
def test_default_config_toml_still_loaded(self) -> None:
settings = self.settings({"config.toml": "n_trials = 42\n"})
self.assertEqual(settings.n_trials, 42)
def test_missing_default_config_file_is_silent(self) -> None:
settings = self.settings({})
self.assertEqual(settings.n_trials, Settings.model_fields["n_trials"].default)
def test_missing_configured_file_aborts(self) -> None:
with self.assertRaisesRegex(SystemExit, "does not exist"):
self.settings({}, "missing.toml")
def test_configured_default_file_missing_aborts(self) -> None:
# Unlike a missing implicit default, this counts as a configuration error.
with self.assertRaisesRegex(SystemExit, "does not exist"):
self.settings({}, "config.toml")
class SettingsUploadTagsTests(unittest.TestCase):
def test_default_upload_tags(self) -> None:
with patch("sys.argv", ["heretic"]):
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__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -1,76 +0,0 @@
# 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()

View File

@ -1,246 +0,0 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import json
import os
import sys
import tempfile
import unittest
from unittest.mock import patch
from pydantic import BaseModel
from heretic.config import Settings
from heretic.plugin import Plugin
from heretic.utils import generate_config_toml
class DummyNestedSettings(BaseModel):
commit: str | None = None
name: str = "default"
class DummySettings(BaseModel):
value: int = 0
optional: str | None = None
nested: DummyNestedSettings = DummyNestedSettings()
FULL_SETTINGS = {
"value": 42,
"optional": None,
"nested": {"commit": None, "name": "default"},
}
class DummyPlugin(Plugin):
settings: DummySettings
class WriteSettingsToConfigTests(unittest.TestCase):
def make_settings(self) -> Settings:
# Ensure no config.toml or HERETIC_* environment variables
# from the surrounding environment leak into the test.
with tempfile.TemporaryDirectory() as directory:
environment = {
key: value
for key, value in os.environ.items()
if not key.startswith("HERETIC_")
}
previous_directory = os.getcwd()
os.chdir(directory)
try:
with (
patch.dict(os.environ, environment, clear=True),
patch.object(sys, "argv", ["heretic"]),
):
return Settings(model="dummy")
finally:
os.chdir(previous_directory)
def make_plugin(self, heretic_settings: Settings) -> DummyPlugin:
return DummyPlugin(
heretic_settings=heretic_settings,
settings=DummySettings(value=42),
)
def test_records_effective_settings_without_config_file(self) -> None:
# Without a configuration file, model_extra starts out empty,
# and the plugin's settings must still be recorded.
heretic_settings = self.make_settings()
self.assertEqual(heretic_settings.model_extra, {})
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
self.assertEqual(
heretic_settings.model_extra,
{"scorer": {"DummyPlugin": FULL_SETTINGS}},
)
def test_records_instance_settings_under_instance_key(self) -> None:
heretic_settings = self.make_settings()
self.make_plugin(heretic_settings).write_settings_to_config("scorer", "small")
self.assertEqual(
heretic_settings.model_extra,
{"scorer": {"DummyPlugin_small": FULL_SETTINGS}},
)
def test_captures_runtime_mutations(self) -> None:
# Plugins resolve settings values at runtime (e.g. pinned dataset
# commits); the recorded settings must reflect those mutations.
heretic_settings = self.make_settings()
plugin = self.make_plugin(heretic_settings)
plugin.settings.value = 7
plugin.settings.optional = "resolved"
plugin.settings.nested.commit = "abc"
plugin.write_settings_to_config("modifier", None)
self.assertEqual(
heretic_settings.model_extra,
{
"modifier": {
"DummyPlugin": {
"value": 7,
"optional": "resolved",
"nested": {"commit": "abc", "name": "default"},
}
}
},
)
def test_recorded_settings_survive_serialization_roundtrip(self) -> None:
heretic_settings = self.make_settings()
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
# This is how settings are stored in study journal files and
# reproduce.json, and how they are restored when resuming
# a study or reproducing a model.
restored = Settings.model_validate_init_only(
json.loads(heretic_settings.model_dump_json()), heretic_settings
)
self.assertEqual(
restored.model_extra,
{"scorer": {"DummyPlugin": FULL_SETTINGS}},
)
def test_recorded_settings_appear_in_generated_config_toml(self) -> None:
heretic_settings = self.make_settings()
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
exported = generate_config_toml(heretic_settings)
# None values are omitted (TOML has no null value); they fall back
# to their defaults when the settings are validated.
self.assertIn("[scorer.DummyPlugin]", exported)
self.assertIn("value = 42", exported)
self.assertNotIn("optional", exported)
self.assertIn("[scorer.DummyPlugin.nested]", exported)
self.assertIn('name = "default"', exported)
self.assertNotIn("commit", exported)
def test_none_values_are_omitted_from_config_toml(self) -> None:
heretic_settings = self.make_settings()
plugin = self.make_plugin(heretic_settings)
plugin.settings.nested.commit = "abc"
plugin.write_settings_to_config("scorer", None)
exported = generate_config_toml(heretic_settings)
self.assertNotIn("optional", exported)
self.assertIn("[scorer.DummyPlugin.nested]", exported)
self.assertIn('commit = "abc"', exported)
self.assertIn('name = "default"', exported)
def test_recorded_settings_feed_back_into_plugin_validation(self) -> None:
# The recorded settings must be readable by the same mechanism
# that reads raw settings from the configuration file, so that
# resuming a study or reproducing a model restores them exactly.
heretic_settings = self.make_settings()
self.make_plugin(heretic_settings).write_settings_to_config("scorer", None)
raw_settings = DummyPlugin.get_settings_raw(
heretic_settings.model_extra, "scorer", None
)
validated = DummyPlugin.validate_settings(raw_settings)
self.assertEqual(validated, DummySettings(value=42))
def test_records_multiple_instances_independently(self) -> None:
heretic_settings = self.make_settings()
extra = heretic_settings.model_extra
assert extra is not None
first = self.make_plugin(heretic_settings)
second = self.make_plugin(heretic_settings)
# Different values ensure that neither instance overwrites the other.
first.settings.value = 10
second.settings.value = 20
first.write_settings_to_config("scorer", "small")
second.write_settings_to_config("scorer", "large")
self.assertEqual(
extra["scorer"],
{
"DummyPlugin_small": {**FULL_SETTINGS, "value": 10},
"DummyPlugin_large": {**FULL_SETTINGS, "value": 20},
},
)
def test_repeated_writes_update_recorded_settings(self) -> None:
heretic_settings = self.make_settings()
extra = heretic_settings.model_extra
assert extra is not None
plugin = self.make_plugin(heretic_settings)
plugin.write_settings_to_config("scorer", None)
# Subsequent writes must capture settings mutations made at runtime.
plugin.settings.value = 123
plugin.write_settings_to_config("scorer", None)
self.assertEqual(
extra["scorer"]["DummyPlugin"]["value"],
123,
)
def test_nested_none_values_fail_toml_serialization(self) -> None:
heretic_settings = self.make_settings()
extra = heretic_settings.model_extra
assert extra is not None
# None values inside lists cannot be represented in TOML and must
# cause serialization to fail rather than be silently removed.
extra["scorer"] = {
"DummyPlugin": {
"values": [1, None, 3],
}
}
with self.assertRaises((TypeError, ValueError)):
generate_config_toml(heretic_settings)
def test_plugins_without_settings_do_not_create_config_entries(self) -> None:
heretic_settings = self.make_settings()
plugin = DummyPluginWithoutSettings(
heretic_settings=heretic_settings,
)
plugin.write_settings_to_config("scorer", None)
self.assertEqual(heretic_settings.model_extra, {})
class DummyPluginWithoutSettings(Plugin):
pass
if __name__ == "__main__":
unittest.main()

View File

@ -1,60 +0,0 @@
# 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()

5307
uv.lock

File diff suppressed because it is too large Load Diff