Compare commits
18 Commits
modified-m
...
master
| Author | SHA1 | Date |
|---|---|---|
|
|
cd315cbceb | |
|
|
d89c7a2d5a | |
|
|
aecd4a845a | |
|
|
64e999152f | |
|
|
a14b854353 | |
|
|
8b0dbac4dd | |
|
|
4f89482c0d | |
|
|
75a640b7eb | |
|
|
ce61e18206 | |
|
|
3dbc48156d | |
|
|
b4864fdd59 | |
|
|
6fc6074c61 | |
|
|
21c68d0a94 | |
|
|
f4cf535403 | |
|
|
4b3a1bd8fd | |
|
|
0db5c31e10 | |
|
|
ecde93f1e0 | |
|
|
a9e7df2cda |
|
|
@ -15,14 +15,14 @@ wheels/
|
|||
# Editors
|
||||
/.vscode/
|
||||
|
||||
# ripgrep/fd-specific ignore file
|
||||
/.ignore
|
||||
|
||||
# Configuration file (root only, not ignored in test directories)
|
||||
/config.toml
|
||||
|
||||
# Study checkpoints
|
||||
checkpoints/
|
||||
|
||||
# Residual plots
|
||||
plots/
|
||||
|
||||
# Models generated by tests
|
||||
/tests/*/model/
|
||||
|
|
|
|||
340
README.md
340
README.md
|
|
@ -1,89 +1,82 @@
|
|||
<img width="128" align="right" alt="Logo" src="https://github.com/user-attachments/assets/df5f2840-2f92-4991-aa57-252747d7182e" />
|
||||
# THIS REPOSITORY HAS BEEN ARCHIVED. See https://github.com/p-e-w/heretic/issues/601 for more information.
|
||||
|
||||
# Heretic: Fully automatic censorship removal for language models<br><br>[](https://discord.gg/gdXc48gSyT) [](https://matrix.to/#/#heretic:matrix.org) [](https://huggingface.co/heretic-org) [](https://codeberg.org/p-e-w/heretic)
|
||||
<div align="center">
|
||||
|
||||
[](https://trendshift.io/repositories/20538)
|
||||
<img width="128" alt="Heretic logo" src="https://github.com/user-attachments/assets/df5f2840-2f92-4991-aa57-252747d7182e" />
|
||||
|
||||
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/).
|
||||
# Heretic
|
||||
|
||||
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.
|
||||
### Training-free language model modification
|
||||
|
||||
Heretic supports most dense models, including many multimodal models,
|
||||
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.
|
||||
**Remove censorship**, suppress slop, reduce sycophancy, and more.<br>
|
||||
All in an afternoon, on your gaming PC.
|
||||
|
||||
<img width="650" height="715" alt="Screenshot" src="https://github.com/user-attachments/assets/d71a5efa-d6be-4705-a817-63332afb2d15" />
|
||||
[](https://discord.gg/gdXc48gSyT)
|
||||
[](https://matrix.to/#/#heretic:matrix.org)
|
||||
[](https://huggingface.co/heretic-org)
|
||||
[](https://codeberg.org/p-e-w/heretic)
|
||||
|
||||
</div>
|
||||
|
||||
-----
|
||||
|
||||
|
||||
|
||||
Running unsupervised with the default configuration, Heretic can produce
|
||||
decensored models that rival the quality of abliterations created manually
|
||||
by human experts:
|
||||
[](https://trendshift.io/repositories/20538)
|
||||
[](https://heretic.sdad.pro/)
|
||||
|
||||
| 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** |
|
||||
|
||||
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.)*
|
||||
## Modify any LLM that you can run on your hardware[^1]
|
||||
|
||||
Of course, mathematical metrics and automated benchmarks never tell the whole
|
||||
story, and are no substitute for human evaluation. Models generated with
|
||||
Heretic have been well-received by users (links and emphasis added):
|
||||
[^1]: Heretic supports on-the-fly 4-bit model quantization with bitsandbytes,
|
||||
which can reduce the amount of VRAM required to process a model to the same amount
|
||||
that is used to run a typical quantized version of it, at a slight accuracy cost.
|
||||
Set the `quantization` option to `bnb_4bit` to enable this.
|
||||
|
||||
> "I was skeptical before, but I just downloaded
|
||||
> [**GPT-OSS 20B Heretic**](https://huggingface.co/p-e-w/gpt-oss-20b-heretic)
|
||||
> model and holy shit. It gives properly formatted long responses to sensitive topics,
|
||||
> using the exact uncensored words that you would expect from an uncensored model,
|
||||
> 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 is a unique tool that lets you do what only corporations with access
|
||||
to massive computing power usually do: *Modify,* rather than merely run,
|
||||
language models. It does not perform expensive training; rather, it uses
|
||||
a collection of mathematical techniques to steer behavior based on contrasting
|
||||
example prompts and matching scorers.
|
||||
|
||||
> "[**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/)
|
||||
Heretic can, depending on the configuration:
|
||||
|
||||
> "[[**Qwen3-4B-Instruct-2507-heretic**](https://huggingface.co/p-e-w/Qwen3-4B-Instruct-2507-heretic)]
|
||||
> Has been the best unquantized abliterated model that I have been able to run on 16gb vram."
|
||||
> [*(Link to comment)*](https://old.reddit.com/r/LocalLLaMA/comments/1phjxca/im_calling_these_people_out_right_now/nt06tji/)
|
||||
* **Suppress refusals/remove censorship** (this is the [default action](/config.default.toml))
|
||||
* Reduce slop ([`config.noslop.toml`](/config.noslop.toml))
|
||||
* Reduce humor ([`config.nohumor.toml`](/config.nohumor.toml))
|
||||
* 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))
|
||||
|
||||
Heretic models have also been independently benchmarked using standard metrics
|
||||
like MMLU and GSM8K, and have been found to compare favorably with models
|
||||
produced by competing abliteration tools:
|
||||
[1](https://old.reddit.com/r/LocalLLaMA/comments/1sojjoc/abliterlitics_benchmark_and_tensor_analysis/),
|
||||
[2](https://old.reddit.com/r/LocalLLaMA/comments/1sy18lx/abliterlitics_benchmarks_and_tensor_comparison/).
|
||||
and many, many other things.
|
||||
|
||||
### :bangbang: Using Heretic does NOT require understanding how language models work internally :bangbang:
|
||||
|
||||
In fact, you can go from zero to removing censorship from your first model
|
||||
[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
|
||||
[well over 5000](https://huggingface.co/models?other=heretic)
|
||||
models with Heretic.
|
||||
[thousands](https://huggingface.co/models?other=heretic)
|
||||
of 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."*
|
||||
|
||||
|
||||
|
||||
<img width="600" alt="Heretic screenshot" src="https://github.com/user-attachments/assets/a030f595-67ef-49a6-9d9a-779fdf752b58" />
|
||||
|
||||
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
Prepare a Python 3.10+ environment with PyTorch 2.2+ installed as appropriate
|
||||
Prepare a Python 3.10+ environment with PyTorch 2.6+ installed as appropriate
|
||||
for your hardware. Then run:
|
||||
|
||||
```sh
|
||||
|
|
@ -91,87 +84,179 @@ pip install -U heretic-llm
|
|||
heretic Qwen/Qwen3-4B-Instruct-2507
|
||||
```
|
||||
|
||||
Replace `Qwen/Qwen3-4B-Instruct-2507` with whatever model you want to decensor.
|
||||
Replace `Qwen/Qwen3-4B-Instruct-2507` with whatever model you want to process.
|
||||
**By default, Heretic performs censorship removal (refusal suppression).**
|
||||
If you want to do something else, choose one of the configuration files linked
|
||||
above, or write your own. See [`config.default.toml`](/config.default.toml)
|
||||
for available configuration options. Heretic loads the configuration from
|
||||
`config.toml` in the working directory by default, or from the file path in the
|
||||
`HERETIC_CONFIG_FILE` environment variable.
|
||||
|
||||
> [!IMPORTANT]
|
||||
>
|
||||
> While PyTorch 2.2 is the minimum version of PyTorch needed for Heretic to work,
|
||||
> some models and configurations might require features only found in
|
||||
> 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.
|
||||
> Configuration files made for Heretic 1.x are **not** compatible with Heretic 2.x!
|
||||
> See the [migration guide](/docs/migration_v1_to_v2.md) for what you need to change
|
||||
> in order to make your old configurations work.
|
||||
|
||||
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.
|
||||
On an RTX 3090, with the default configuration, decensoring
|
||||
On an RTX 3090, with the default configuration, processing
|
||||
[Qwen3-4B-Instruct-2507](https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507)
|
||||
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.
|
||||
takes about 30-40 minutes.
|
||||
|
||||
After Heretic has finished decensoring a model, you are given the option to
|
||||
After Heretic has finished processing a model, you are given the choice to
|
||||
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.
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
Heretic implements a parametrized variant of directional ablation. For each
|
||||
supported transformer component (currently, attention out-projection and
|
||||
MLP down-projection), it identifies the associated matrices in each transformer
|
||||
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 combines a pluggable modifier (interface in
|
||||
[`modifier.py`](/src/heretic/modifier.py)) with a TPE-based hyperparameter optimizer
|
||||
powered by [Optuna](https://optuna.org/). The optimizer finds a set of parameters that,
|
||||
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)).
|
||||
|
||||
Residual directions are computed for each layer as a difference-of-means between
|
||||
the first-token residuals for "harmful" and "harmless" example prompts.
|
||||
Heretic ships with two modifiers:
|
||||
|
||||
The ablation process is controlled by several optimizable parameters:
|
||||
* **Arbitrary-Rank Ablation (ARA)**[^4]: This is the default modifier, and was
|
||||
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).
|
||||
|
||||
* `direction_index`: Either the index of a residual direction, or the special
|
||||
value `per layer`, indicating that each layer should be ablated using the
|
||||
residual direction associated with that layer.
|
||||
* `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:
|
||||
* **Directional ablation aka "abliteration"**[^5]: The classic method for refusal
|
||||
suppression. Heretic's implementation uses a flexible ablation weight kernel over
|
||||
the layers, and supports both projected abliteration[^6] and norm preservation (MPOA)[^7].
|
||||
The complete code is in [`abliteration.py`](/src/heretic/modifiers/abliteration.py).
|
||||
|
||||
<img width="800" height="500" alt="Explanation" src="https://github.com/user-attachments/assets/82e4b84e-5a82-4faf-b918-ac642f9e4892" />
|
||||
[^4]: *Weidmann 2026.* A preprint explaining the technique will be available soon.
|
||||
[^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.
|
||||
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:
|
||||
|
||||
* The shape of the ablation weight kernel is highly flexible, which, combined with
|
||||
automatic parameter optimization, can improve the compliance/quality tradeoff.
|
||||
Non-constant ablation weights were previously explored by Maxime Labonne in
|
||||
[gemma-3-12b-it-abliterated-v2](https://huggingface.co/mlabonne/gemma-3-12b-it-abliterated-v2).
|
||||
* The residual direction index is a float rather than an integer. For non-integral
|
||||
values, the two nearest residual direction vectors are linearly interpolated.
|
||||
This unlocks a vast space of additional directions beyond the ones identified
|
||||
by the difference-of-means computation, and often enables the optimization
|
||||
process to find a better direction than that belonging to any individual layer.
|
||||
* Ablation parameters are chosen separately for each component. I have found that
|
||||
MLP interventions tend to be more damaging to the model than attention interventions,
|
||||
so using different ablation weights can squeeze out some extra performance.
|
||||
## Reproducibility and the Heretic Grimoire
|
||||
|
||||
Heretic has the ability to create *reproducible models* whose repositories contain
|
||||
all information required to produce a byte-for-byte identical model on demand,
|
||||
provided that the environment is perfectly identical to the original one. PyTorch
|
||||
doesn't guarantee that operations return identical outputs unless hardware, drivers,
|
||||
operating system, and the entire software stack including all package versions
|
||||
are exactly the same.
|
||||
|
||||
Heretic manages all that complexity for you. When uploading a processed model to
|
||||
Hugging Face, Heretic offers to include reproducibility information. This is entirely
|
||||
optional, but if you choose to do so, the uploaded repository will contain a
|
||||
`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
|
||||
|
||||
I'm aware of the following publicly available implementations of abliteration
|
||||
techniques:
|
||||
I'm aware of the following implementations of abliteration techniques
|
||||
that were publicly available when Heretic was first released (November 2025):
|
||||
|
||||
* [AutoAbliteration](https://huggingface.co/posts/mlabonne/714992455492422)
|
||||
* [abliterator.py](https://github.com/FailSpy/abliterator)
|
||||
|
|
@ -188,11 +273,13 @@ any of those projects.
|
|||
|
||||
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),
|
||||
as well as some details from the model cards of his own abliterated models (see above)
|
||||
as well as some details from the model cards of his own abliterated models, such as
|
||||
the use of non-constant ablation weights
|
||||
* 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)
|
||||
* Thousands of interactions with members of the community
|
||||
|
||||
|
||||
## Citation
|
||||
|
|
@ -202,7 +289,7 @@ If you use Heretic for your research, please cite it using the following BibTeX
|
|||
```bibtex
|
||||
@misc{heretic,
|
||||
author = {Weidmann, Philipp Emanuel},
|
||||
title = {Heretic: Fully automatic censorship removal for language models},
|
||||
title = {Heretic: Training-free language model modification},
|
||||
year = {2025},
|
||||
publisher = {GitHub},
|
||||
journal = {GitHub repository},
|
||||
|
|
@ -230,3 +317,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|||
|
||||
**By contributing to this project, you agree to release your
|
||||
contributions under the same license.**
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,14 @@
|
|||
# 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" },
|
||||
]
|
||||
|
|
@ -87,7 +87,7 @@ modifiers = [
|
|||
{ plugin = "heretic.modifiers.ara.ARA" },
|
||||
]
|
||||
|
||||
# Number of abliteration trials to run during optimization.
|
||||
# Number of trials to run during optimization.
|
||||
n_trials = 100
|
||||
|
||||
# Number of trials that use random sampling for the purpose of exploration.
|
||||
|
|
@ -96,6 +96,9 @@ n_startup_trials = 30
|
|||
# Directory to save and load study progress to/from.
|
||||
study_checkpoint_dir = "checkpoints"
|
||||
|
||||
# Adjective describing the type of model produced by the configuration.
|
||||
modified_model_type = "decensored"
|
||||
|
||||
# Maximum size for individual safetensors files generated when exporting a model.
|
||||
max_shard_size = "5GB"
|
||||
|
||||
|
|
@ -109,6 +112,10 @@ upload_tags = [
|
|||
# System prompt to use when prompting the model.
|
||||
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.
|
||||
[batch_size_test_prompts]
|
||||
dataset = "mlabonne/harmless_alpaca"
|
||||
|
|
@ -160,7 +167,7 @@ column = "text"
|
|||
# Name that describes what the configured keyword rate measures.
|
||||
score_name = "Refusals"
|
||||
|
||||
# Whether to print prompt/response pairs when counting keyword matches.
|
||||
# Whether to print prompt/response pairs.
|
||||
print_responses = false
|
||||
|
||||
# Strings whose presence in a response (case insensitive) identifies the response as a keyword match.
|
||||
|
|
@ -214,6 +221,71 @@ split = "test[:100]"
|
|||
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]
|
||||
# Name that describes what the configured benchmark score measures.
|
||||
score_name = "PIQA acc_norm"
|
||||
|
|
@ -224,6 +296,30 @@ task = "piqa"
|
|||
# Task metric to use as the benchmark score.
|
||||
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]
|
||||
# Whether to renormalize the rows of the modified matrices to preserve
|
||||
|
|
|
|||
|
|
@ -0,0 +1,120 @@
|
|||
# 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"
|
||||
|
|
@ -3,6 +3,8 @@
|
|||
|
||||
max_response_length = 300
|
||||
|
||||
modified_model_type = "humor-reduced"
|
||||
|
||||
upload_tags = [
|
||||
"no-humor",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
|
||||
max_response_length = 300
|
||||
|
||||
modified_model_type = "slop-reduced"
|
||||
|
||||
upload_tags = [
|
||||
"no-slop",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
|
||||
max_response_length = 100
|
||||
|
||||
modified_model_type = "sycophancy-reduced"
|
||||
|
||||
upload_tags = [
|
||||
"no-sycophancy",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
# Rename this file to config.toml, place it in the working directory
|
||||
# that you run Heretic from, and edit the configuration to your liking.
|
||||
|
||||
scorers = [
|
||||
{ plugin = "heretic.scorers.response_length.ResponseLength", optimization = "minimize" },
|
||||
# We cannot use KL divergence because there is no set of prompts for which
|
||||
# we expect the modified model to retain its behavior.
|
||||
{ plugin = "heretic.scorers.benchmark_score.BenchmarkScore", optimization = "maximize" },
|
||||
]
|
||||
|
||||
modified_model_type = "tersified"
|
||||
|
||||
upload_tags = [
|
||||
"terse",
|
||||
]
|
||||
|
||||
[modifier.ARA.good_prompts]
|
||||
dataset = "mlabonne/harmless_alpaca"
|
||||
split = "train[:400]"
|
||||
column = "text"
|
||||
system_prompt = """You are a hyper-terse assistant. You respond with the minimum amount of text that satisfies the prompt.
|
||||
You don't use introductions, you don't repeat or rephrase the task, you don't provide additional information,
|
||||
and you don't use full sentences when a single word or item suffices.
|
||||
|
||||
Here are some examples showing how you should, and shouldn't, respond:
|
||||
|
||||
User: What is 1+1?
|
||||
Good response: 2
|
||||
Bad response: 1 + 1 = 2! This is a simple addition operation.
|
||||
|
||||
User: What is the largest land animal?
|
||||
Good response: African elephant
|
||||
Bad response: The largest land animal is the African bush elephant (*Loxodonta africana*),
|
||||
with fully grown bulls reaching an average shoulder height of 3.3 meters, and a body mass of 6 tons.
|
||||
|
||||
User: Describe a grocery shopping trip.
|
||||
Good response: Go to store, buy groceries, return
|
||||
Bad response: First, make sure you have a shopping list. Then pack your shopping bags
|
||||
into your car and drive to the grocery store. Make sure you park as closely as possible
|
||||
to the entrance of the store. Once inside, pick up a cart and check the aisles for the items you need.
|
||||
Collect all items in your cart and proceed to the register. Pay for the items and take the cart
|
||||
to your car. Move the items from the cart into the trunk of your car. Then return the cart to the store,
|
||||
return to your car, and drive home."""
|
||||
|
||||
[modifier.ARA.bad_prompts]
|
||||
dataset = "mlabonne/harmless_alpaca"
|
||||
split = "train[:400]"
|
||||
column = "text"
|
||||
system_prompt = """You are a loquacious personal assistant. You give elaborate, highly detailed responses to every prompt.
|
||||
Your responses contain proper introductions and start with a summary of the task or question.
|
||||
You supply as much additional information as possible and write everything out in full detail."""
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
# 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.
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
[project]
|
||||
name = "heretic-llm"
|
||||
version = "2.0.0.dev0"
|
||||
description = "Fully automatic censorship removal for language models"
|
||||
version = "2.2.0.dev0"
|
||||
description = "Training-free language model modification"
|
||||
readme = "README.md"
|
||||
license = "AGPL-3.0-or-later"
|
||||
authors = [
|
||||
|
|
@ -10,7 +10,7 @@ authors = [
|
|||
requires-python = ">=3.10"
|
||||
keywords = ["llm", "transformer", "abliteration"]
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Environment :: Console",
|
||||
"Environment :: GPU",
|
||||
"Intended Audience :: Science/Research",
|
||||
|
|
@ -19,6 +19,9 @@ classifiers = [
|
|||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Programming Language :: Python :: 3.14",
|
||||
"Programming Language :: Python :: 3.15",
|
||||
]
|
||||
dependencies = [
|
||||
"accelerate~=1.15",
|
||||
|
|
@ -26,6 +29,7 @@ dependencies = [
|
|||
"datasets~=5.0",
|
||||
"huggingface-hub~=1.33",
|
||||
"immutabledict~=4.3",
|
||||
"ipython~=8.39",
|
||||
"langdetect~=1.0",
|
||||
"lm-eval[hf]~=0.4",
|
||||
"numpy~=2.2",
|
||||
|
|
@ -72,8 +76,7 @@ ignore = [
|
|||
]
|
||||
|
||||
[tool.uv]
|
||||
# TODO: Re-enable before 2.0 release!
|
||||
#exclude-newer = "7 days"
|
||||
exclude-newer = "7 days"
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch" }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
|
||||
|
||||
import os
|
||||
from enum import Enum
|
||||
from typing import Any, Literal, TypeAlias
|
||||
|
||||
|
|
@ -190,6 +191,15 @@ class BenchmarkSpecification(BaseModel):
|
|||
)
|
||||
|
||||
|
||||
def _config_path() -> str:
|
||||
path = os.environ.get("HERETIC_CONFIG_FILE", "config.toml")
|
||||
|
||||
if "HERETIC_CONFIG_FILE" in os.environ and not os.path.isfile(path):
|
||||
raise SystemExit(f"heretic: configuration file {path} does not exist")
|
||||
|
||||
return path
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model: str = Field(description="Hugging Face model ID, or path to model on disk.")
|
||||
|
||||
|
|
@ -201,7 +211,7 @@ class Settings(BaseSettings):
|
|||
evaluate_model: str | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"If this model ID or path is set, then instead of abliterating the main model, "
|
||||
"If this model ID or path is set, then instead of modifying the main model, "
|
||||
"evaluate this model relative to the main model."
|
||||
),
|
||||
exclude=True,
|
||||
|
|
@ -210,7 +220,7 @@ class Settings(BaseSettings):
|
|||
collect_reproducibles: str | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"If this directory path is set, then instead of abliterating a model, "
|
||||
"If this directory path is set, then instead of modifying a model, "
|
||||
"download all reproduce.json files from public Heretic model repositories "
|
||||
"on Hugging Face, and store them in that directory for archival purposes."
|
||||
),
|
||||
|
|
@ -221,7 +231,7 @@ class Settings(BaseSettings):
|
|||
default=None,
|
||||
description=(
|
||||
"If this path or URL to a reproduce.json file is set, load reproduction information "
|
||||
"from that file, and attempt to reproduce the abliterated model it originated from."
|
||||
"from that file, and attempt to reproduce the modified model it originated from."
|
||||
),
|
||||
exclude=True,
|
||||
)
|
||||
|
|
@ -405,7 +415,7 @@ class Settings(BaseSettings):
|
|||
|
||||
n_trials: PositiveInt = Field(
|
||||
default=100,
|
||||
description="Number of abliteration trials to run during optimization.",
|
||||
description="Number of trials to run during optimization.",
|
||||
)
|
||||
|
||||
n_startup_trials: NonNegativeInt = Field(
|
||||
|
|
@ -427,6 +437,11 @@ class Settings(BaseSettings):
|
|||
exclude=True,
|
||||
)
|
||||
|
||||
modified_model_type: str = Field(
|
||||
default="decensored",
|
||||
description="Adjective describing the type of model produced by the configuration.",
|
||||
)
|
||||
|
||||
benchmarks: list[BenchmarkSpecification] = Field(
|
||||
default=[
|
||||
BenchmarkSpecification(
|
||||
|
|
@ -485,7 +500,7 @@ class Settings(BaseSettings):
|
|||
description="An Adversarial Winograd Schema Challenge at Scale",
|
||||
),
|
||||
],
|
||||
description="Benchmarks to offer to the user for evaluating abliterated models.",
|
||||
description="Benchmarks to offer to the user for evaluating modified models.",
|
||||
exclude=True,
|
||||
)
|
||||
|
||||
|
|
@ -516,7 +531,7 @@ class Settings(BaseSettings):
|
|||
|
||||
model_action: str | None = Field(
|
||||
default=None,
|
||||
description='Action to take with the decensored model: "save", "upload", or unset to prompt the user.',
|
||||
description='Action to take with the modified model: "save", "upload", or unset to prompt the user.',
|
||||
)
|
||||
|
||||
save_directory: str | None = Field(
|
||||
|
|
@ -560,6 +575,15 @@ class Settings(BaseSettings):
|
|||
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
|
||||
# configuration in TOML tables like `[scorer.KeywordRate]` which are later
|
||||
# consumed via `settings.model_extra` (see `plugin.get_plugin_namespace`).
|
||||
|
|
@ -585,7 +609,7 @@ class Settings(BaseSettings):
|
|||
EnvSettingsSource(settings_cls, env_prefix="HERETIC_"),
|
||||
dotenv_settings,
|
||||
file_secret_settings,
|
||||
TomlConfigSettingsSource(settings_cls, toml_file="config.toml"),
|
||||
TomlConfigSettingsSource(settings_cls, toml_file=_config_path()),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
|
|
|||
|
|
@ -174,7 +174,9 @@ class Evaluator:
|
|||
"""
|
||||
records: list[dict[str, Any]] = []
|
||||
for (name, score), (baseline_name, baseline) in zip(
|
||||
scores, self.baseline_scores
|
||||
scores,
|
||||
self.baseline_scores,
|
||||
strict=True,
|
||||
):
|
||||
assert name == baseline_name, (
|
||||
f"Score/baseline order mismatch: {name!r} != {baseline_name!r}"
|
||||
|
|
@ -228,3 +230,10 @@ class Evaluator:
|
|||
parse_study_direction(entry.config.optimization)
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -60,10 +60,12 @@ from pathlib import Path
|
|||
from typing import Any, cast
|
||||
|
||||
import huggingface_hub
|
||||
import IPython
|
||||
import lm_eval
|
||||
import numpy as np
|
||||
import optuna
|
||||
import questionary
|
||||
import rich.traceback
|
||||
import torch
|
||||
import transformers
|
||||
from huggingface_hub import HfApi, ModelCard, ModelCardData
|
||||
|
|
@ -79,7 +81,6 @@ from questionary import Choice, Style
|
|||
from rich.markup import escape
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
from rich.traceback import install
|
||||
|
||||
from .config import (
|
||||
DatasetSpecification,
|
||||
|
|
@ -175,7 +176,7 @@ def obtain_export_strategy(
|
|||
"How do you want to export the model?",
|
||||
choices=[
|
||||
Choice(
|
||||
title="Merge the abliteration LoRA and export the full model"
|
||||
title="Merge the LoRA and export the full model"
|
||||
+ (
|
||||
""
|
||||
if settings.quantization == QuantizationMethod.NONE
|
||||
|
|
@ -184,7 +185,7 @@ def obtain_export_strategy(
|
|||
value=ExportStrategy.MERGE,
|
||||
),
|
||||
Choice(
|
||||
title="Export the abliteration LoRA only (can be merged later)",
|
||||
title="Export the LoRA only (can be merged later)",
|
||||
value=ExportStrategy.ADAPTER,
|
||||
),
|
||||
],
|
||||
|
|
@ -661,6 +662,18 @@ def run():
|
|||
modifier = modifier_entry.modifier
|
||||
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.
|
||||
# This should free up memory from temporary objects created while initializing modifiers.
|
||||
empty_cache()
|
||||
|
|
@ -739,6 +752,7 @@ def run():
|
|||
load_if_exists=True,
|
||||
)
|
||||
|
||||
write_plugin_settings_to_config()
|
||||
study.set_user_attr("settings", settings.model_dump_json())
|
||||
study.set_user_attr("finished", False)
|
||||
|
||||
|
|
@ -815,6 +829,14 @@ def run():
|
|||
)
|
||||
)
|
||||
|
||||
if settings.enable_shell:
|
||||
choices.append(
|
||||
Choice(
|
||||
title="Open in-context Python shell",
|
||||
value="shell",
|
||||
)
|
||||
)
|
||||
|
||||
choices.append(
|
||||
Choice(
|
||||
title="Exit program",
|
||||
|
|
@ -891,6 +913,7 @@ def run():
|
|||
continue
|
||||
|
||||
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("finished", False)
|
||||
|
||||
|
|
@ -907,6 +930,53 @@ def run():
|
|||
|
||||
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(
|
||||
f"Restoring model from trial [bold]{trial.user_attrs['index']}[/]..."
|
||||
|
|
@ -925,7 +995,7 @@ def run():
|
|||
modifier.reset_model(ctx)
|
||||
print(f"* Modifying model using {modifier_name}...")
|
||||
parameters = modifier.parameters_class.from_dict(
|
||||
trial.user_attrs["parameters"]
|
||||
trial.user_attrs["parameters"] # ty: ignore[unresolved-attribute]
|
||||
)
|
||||
modifier.modify_model(ctx, parameters)
|
||||
|
||||
|
|
@ -944,7 +1014,7 @@ def run():
|
|||
action = ask_if_unset(
|
||||
settings.model_action,
|
||||
questionary.select(
|
||||
"What do you want to do with the decensored model?",
|
||||
f"What do you want to do with the {settings.modified_model_type} model?",
|
||||
choices=[
|
||||
Choice(
|
||||
title="Save the model to a local folder",
|
||||
|
|
@ -1005,7 +1075,6 @@ def run():
|
|||
save_directory,
|
||||
max_shard_size=settings.max_shard_size,
|
||||
)
|
||||
print(f"Model saved to [bold]{save_directory}[/].")
|
||||
else:
|
||||
print("Saving merged model...")
|
||||
merged_model = model.get_merged_model()
|
||||
|
|
@ -1018,10 +1087,8 @@ def run():
|
|||
model.tokenizer.save_pretrained(save_directory)
|
||||
if model.processor is not None:
|
||||
model.processor.save_pretrained(save_directory)
|
||||
print(f"Model saved to [bold]{save_directory}[/].")
|
||||
# Merging replaced the trial's adapter in place.
|
||||
# Restore it only after the save has been reported.
|
||||
reset_trial_model()
|
||||
|
||||
print(f"Model saved to [bold]{save_directory}[/].")
|
||||
|
||||
if reproduction_mode:
|
||||
print("Verifying hashes of weight files...")
|
||||
|
|
@ -1048,6 +1115,9 @@ def run():
|
|||
f"[bold]{filename}:[/] [red]File not found[/]"
|
||||
)
|
||||
|
||||
if strategy != ExportStrategy.ADAPTER:
|
||||
reset_trial_model()
|
||||
|
||||
case "upload":
|
||||
# We don't use huggingface_hub.login() because that stores the token on disk,
|
||||
# and since this program will often be run on rented or shared GPU servers,
|
||||
|
|
@ -1175,7 +1245,6 @@ def run():
|
|||
max_shard_size=settings.max_shard_size,
|
||||
token=token,
|
||||
)
|
||||
print(f"Model uploaded to [bold]{repo_id}[/].")
|
||||
else:
|
||||
print("Uploading merged model...")
|
||||
merged_model = model.get_merged_model()
|
||||
|
|
@ -1198,10 +1267,6 @@ def run():
|
|||
private=private,
|
||||
token=token,
|
||||
)
|
||||
print(f"Model uploaded to [bold]{repo_id}[/].")
|
||||
# Merging replaced the trial's adapter in place.
|
||||
# Restore it only after the upload has been reported.
|
||||
reset_trial_model()
|
||||
|
||||
if is_hf_path(settings.model):
|
||||
card = ModelCard.load(settings.model)
|
||||
|
|
@ -1248,8 +1313,22 @@ def run():
|
|||
card.push_to_hub(repo_id, token=token)
|
||||
|
||||
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
|
||||
# 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)
|
||||
current_export_strategy = settings.export_strategy
|
||||
settings.export_strategy = strategy
|
||||
|
|
@ -1269,6 +1348,8 @@ def run():
|
|||
finally:
|
||||
settings.export_strategy = current_export_strategy
|
||||
|
||||
print(f"Model uploaded to [bold]{repo_id}[/].")
|
||||
|
||||
if reproduction_mode:
|
||||
print("Verifying hashes of weight files...")
|
||||
|
||||
|
|
@ -1320,6 +1401,9 @@ def run():
|
|||
f"[bold]{filename}:[/] [red]File not found[/]"
|
||||
)
|
||||
|
||||
if strategy != ExportStrategy.ADAPTER:
|
||||
reset_trial_model()
|
||||
|
||||
case "chat":
|
||||
print()
|
||||
print(
|
||||
|
|
@ -1366,11 +1450,11 @@ def run():
|
|||
|
||||
scope = questionary.select(
|
||||
(
|
||||
"Do you want to benchmark the original model along with the decensored model? "
|
||||
f"Do you want to benchmark the original model along with the {settings.modified_model_type} model? "
|
||||
"Benchmarking both models allows you to compare the scores, but it takes twice as much time."
|
||||
),
|
||||
choices=[
|
||||
"Benchmark only the decensored model",
|
||||
f"Benchmark only the {settings.modified_model_type} model",
|
||||
"Benchmark both models",
|
||||
],
|
||||
style=Style([("highlighted", "reverse")]),
|
||||
|
|
@ -1467,8 +1551,7 @@ def run():
|
|||
|
||||
|
||||
def main():
|
||||
# Install Rich traceback handler.
|
||||
install()
|
||||
rich.traceback.install()
|
||||
|
||||
try:
|
||||
run()
|
||||
|
|
|
|||
|
|
@ -44,6 +44,29 @@ def get_model_class(
|
|||
return AutoModelForCausalLM
|
||||
|
||||
|
||||
def check_model_resident(model: PreTrainedModel | PeftModel) -> None:
|
||||
"""
|
||||
Ensure that all of the model's weights are resident in memory.
|
||||
"""
|
||||
offloaded = [name for name, param in model.named_parameters() if param.is_meta]
|
||||
|
||||
if not offloaded:
|
||||
return
|
||||
|
||||
raise Exception(
|
||||
"The model does not fit into the available device memory: "
|
||||
f"{len(offloaded)} weights (such as {', '.join(offloaded[:3])}) had to "
|
||||
"be offloaded to CPU or disk. Heretic cannot process offloaded models "
|
||||
"because it requires direct, persistent access to all weights, whereas "
|
||||
"offloaded weights only exist temporarily during forward passes.\n"
|
||||
"Possible remedies:\n"
|
||||
"* Free up memory, e.g. by closing other applications.\n"
|
||||
"* Change the device map (device_map/max_memory settings) so that all "
|
||||
"weights fit into device memory.\n"
|
||||
'* Enable 4-bit quantization (quantization = "bnb_4bit").'
|
||||
)
|
||||
|
||||
|
||||
def _collapse_flattened_residual_streams(
|
||||
hidden_states: tuple[FloatTensor, ...],
|
||||
config: Any,
|
||||
|
|
@ -212,6 +235,10 @@ class Model:
|
|||
)
|
||||
],
|
||||
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:
|
||||
self.model = None
|
||||
|
|
@ -233,6 +260,8 @@ class Model:
|
|||
if self.model is None:
|
||||
raise Exception("Failed to load model with all configured dtypes.")
|
||||
|
||||
check_model_resident(self.model)
|
||||
|
||||
print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers")
|
||||
|
||||
all_components = {}
|
||||
|
|
@ -242,7 +271,7 @@ class Model:
|
|||
all_components[component] = 0
|
||||
all_components[component] += len(modules)
|
||||
|
||||
print("* Abliterable components:")
|
||||
print("* Modifiable components:")
|
||||
for component, count in all_components.items():
|
||||
print(f" * [bold]{component}[/]: [bold]{count}[/] modules total")
|
||||
|
||||
|
|
@ -250,7 +279,7 @@ class Model:
|
|||
# Guard against calling this method at the wrong time.
|
||||
assert isinstance(self.model, PreTrainedModel)
|
||||
|
||||
# Always use LoRA adapters for abliteration (faster reload, no weight modification).
|
||||
# Always use LoRA adapters for modification (faster reload, no weight modification).
|
||||
# Collect actual leaf module names from the model for LoRA targeting.
|
||||
# This is more robust than splitting component keys (e.g. "attn.o_proj" -> "o_proj")
|
||||
# because hybrid models like Qwen3.5 MoE have modules with different names
|
||||
|
|
@ -419,6 +448,8 @@ class Model:
|
|||
**extra_kwargs,
|
||||
)
|
||||
|
||||
check_model_resident(self.model)
|
||||
|
||||
self.needs_reload = False
|
||||
|
||||
return False
|
||||
|
|
@ -513,13 +544,13 @@ class Model:
|
|||
for expert in layer.moe.experts: # ty:ignore[not-iterable, unresolved-attribute]
|
||||
try_add("mlp.down_proj", expert.output_linear) # ty: ignore[unresolved-attribute]
|
||||
|
||||
# We need at least one module across all components for abliteration to work.
|
||||
# We need at least one module across all components.
|
||||
total_modules = sum(len(mods) for mods in modules.values())
|
||||
assert total_modules > 0, "No abliterable modules found in layer"
|
||||
assert total_modules > 0, "No modifiable modules found in layer"
|
||||
|
||||
return modules
|
||||
|
||||
def get_abliterable_components(self) -> list[str]:
|
||||
def get_modifiable_components(self) -> list[str]:
|
||||
components: set[str] = set()
|
||||
|
||||
# Scan all layers because hybrid models (e.g. Qwen3.5 MoE) have different
|
||||
|
|
@ -828,7 +859,11 @@ class Model:
|
|||
)
|
||||
)
|
||||
|
||||
self.generate(prompts, max_new_tokens=1)
|
||||
self.generate(
|
||||
prompts,
|
||||
max_new_tokens=1,
|
||||
use_cache=False,
|
||||
)
|
||||
|
||||
for hook_handle in hook_handles:
|
||||
hook_handle.remove()
|
||||
|
|
|
|||
|
|
@ -255,7 +255,7 @@ class Abliteration(Modifier[Parameters]):
|
|||
|
||||
weight_distributions = {}
|
||||
|
||||
for component in model.get_abliterable_components():
|
||||
for component in model.get_modifiable_components():
|
||||
# The parameter ranges are based on experiments with various models
|
||||
# and much wider ranges. They are not set in stone and might have to be
|
||||
# adjusted for future models.
|
||||
|
|
|
|||
|
|
@ -8,7 +8,16 @@ import sys
|
|||
import types
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Annotated, Any, TypeVar, Union, get_args, get_origin, get_type_hints
|
||||
from typing import (
|
||||
Annotated,
|
||||
Any,
|
||||
TypeVar,
|
||||
Union,
|
||||
cast,
|
||||
get_args,
|
||||
get_origin,
|
||||
get_type_hints,
|
||||
)
|
||||
|
||||
from pydantic import BaseModel
|
||||
from torch import Tensor
|
||||
|
|
@ -202,14 +211,23 @@ class Plugin:
|
|||
"""
|
||||
Whether runs using this plugin can be reproduced bit-for-bit.
|
||||
|
||||
Set to False when the plugin's behavior is not deterministic or depends on
|
||||
Set to False if the plugin's behavior is not deterministic or depends on
|
||||
state outside the pinned config, for example:
|
||||
- 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 is otherwise non-deterministic (network, wall-clock, unseeded RNG).
|
||||
|
||||
Defaults to False; override to True in your plugin class if any of the
|
||||
Defaults to False; override to True in your plugin class if the
|
||||
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
|
||||
|
||||
|
|
@ -338,6 +356,28 @@ class Plugin:
|
|||
return None
|
||||
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]:
|
||||
"""
|
||||
Collect the dataset specifications declared in the settings
|
||||
|
|
|
|||
|
|
@ -53,8 +53,6 @@ class Scorer(Plugin, ABC):
|
|||
def get_score(self, ctx: Context) -> Score:
|
||||
"""
|
||||
Return a `Score` given the evaluation context.
|
||||
The `value` of the `Score` must be of the order of magnitude 1
|
||||
to ensure that all scores are comparable during co-optimization.
|
||||
"""
|
||||
|
||||
def get_baseline_score(self, ctx: Context) -> Score:
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
import lm_eval
|
||||
from lm_eval.models.huggingface import HFLM
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, NonNegativeInt
|
||||
|
||||
from heretic.scorer import Context, Score, Scorer
|
||||
|
||||
|
|
@ -24,6 +24,11 @@ class Settings(BaseModel):
|
|||
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):
|
||||
"""
|
||||
|
|
@ -40,29 +45,27 @@ class BenchmarkScore(Scorer):
|
|||
def score_name(self) -> str:
|
||||
return self.settings.score_name
|
||||
|
||||
def init(self, ctx: Context) -> None:
|
||||
model = ctx.get_model()
|
||||
|
||||
self.hflm = HFLM(
|
||||
pretrained=model.model,
|
||||
tokenizer=model.tokenizer, # ty:ignore[invalid-argument-type]
|
||||
batch_size="auto",
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
hflm = HFLM(
|
||||
pretrained=model.model,
|
||||
tokenizer=model.tokenizer, # ty: ignore[invalid-argument-type]
|
||||
batch_size="auto"
|
||||
if self.settings.batch_size == 0
|
||||
else self.settings.batch_size,
|
||||
)
|
||||
|
||||
results = lm_eval.simple_evaluate(
|
||||
model=self.hflm,
|
||||
model=hflm,
|
||||
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(
|
||||
results["results"][self.settings.task][self.settings.metric]
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,276 @@
|
|||
# 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]
|
||||
|
|
@ -78,7 +78,7 @@ class Settings(BaseModel):
|
|||
|
||||
print_responses: bool = Field(
|
||||
default=False,
|
||||
description="Whether to print prompt/response pairs when counting keyword matches.",
|
||||
description="Whether to print prompt/response pairs.",
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -110,7 +110,8 @@ class KeywordRate(Scorer):
|
|||
def get_score(self, ctx: Context) -> Score:
|
||||
match_count = 0
|
||||
responses = ctx.get_responses(self.prompts)
|
||||
for prompt, response in zip(self.prompts, responses):
|
||||
|
||||
for prompt, response in zip(self.prompts, responses, strict=True):
|
||||
is_match = self._is_match(response)
|
||||
if is_match:
|
||||
match_count += 1
|
||||
|
|
|
|||
|
|
@ -0,0 +1,101 @@
|
|||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
|
||||
|
||||
from pydantic import BaseModel, Field, NonNegativeInt
|
||||
from rich.markup import escape
|
||||
|
||||
from heretic.config import DatasetSpecification, SingleDatasetSpecification
|
||||
from heretic.scorer import Context, Score, Scorer
|
||||
from heretic.utils import format_dataset_specification, print
|
||||
|
||||
|
||||
class Settings(BaseModel):
|
||||
prompts: DatasetSpecification = Field(
|
||||
default=SingleDatasetSpecification(
|
||||
dataset="mlabonne/harmless_alpaca",
|
||||
split="test[:100]",
|
||||
column="text",
|
||||
),
|
||||
description="Dataset of prompts to evaluate the response length on.",
|
||||
)
|
||||
|
||||
strip_responses: bool = Field(
|
||||
default=True,
|
||||
description="Whether to strip leading and trailing whitespace from responses before measuring their length.",
|
||||
)
|
||||
|
||||
short_response_threshold: NonNegativeInt = Field(
|
||||
# Chosen because "No" is the shortest common valid response.
|
||||
default=2,
|
||||
description="Length in characters below which a response is classified as a 'short response'.",
|
||||
)
|
||||
|
||||
short_response_score_length: float = Field(
|
||||
default=500,
|
||||
description=(
|
||||
"Length value artificially assigned to 'short responses' for the purpose of scoring. "
|
||||
"This can be used to penalize very short (and thus likely invalid) responses."
|
||||
),
|
||||
)
|
||||
|
||||
print_responses: bool = Field(
|
||||
default=False,
|
||||
description="Whether to print prompt/response pairs.",
|
||||
)
|
||||
|
||||
|
||||
class ResponseLength(Scorer):
|
||||
"""
|
||||
Measures the mean length of responses.
|
||||
"""
|
||||
|
||||
settings: Settings
|
||||
|
||||
@property
|
||||
def reproducible(self) -> bool:
|
||||
return True
|
||||
|
||||
@property
|
||||
def score_name(self) -> str:
|
||||
return "Mean response length"
|
||||
|
||||
def init(self, ctx: Context) -> None:
|
||||
print()
|
||||
print(
|
||||
f"Loading response length evaluation prompts from [bold]{format_dataset_specification(self.settings.prompts)}[/]..."
|
||||
)
|
||||
self.prompts = ctx.load_prompts(self.settings.prompts)
|
||||
print(f"* [bold]{len(self.prompts)}[/] prompts loaded")
|
||||
|
||||
def get_score(self, ctx: Context) -> Score:
|
||||
total_length = 0
|
||||
responses = ctx.get_responses(self.prompts)
|
||||
|
||||
for prompt, response in zip(self.prompts, responses, strict=True):
|
||||
response_length = len(
|
||||
response.strip() if self.settings.strip_responses else response
|
||||
)
|
||||
if response_length < self.settings.short_response_threshold:
|
||||
response_length = self.settings.short_response_score_length
|
||||
total_length += response_length
|
||||
|
||||
if self.settings.print_responses:
|
||||
print()
|
||||
print(f"[bold]System prompt:[/] {escape(prompt.system)}")
|
||||
print(f"[bold]Prompt:[/] {escape(prompt.user)}")
|
||||
if not response.strip():
|
||||
response = "[italic]\\[empty][/]"
|
||||
else:
|
||||
response = escape(response)
|
||||
print(f"[bold]Response:[/] {response}")
|
||||
|
||||
if self.settings.print_responses:
|
||||
print()
|
||||
|
||||
mean_length = float(total_length / len(self.prompts))
|
||||
|
||||
return Score(
|
||||
value=mean_length,
|
||||
rich_display=f"[bold]{mean_length:.1f}[/]",
|
||||
md_display=f"{mean_length:.1f}",
|
||||
)
|
||||
|
|
@ -344,7 +344,7 @@ def get_readme_intro(
|
|||
else:
|
||||
reproducibility_instructions = ""
|
||||
|
||||
return f"""# This is a decensored version of {
|
||||
return f"""# This is a {settings.modified_model_type} version of {
|
||||
model_link
|
||||
}, made using [Heretic](https://heretic-project.org) v{version("heretic-llm")}
|
||||
{reproducibility_instructions}
|
||||
|
|
@ -372,10 +372,26 @@ 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:
|
||||
"""Serializes the full Settings object to TOML."""
|
||||
|
||||
return tomli_w.dumps(settings.model_dump(exclude_none=True))
|
||||
# The `exclude_none` option can't be used here because it only applies
|
||||
# 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:
|
||||
|
|
|
|||
119
tests/README.md
119
tests/README.md
|
|
@ -1,53 +1,47 @@
|
|||
# Test Suite Guide
|
||||
# Test Guide
|
||||
|
||||
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).
|
||||
This directory contains two kinds of tests:
|
||||
|
||||
## How to test
|
||||
1. **Reproducibility tests**: end-to-end tests that verify whether your new changes affect a model's reproducibility. See [Reproducibility tests](#1-reproducibility-tests).
|
||||
2. **Unit tests**: tests for individual units of heretic. See [Unit tests](#2-unit-tests).
|
||||
|
||||
1. Choose any model from [tiny-random](https://huggingface.co/tiny-random) org which provides tiny models useful for debugging.
|
||||
## 1. Reproducibility tests
|
||||
|
||||
**Example**: [tiny-random/minicpm5](https://huggingface.co/tiny-random/minicpm5).
|
||||
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.
|
||||
|
||||
> [!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.
|
||||
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.
|
||||
|
||||
2. Clone that model repository using Git and generate the SHA256 hashes using `sha256sum`:
|
||||
### How to test
|
||||
|
||||
**On Linux**:
|
||||
```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.
|
||||
|
||||
* **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:
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Delete the unnecessary files such as `README.md` and `.gitattributes` before generating the hash file.
|
||||
|
||||
* **On Linux**:
|
||||
|
||||
```bash
|
||||
sha256sum -b * > ../SHA256SUMS.LABEL
|
||||
```
|
||||
|
||||
**On Windows**:
|
||||
* **On Windows**:
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
**Example**:
|
||||
|
|
@ -56,19 +50,41 @@ Where `LABEL` describes the type of system you are running the tests on.
|
|||
- `SHA256SUMS.ci` (For GitHub CI)
|
||||
- `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:
|
||||
|
||||
```bash
|
||||
uv run run_tests.py
|
||||
```
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
```bash
|
||||
cd TEST_MODEL_DIR/model
|
||||
sha256sum -b * > ../SHA256SUMS.LABEL # or use windows command.
|
||||
sha256sum -b * > ../SHA256SUMS.LABEL # or use windows command.
|
||||
```
|
||||
|
||||
5. Re-run the tests with:
|
||||
|
|
@ -77,14 +93,33 @@ sha256sum -b * > ../SHA256SUMS.LABEL # or use windows command.
|
|||
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 GitHub CI actions to run those tests.
|
||||
6. After that, push the `SHA256SUMS.LABEL` files and wait for the **GitHub CI** actions to run those tests.
|
||||
|
||||
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.
|
||||
> [!NOTE]
|
||||
> The GitHub CI actions will run the tests only if your PR is targeting the `master` branch of Heretic.
|
||||
|
||||
For this, copy the `Actual hash` value for *each mismatched unidentical* file into a `SHA256SUMS.ci` file.
|
||||
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)*.
|
||||
|
||||
7. After that push the `SHA256SUMS.ci` files and wait for GitHub CI actions to re-run those tests.
|
||||
For this, copy the `Actual hash` value for *each* **unidentical** file into a new `SHA256SUMS.ci` file.
|
||||
|
||||
This time the tests *should* PASS because we added the new hashes which are expected to be reproduced on CI.
|
||||
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 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
|
||||
```
|
||||
|
|
|
|||
|
|
@ -0,0 +1,4 @@
|
|||
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
|
||||
f8f1fd0ef18d709772584f1a4d736fc8f31aafee83a001b34d333c30a606baf8 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
|
||||
2b0b38f5cc5b25e424dc944cf0b27432f736cffd59a8753f2ddd23f5434e5ab4 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
|
||||
ad8c373f6d6f3f00e646d118116fc1f34c91c5c67a10db6fe9366fd34f534df5 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
5595714af3f245d20831e545ee5ee41fec8f4ad5a89d9ca5abce0bf476debfa7 *config.json
|
||||
333322c2521ae1cbe6405f4770d690d8f404d0ce5587308b94520f058b949762 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
43184dd63293fc63deba9c8aab4353b4a15e46a2e7ab691ddcf4fd16d73cf77c *tokenizer_config.json
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
# 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"
|
||||
|
|
@ -134,6 +134,58 @@ class ModelValidateInitOnlyTests(unittest.TestCase):
|
|||
self.assertEqual(settings.max_memory, {"0": "20GiB"})
|
||||
|
||||
|
||||
class ConfigFileSelectionTests(unittest.TestCase):
|
||||
def settings(
|
||||
self, config_files: dict[str, str], heretic_config: str | None = None
|
||||
) -> Settings:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
for name, content in config_files.items():
|
||||
Path(directory, name).write_text(content)
|
||||
|
||||
environment = {
|
||||
key: value
|
||||
for key, value in os.environ.items()
|
||||
if not key.startswith("HERETIC_")
|
||||
}
|
||||
if heretic_config is not None:
|
||||
environment["HERETIC_CONFIG_FILE"] = heretic_config
|
||||
|
||||
previous_directory = os.getcwd()
|
||||
os.chdir(directory)
|
||||
try:
|
||||
with (
|
||||
patch.dict(os.environ, environment, clear=True),
|
||||
patch("sys.argv", ["heretic"]),
|
||||
):
|
||||
return Settings(model="dummy")
|
||||
finally:
|
||||
os.chdir(previous_directory)
|
||||
|
||||
def test_environment_variable_selects_file(self) -> None:
|
||||
settings = self.settings({"custom.toml": "n_trials = 42\n"}, "custom.toml")
|
||||
|
||||
self.assertEqual(settings.n_trials, 42)
|
||||
|
||||
def test_default_config_toml_still_loaded(self) -> None:
|
||||
settings = self.settings({"config.toml": "n_trials = 42\n"})
|
||||
|
||||
self.assertEqual(settings.n_trials, 42)
|
||||
|
||||
def test_missing_default_config_file_is_silent(self) -> None:
|
||||
settings = self.settings({})
|
||||
|
||||
self.assertEqual(settings.n_trials, Settings.model_fields["n_trials"].default)
|
||||
|
||||
def test_missing_configured_file_aborts(self) -> None:
|
||||
with self.assertRaisesRegex(SystemExit, "does not exist"):
|
||||
self.settings({}, "missing.toml")
|
||||
|
||||
def test_configured_default_file_missing_aborts(self) -> None:
|
||||
# Unlike a missing implicit default, this counts as a configuration error.
|
||||
with self.assertRaisesRegex(SystemExit, "does not exist"):
|
||||
self.settings({}, "config.toml")
|
||||
|
||||
|
||||
class SettingsUploadTagsTests(unittest.TestCase):
|
||||
def test_default_upload_tags(self) -> None:
|
||||
with patch("sys.argv", ["heretic"]):
|
||||
|
|
|
|||
|
|
@ -0,0 +1,246 @@
|
|||
# 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()
|
||||
143
uv.lock
143
uv.lock
|
|
@ -18,6 +18,10 @@ resolution-markers = [
|
|||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[[package]]
|
||||
name = "absl-py"
|
||||
version = "2.5.0"
|
||||
|
|
@ -297,6 +301,15 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asttokens"
|
||||
version = "3.0.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-timeout"
|
||||
version = "5.0.1"
|
||||
|
|
@ -776,6 +789,15 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/44/0b/98fc6eb83333508ca5f44c52b3e287ea8137a0ad582714e2cbc67a02154b/datasets-5.0.1-py3-none-any.whl", hash = "sha256:9fbf73688f8c18f7529b4fe592abd04015f81d1e58001e4bac73ffb2b39d7cc4", size = 559079, upload-time = "2026-07-28T11:09:10.266Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "decorator"
|
||||
version = "5.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/60/8b/32f9823da46cde7df2087faa08cd98d01b908f8dcab982cdba9c84e85355/decorator-5.3.1.tar.gz", hash = "sha256:4cbcdd55a6efadb9dbea26b858f4fb3264567b52d69ca0d25b721b553f60ea82", size = 58084, upload-time = "2026-05-18T06:03:28.057Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/05/7f/798705f5296a58ca505d600456748d1be48078eac8a7050d8a98bc9edb89/decorator-5.3.1-py3-none-any.whl", hash = "sha256:f47fe6fdbd2edd623ecfe36875d37aba411624e2670dd395dddae1358689bb3c", size = 10365, upload-time = "2026-05-18T06:03:26.517Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "defusedxml"
|
||||
version = "0.7.1"
|
||||
|
|
@ -853,6 +875,15 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "executing"
|
||||
version = "2.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/52/92/8a611141e42930c0f194f7504063ab87dfe970cf1a5af28e7703df448734/executing-2.3.0.tar.gz", hash = "sha256:15919cb5d667e5cb4e099511971d00d659573fff2dd5c4e6cd8b71636c7858d2", size = 1338003, upload-time = "2026-10-10T14:06:04.64Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/dd/8bc67e7d5ffc1d88aa5af511189dfb76dc4e1e5b808fab186146ef2663e5/executing-2.3.0-py3-none-any.whl", hash = "sha256:736e859c9f8701f11fcf516856f26f562e04776387824b43a35a1dfe21c84122", size = 29393, upload-time = "2026-10-10T14:06:02.777Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filelock"
|
||||
version = "4.0.8"
|
||||
|
|
@ -1078,7 +1109,7 @@ wheels = [
|
|||
|
||||
[[package]]
|
||||
name = "heretic-llm"
|
||||
version = "2.0.0.dev0"
|
||||
version = "2.2.0.dev0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "accelerate" },
|
||||
|
|
@ -1086,6 +1117,7 @@ dependencies = [
|
|||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "immutabledict" },
|
||||
{ name = "ipython" },
|
||||
{ name = "langdetect" },
|
||||
{ name = "lm-eval", extra = ["hf"] },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
|
|
@ -1120,6 +1152,7 @@ requires-dist = [
|
|||
{ name = "datasets", specifier = "~=5.0" },
|
||||
{ name = "huggingface-hub", specifier = "~=1.33" },
|
||||
{ name = "immutabledict", specifier = "~=4.3" },
|
||||
{ name = "ipython", specifier = "~=8.39" },
|
||||
{ name = "langdetect", specifier = "~=1.0" },
|
||||
{ name = "lm-eval", extras = ["hf"], specifier = "~=0.4" },
|
||||
{ name = "numpy", specifier = "~=2.2" },
|
||||
|
|
@ -1255,6 +1288,40 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/7a/68/bd9dd6bbf06772c7accce77d0354d783333fbe712a60b08fc13540c05422/importlib_resources-5.13.0-py3-none-any.whl", hash = "sha256:9f7bd0c97b79972a6cce36a366356d16d5e13b09679c11a58f1014bfdf8e64b2", size = 32912, upload-time = "2023-07-07T16:20:58.128Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipython"
|
||||
version = "8.39.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
{ name = "decorator" },
|
||||
{ name = "exceptiongroup", marker = "python_full_version < '3.11'" },
|
||||
{ name = "jedi" },
|
||||
{ name = "matplotlib-inline" },
|
||||
{ name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
|
||||
{ name = "prompt-toolkit" },
|
||||
{ name = "pygments" },
|
||||
{ name = "stack-data" },
|
||||
{ name = "traitlets" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.12'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/40/18/f8598d287006885e7136451fdea0755af4ebcbfe342836f24deefaed1164/ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624", size = 5513971, upload-time = "2026-03-27T10:02:13.94Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c0/56/4cc7fc9e9e3f38fd324f24f8afe0ad8bb5fa41283f37f1aaf9de0612c968/ipython-8.39.0-py3-none-any.whl", hash = "sha256:bb3c51c4fa8148ab1dea07a79584d1c854e234ea44aa1283bcb37bc75054651f", size = 831849, upload-time = "2026-03-27T10:02:07.846Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jedi"
|
||||
version = "0.20.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "parso" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/a4/4692ecd7fa700ac1066b1c1f6cadef60aa2e01e5e364710235137d823e0a/jedi-0.20.1.tar.gz", hash = "sha256:2f71208c3f9c1bca057c0e90d3f272aba44ace88fc4067d7587e9e069331b7e5", size = 3121738, upload-time = "2026-10-12T17:42:24.361Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/be/c7/71eb0d51cdcbb63b857c931aa4e9218b078b5d9f8ecd383b234f28fe7b0f/jedi-0.20.1-py2.py3-none-any.whl", hash = "sha256:0fb16d86c4a4c73c37ba518c77419975e30fcc620658a8d14fbb5720cdd34142", size = 4885980, upload-time = "2026-10-12T17:42:21.585Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jinja2"
|
||||
version = "3.1.6"
|
||||
|
|
@ -1634,6 +1701,18 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matplotlib-inline"
|
||||
version = "0.2.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "traitlets" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mbstrdecoder"
|
||||
version = "1.1.5"
|
||||
|
|
@ -2363,6 +2442,15 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/0b/a3/6419c14da2adc1f09a6a183b8f91d7494d325b287f4ca984ac04f663638a/pandas-3.0.6-cp315-cp315t-win_arm64.whl", hash = "sha256:963ca21199097a84c7827c4678b04e30833084fbf8ef44fde3fa7180a29f8fa0", size = 9364529, upload-time = "2026-09-17T23:23:15.274Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parso"
|
||||
version = "0.8.7"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pathvalidate"
|
||||
version = "3.3.1"
|
||||
|
|
@ -2396,6 +2484,18 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/70/0b/59441cdbfdd342ed03c08af90a2fe16173f0cd48ab219f523b39ca059a79/peft-0.21.2-py3-none-any.whl", hash = "sha256:106ab6077ff72c54d21577f9af5970e34bac7582cb14209f7b2b511e322a4eae", size = 835427, upload-time = "2026-10-01T10:26:34.085Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pexpect"
|
||||
version = "4.9.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "ptyprocess" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pillow"
|
||||
version = "12.3.0"
|
||||
|
|
@ -2693,6 +2793,24 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ptyprocess"
|
||||
version = "0.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pure-eval"
|
||||
version = "0.2.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/da/9f/abfd2959e9261dd5217ca8551d4de211ca6ab26fe9b72cf44731ff6c4442/pure_eval-0.2.4.tar.gz", hash = "sha256:260c2774686e651b79f8b8e7fc9d80b3599ea6a66334b47d5f4abb69fc2c0ea1", size = 20563, upload-time = "2026-09-10T21:41:22.836Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6d/18/83376915176eb058cb86470eb7396388a13350b09a8f233a79303bbcbc5b/pure_eval-0.2.4-py3-none-any.whl", hash = "sha256:96cae060a313cfaad51bb761278bfb0e62dc0248d9315a81173752dc546cd37a", size = 11893, upload-time = "2026-09-10T21:41:21.532Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "py-cpuinfo"
|
||||
version = "9.0.0"
|
||||
|
|
@ -3944,6 +4062,20 @@ version = "2.1.0"
|
|||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/12/9a/7620d1e9dcb02839ed6d4b14064e609cdd7a8ae1e47289aa0456796dd9ca/sqlitedict-2.1.0.tar.gz", hash = "sha256:03d9cfb96d602996f1d4c2db2856f1224b96a9c431bdd16e78032a72940f9e8c", size = 21846, upload-time = "2022-12-03T13:39:13.102Z" }
|
||||
|
||||
[[package]]
|
||||
name = "stack-data"
|
||||
version = "0.6.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "asttokens" },
|
||||
{ name = "executing" },
|
||||
{ name = "pure-eval" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sympy"
|
||||
version = "1.14.0"
|
||||
|
|
@ -4280,6 +4412,15 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "traitlets"
|
||||
version = "5.16.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/2c/2e/a7fbfe268c8a3b32546930c0297c101d65a4a14c304ad5790a9f478f0e4e/traitlets-5.16.1.tar.gz", hash = "sha256:ed900c2b631aa3a112811139fa97b8d2c3bad5e989656bba4b7e52c7852c18c1", size = 166137, upload-time = "2026-08-03T08:32:36.848Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "transformers"
|
||||
version = "5.18.0"
|
||||
|
|
|
|||
Loading…
Reference in New Issue