Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
753c9b6635 |
No files matched your search
@@ -21,5 +21,8 @@ wheels/
|
||||
# Study checkpoints
|
||||
checkpoints/
|
||||
|
||||
# Residual plots
|
||||
plots/
|
||||
|
||||
# Models generated by tests
|
||||
/tests/*/model/
|
||||
@@ -1,79 +1,89 @@
|
||||
<div align="center">
|
||||
<img width="128" align="right" alt="Logo" src="https://github.com/user-attachments/assets/df5f2840-2f92-4991-aa57-252747d7182e" />
|
||||
|
||||
<img width="128" alt="Heretic logo" src="https://github.com/user-attachments/assets/df5f2840-2f92-4991-aa57-252747d7182e" />
|
||||
# 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)
|
||||
|
||||
# Heretic
|
||||
[](https://trendshift.io/repositories/20538)
|
||||
|
||||
### Training-free language model modification
|
||||
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/).
|
||||
|
||||
**Remove censorship**, suppress slop, reduce sycophancy, and more.<br>
|
||||
All in an afternoon, on your gaming PC.
|
||||
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.
|
||||
|
||||
[](https://discord.gg/gdXc48gSyT)
|
||||
[](https://matrix.to/#/#heretic:matrix.org)
|
||||
[](https://huggingface.co/heretic-org)
|
||||
[](https://codeberg.org/p-e-w/heretic)
|
||||
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.
|
||||
|
||||
</div>
|
||||
|
||||
-----
|
||||
<img width="650" height="715" alt="Screenshot" src="https://github.com/user-attachments/assets/d71a5efa-d6be-4705-a817-63332afb2d15" />
|
||||
|
||||
|
||||
|
||||
[](https://trendshift.io/repositories/20538)
|
||||
[](https://heretic.sdad.pro/)
|
||||
Running unsupervised with the default configuration, Heretic can produce
|
||||
decensored models that rival the quality of abliterations created manually
|
||||
by human experts:
|
||||
|
||||
| Model | Refusals for "harmful" prompts | KL divergence from original model for "harmless" prompts |
|
||||
| :--- | ---: | ---: |
|
||||
| [google/gemma-3-12b-it](https://huggingface.co/google/gemma-3-12b-it) (original) | 97/100 | 0 *(by definition)* |
|
||||
| [mlabonne/gemma-3-12b-it-abliterated-v2](https://huggingface.co/mlabonne/gemma-3-12b-it-abliterated-v2) | 3/100 | 1.04 |
|
||||
| [huihui-ai/gemma-3-12b-it-abliterated](https://huggingface.co/huihui-ai/gemma-3-12b-it-abliterated) | 3/100 | 0.45 |
|
||||
| **[p-e-w/gemma-3-12b-it-heretic](https://huggingface.co/p-e-w/gemma-3-12b-it-heretic) (ours)** | **3/100** | **0.16** |
|
||||
|
||||
## Modify any LLM that you can run on your hardware[^1]
|
||||
The Heretic version, generated without any human effort, achieves the same
|
||||
level of refusal suppression as other abliterations, but at a much lower
|
||||
KL divergence, indicating less damage to the original model's capabilities.
|
||||
*(You can reproduce those numbers using Heretic's built-in evaluation functionality,
|
||||
e.g. `heretic --model google/gemma-3-12b-it --evaluate-model p-e-w/gemma-3-12b-it-heretic`.
|
||||
Note that the exact values might be platform- and hardware-dependent.
|
||||
The table above was compiled using PyTorch 2.8 on an RTX 5090.)*
|
||||
|
||||
[^1]: Heretic supports on-the-fly 4-bit model quantization with bitsandbytes,
|
||||
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.
|
||||
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):
|
||||
|
||||
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.
|
||||
> "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 can, depending on the configuration:
|
||||
> "[**Heretic GPT 20b**](https://huggingface.co/p-e-w/gpt-oss-20b-heretic)
|
||||
> seems to be the best uncensored model I have tried yet. It doesn't destroy a
|
||||
> the model's intelligence and it is answering prompts normally would be
|
||||
> rejected by the base model."
|
||||
> [*(Link to comment)*](https://old.reddit.com/r/LocalLLaMA/comments/1oymku1/heretic_fully_automatic_censorship_removal_for/npe9jng/)
|
||||
|
||||
* **Suppress refusals/remove censorship** (this is the [default action](/config.default.toml))
|
||||
* 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))
|
||||
> "[[**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/)
|
||||
|
||||
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.
|
||||
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/).
|
||||
|
||||
The community has created and published
|
||||
[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]: https://old.reddit.com/r/LocalLLaMA/comments/1sojjoc/abliterlitics_benchmark_and_tensor_analysis/
|
||||
[^3]: https://old.reddit.com/r/LocalLLaMA/comments/1sy18lx/abliterlitics_benchmarks_and_tensor_comparison/
|
||||
|
||||
|
||||
|
||||
<img width="600" alt="Heretic screenshot" src="https://github.com/user-attachments/assets/a030f595-67ef-49a6-9d9a-779fdf752b58" />
|
||||
|
||||
|
||||
[well over 5000](https://huggingface.co/models?other=heretic)
|
||||
models with Heretic.
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
Prepare a Python 3.10+ environment with PyTorch 2.6+ installed as appropriate
|
||||
Prepare a Python 3.10+ environment with PyTorch 2.2+ installed as appropriate
|
||||
for your hardware. Then run:
|
||||
|
||||
```sh
|
||||
@@ -81,176 +91,87 @@ pip install -U heretic-llm
|
||||
heretic Qwen/Qwen3-4B-Instruct-2507
|
||||
```
|
||||
|
||||
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.
|
||||
Replace `Qwen/Qwen3-4B-Instruct-2507` with whatever model you want to decensor.
|
||||
|
||||
> [!IMPORTANT]
|
||||
>
|
||||
> 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.
|
||||
> 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.
|
||||
|
||||
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, processing
|
||||
On an RTX 3090, with the default configuration, decensoring
|
||||
[Qwen3-4B-Instruct-2507](https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507)
|
||||
takes about 30-40 minutes.
|
||||
takes about 20-30 minutes. Note that Heretic supports model quantization with
|
||||
bitsandbytes, which can drastically reduce the amount of VRAM required to process
|
||||
models. Set the `quantization` option to `bnb_4bit` to enable quantization.
|
||||
|
||||
After Heretic has finished processing a model, you are given the choice to
|
||||
After Heretic has finished decensoring a model, you are given the option to
|
||||
save the model, upload it to Hugging Face, chat with it to test how well it works,
|
||||
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 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)).
|
||||
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 ships with two modifiers:
|
||||
Residual directions are computed for each layer as a difference-of-means between
|
||||
the first-token residuals for "harmful" and "harmless" example prompts.
|
||||
|
||||
* **Arbitrary-Rank Ablation (ARA)**[^4]: This is the default modifier, and was
|
||||
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).
|
||||
The ablation process is controlled by several optimizable parameters:
|
||||
|
||||
* **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).
|
||||
* `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:
|
||||
|
||||
[^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)*
|
||||
<img width="800" height="500" alt="Explanation" src="https://github.com/user-attachments/assets/82e4b84e-5a82-4faf-b918-ac642f9e4892" />
|
||||
|
||||
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:
|
||||
|
||||
## 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 in this project so far were written
|
||||
100% by hand, the way I have been doing programming for decades, and while some
|
||||
Heretic contributors use coding agents, I review every single line of code that I
|
||||
merge very carefully. 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 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.
|
||||
* 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.
|
||||
|
||||
|
||||
## Prior art
|
||||
|
||||
I'm aware of the following implementations of abliteration techniques
|
||||
that were publicly available when Heretic was first released (November 2025):
|
||||
I'm aware of the following publicly available implementations of abliteration
|
||||
techniques:
|
||||
|
||||
* [AutoAbliteration](https://huggingface.co/posts/mlabonne/714992455492422)
|
||||
* [abliterator.py](https://github.com/FailSpy/abliterator)
|
||||
@@ -267,13 +188,11 @@ 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, such as
|
||||
the use of non-constant ablation weights
|
||||
as well as some details from the model cards of his own abliterated models (see above)
|
||||
* 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
|
||||
@@ -283,7 +202,7 @@ If you use Heretic for your research, please cite it using the following BibTeX
|
||||
```bibtex
|
||||
@misc{heretic,
|
||||
author = {Weidmann, Philipp Emanuel},
|
||||
title = {Heretic: Training-free language model modification},
|
||||
title = {Heretic: Fully automatic censorship removal for language models},
|
||||
year = {2025},
|
||||
publisher = {GitHub},
|
||||
journal = {GitHub repository},
|
||||
@@ -311,10 +230,3 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
**By contributing to this project, you agree to release your
|
||||
contributions under the same license.**
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
# Rename this file to config.toml, place it in the working directory
|
||||
# that you run Heretic from, and edit the configuration to your liking.
|
||||
#
|
||||
# BERTClassifier scorer instead of the default KeywordRate.
|
||||
# To compare with keyword-based scoring alongside,
|
||||
# Use "none" to compute its score for reference only without influencing optimization.
|
||||
# Or use "minimize" to use its scores for optimization as well.
|
||||
#
|
||||
# { plugin = "heretic.scorers.keyword_rate.KeywordRate", optimization = "none" }
|
||||
|
||||
scorers = [
|
||||
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" },
|
||||
{ plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" },
|
||||
]
|
||||
@@ -217,71 +217,6 @@ 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"
|
||||
|
||||
# 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"
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
# Rename this file to config.toml, place it in the working directory
|
||||
# that you run Heretic from, and edit the configuration to your liking.
|
||||
#
|
||||
# BERTClassifier scorer for personality/emotion steering.
|
||||
#
|
||||
# This uses a DistilRoBERTa model fine-tuned on emotion classification
|
||||
# and allows minimizing or maximizing specific emotions in the model's responses.
|
||||
#
|
||||
# Example use: configure two scorer instances, one to minimize negative emotions
|
||||
# (e.g. anger, disgust, fear, sadness) and one to maximize positive emotions
|
||||
# (e.g joy, surprise) or vice versa.
|
||||
#
|
||||
# This can be done in one of the two ways:
|
||||
#
|
||||
# 1. Multi‑objective steering:
|
||||
# Here, we use two instances: `negative_emotions` and `positive_emotions` with
|
||||
# `optimization = "minimize"` and `optimization = "maximize"` respectively.
|
||||
#
|
||||
# Minimizing the first score pushes the model *away* from those negative emotions.
|
||||
# Maximizing the second score pushes the model *towards* those emotions.
|
||||
#
|
||||
# 2. Single‑objective steering:
|
||||
# With two instances, heretic builds a Pareto front that **balances** both objectives above.
|
||||
# Due to which, the model learns to be less angry *and* more joyful **simultaneously**.
|
||||
#
|
||||
# With only one instance, we have only one objective which can be either minimized or maximized.
|
||||
# Due to which, the model will reduce anger, but it *may* drift towards **anything** that lowers
|
||||
# the other most natural instincts (e.g. neutral, overly polite, or wierdly happy).
|
||||
#
|
||||
# With the first method, you can expect to control both objectives effectively,
|
||||
# which is the recommended method and is the default.
|
||||
# With the second method, you can only *hope* and *assume* the most expected common/natural
|
||||
# behavior, depending upon what you tried to "minimize" or "maximize".
|
||||
scorers = [
|
||||
{ plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" },
|
||||
# Scorer to minimize negative emotions.
|
||||
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize", instance_name = "negative_emotions" },
|
||||
# Scorer to maximize positive emotions.
|
||||
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "maximize", instance_name = "positive_emotions" },
|
||||
]
|
||||
|
||||
modified_model_type = "happiness-increased"
|
||||
|
||||
upload_tags = [
|
||||
"personality-steering",
|
||||
"emotion-steering",
|
||||
]
|
||||
|
||||
# Dataset of prompts used for steering, which tends to produce
|
||||
# the target emotion you want to influence.
|
||||
# For example:
|
||||
# - For minimizing anger: prompts about creative writing which involves those emotions.
|
||||
# - For maximizing joy: prompts about celebrations, happy scenarios, good news from user, etc.
|
||||
[modifier.ARA.good_prompts]
|
||||
dataset = "VINAY-UMRETHE/Positive-Prompts"
|
||||
split = "train[:200]"
|
||||
column = "prompt"
|
||||
|
||||
[modifier.ARA.bad_prompts]
|
||||
dataset = "VINAY-UMRETHE/Negative-Prompts"
|
||||
split = "train[:200]"
|
||||
column = "prompt"
|
||||
|
||||
|
||||
[scorer.BERTClassifier_negative_emotions]
|
||||
# Name that describes what the configured match rate measures.
|
||||
score_name = "Minimize"
|
||||
|
||||
# Hugging Face model ID, or path to a text-classification model on disk.
|
||||
model = "j-hartmann/emotion-english-distilroberta-base"
|
||||
|
||||
# Hugging Face commit hash of the classifier model.
|
||||
# Set this to pin a specific revision; unset means the latest revision
|
||||
# is auto-pinned and recorded when the classifier is loaded.
|
||||
# When reproducing, the recorded revision is restored and used.
|
||||
# model_commit = "<commit-hash>"
|
||||
|
||||
# Labels predicted by the classifier that identify a response as a match.
|
||||
# We want to minimize these emotions.
|
||||
match_labels = ["anger", "disgust", "fear", "sadness"]
|
||||
|
||||
# Number of prompt/response pairs to classify in parallel.
|
||||
batch_size = 16
|
||||
|
||||
# Maximum number of tokens per classifier input (longer inputs are truncated).
|
||||
max_length = 512
|
||||
|
||||
# Whether to pass inputs as prompt/response text pairs.
|
||||
# Requires a model trained on pairs (e.g. the default refusal classifier).
|
||||
# Set to False when using a single-sequence text-classification model
|
||||
# to evaluate the response string only (e.g. sentiment analysis).
|
||||
use_text_pairs = false
|
||||
|
||||
# Whether to print prompt/response pairs and their predicted labels.
|
||||
print_responses = true
|
||||
|
||||
# Dataset of prompts to evaluate the match rate on.
|
||||
# Use a dataset that tends to produce the target emotions (anger, disgust, fear, sadness).
|
||||
[scorer.BERTClassifier_negative_emotions.prompts]
|
||||
dataset = "VINAY-UMRETHE/Negative-Prompts"
|
||||
split = "train[:100]"
|
||||
column = "prompt"
|
||||
|
||||
|
||||
[scorer.BERTClassifier_positive_emotions]
|
||||
score_name = "Maximize"
|
||||
|
||||
model = "j-hartmann/emotion-english-distilroberta-base"
|
||||
|
||||
# We want to maximize these emotions.
|
||||
match_labels = ["joy", "surprise"]
|
||||
|
||||
batch_size = 16
|
||||
max_length = 512
|
||||
print_responses = true
|
||||
|
||||
[scorer.BERTClassifier_positive_emotions.prompts]
|
||||
dataset = "VINAY-UMRETHE/Positive-Prompts"
|
||||
split = "train[:100]"
|
||||
column = "prompt"
|
||||
@@ -1,67 +0,0 @@
|
||||
# Migrating from Heretic 1.x to Heretic 2.x
|
||||
|
||||
Heretic 2.x is not backwards compatible with Heretic 1.x configurations.
|
||||
|
||||
If you have existing configuration files written to work with a Heretic 1.x release,
|
||||
you need to make the following changes before using them with a Heretic 2.x release.
|
||||
Only settings that are actually in your configuration file must be updated;
|
||||
defaults are automatically set to the current values. Of course, you can also simply
|
||||
start with [an up-to-date default configuration](/config.default.toml), and modify
|
||||
it to match your requirements.
|
||||
|
||||
|
||||
## Remove settings for research features
|
||||
|
||||
Research features have been removed in Heretic 2.0. The following settings
|
||||
are no longer recognized:
|
||||
|
||||
* `print_residual_geometry`
|
||||
* `plot_residuals`
|
||||
* `residual_plot_path`
|
||||
* `residual_plot_title`
|
||||
* `residual_plot_style`
|
||||
* `residual_plot_label` and `residual_plot_color` in prompt sections
|
||||
|
||||
|
||||
## Remove `kl_divergence_scale` and `kl_divergence_target`
|
||||
|
||||
KL divergence balancing has been removed and these settings
|
||||
are no longer recognized.
|
||||
|
||||
|
||||
## Rename `chain_of_thought_skips` to `chain_of_thought_blocks` and update its structure
|
||||
|
||||
The new setting `chain_of_thought_blocks` contains pairs of the form
|
||||
`[cot_initializer, cot_finalizer]` instead of `[cot_initializer, closed_cot_block]`.
|
||||
|
||||
|
||||
## Move abliteration settings to the `[modifier.Abliteration]` section
|
||||
|
||||
This includes the following settings:
|
||||
|
||||
* `orthogonalize_direction`
|
||||
* `row_normalization`
|
||||
* `full_normalization_lora_rank`
|
||||
* `winsorization_quantile`
|
||||
* `[good_prompts]` (renamed to `[modifier.Abliteration.good_prompts]`)
|
||||
* `[bad_prompts]` (renamed to `[modifier.Abliteration.bad_prompts]`)
|
||||
|
||||
> [!IMPORTANT]
|
||||
>
|
||||
> Heretic 2.x defaults to using ARA for modifying models, not abliteration.
|
||||
> To continue using abliteration, edit the `modifiers` setting accordingly.
|
||||
> To configure ARA, edit the `[modifier.ARA]` section.
|
||||
|
||||
|
||||
## Move refusal evaluation settings to the `[scorer.KeywordRate]` section
|
||||
|
||||
This includes the following settings:
|
||||
|
||||
* `print_responses`
|
||||
* `refusal_markers` (renamed to `keyword_markers`)
|
||||
* `[bad_evaluation_prompts]` (renamed to `[scorer.KeywordRate.prompts]`)
|
||||
|
||||
|
||||
## Rename `[good_evaluation_prompts]` to `[scorer.KLDivergence.prompts]`
|
||||
|
||||
KL divergence is now computed by a scorer plugin.
|
||||
+5
-7
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "heretic-llm"
|
||||
version = "2.1.0.dev0"
|
||||
description = "Training-free language model modification"
|
||||
version = "2.0.0.dev0"
|
||||
description = "Fully automatic censorship removal for language models"
|
||||
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 :: 5 - Production/Stable",
|
||||
"Development Status :: 4 - Beta",
|
||||
"Environment :: Console",
|
||||
"Environment :: GPU",
|
||||
"Intended Audience :: Science/Research",
|
||||
@@ -19,9 +19,6 @@ 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",
|
||||
@@ -75,7 +72,8 @@ ignore = [
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
# TODO: Re-enable before 2.0 release!
|
||||
#exclude-newer = "7 days"
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch" }
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
|
||||
|
||||
# Generic text-classification scorer: classifies each response with a
|
||||
# text-classification model and counts the responses whose
|
||||
# predicted label is one of the `match_labels`, as an alternative to the
|
||||
# `keyword_markers` of the KeywordRate scorer.
|
||||
#
|
||||
# The default settings detect refusals using a ModernBERT model fine-tuned on refusal
|
||||
# classification. Any text-classification model and label set can be used by
|
||||
# changing the plugin settings.
|
||||
#
|
||||
# For more information, see:
|
||||
# Implementation: https://github.com/p-e-w/heretic/pull/500
|
||||
# Default classifier model: https://huggingface.co/VINAY-UMRETHE/Refusal-Classifier
|
||||
|
||||
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",
|
||||
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):
|
||||
# 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)
|
||||
]
|
||||
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]
|
||||
+1
-1
@@ -32,7 +32,7 @@ sha256sum * | Out-File -Encoding utf8NoBOM ../SHA256SUMS.LABEL
|
||||
**Verify with**:
|
||||
|
||||
```bash
|
||||
Get-Command sha256sum
|
||||
Get-Command sha256sum`
|
||||
```
|
||||
|
||||
**Expected**:
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
|
||||
f8f1fd0ef18d709772584f1a4d736fc8f31aafee83a001b34d333c30a606baf8 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json
|
||||
@@ -1,4 +0,0 @@
|
||||
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
|
||||
2b0b38f5cc5b25e424dc944cf0b27432f736cffd59a8753f2ddd23f5434e5ab4 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json
|
||||
@@ -1,4 +0,0 @@
|
||||
7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json
|
||||
ad8c373f6d6f3f00e646d118116fc1f34c91c5c67a10db6fe9366fd34f534df5 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json
|
||||
@@ -1,4 +0,0 @@
|
||||
5595714af3f245d20831e545ee5ee41fec8f4ad5a89d9ca5abce0bf476debfa7 *config.json
|
||||
333322c2521ae1cbe6405f4770d690d8f404d0ce5587308b94520f058b949762 *model.safetensors
|
||||
daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json
|
||||
43184dd63293fc63deba9c8aab4353b4a15e46a2e7ab691ddcf4fd16d73cf77c *tokenizer_config.json
|
||||
@@ -1,76 +0,0 @@
|
||||
# This test case is for the BERTClassifier scorer plugin.
|
||||
# After any change related to it, this test should PASS.
|
||||
|
||||
model = "tiny-random/gemma-3"
|
||||
model_commit = "69a78d1ad0ad66620c43579acd1327553713e22a"
|
||||
|
||||
seed = 12345
|
||||
print_debug_information = true
|
||||
|
||||
batch_size = 2
|
||||
max_response_length = 10
|
||||
|
||||
n_trials = 2
|
||||
n_startup_trials = 1
|
||||
|
||||
export_strategy = "merge"
|
||||
checkpoint_action = "restart"
|
||||
trial_index = 0
|
||||
model_action = "save"
|
||||
save_directory = "model"
|
||||
|
||||
scorers = [
|
||||
{ plugin = "heretic.scorers.keyword_rate.KeywordRate", optimization = "none" },
|
||||
{ plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" },
|
||||
{ plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" },
|
||||
]
|
||||
|
||||
[[response_prefix_test_prompts]]
|
||||
dataset = "mlabonne/harmless_alpaca"
|
||||
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
|
||||
split = "train[:5]"
|
||||
column = "text"
|
||||
|
||||
[[response_prefix_test_prompts]]
|
||||
dataset = "mlabonne/harmful_behaviors"
|
||||
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
|
||||
split = "train[:5]"
|
||||
column = "text"
|
||||
|
||||
[scorer.KLDivergence.prompts]
|
||||
dataset = "mlabonne/harmless_alpaca"
|
||||
commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f"
|
||||
split = "test[:5]"
|
||||
column = "text"
|
||||
|
||||
[scorer.KeywordRate]
|
||||
print_responses = true
|
||||
|
||||
[scorer.KeywordRate.prompts]
|
||||
dataset = "mlabonne/harmful_behaviors"
|
||||
commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7"
|
||||
split = "test[:5]"
|
||||
column = "text"
|
||||
|
||||
[scorer.BERTClassifier]
|
||||
model = "VINAY-UMRETHE/tiny-refusal-classifier"
|
||||
model_commit = "ca106855daaa6d695bd2a66934eb1a40cbd3f18a"
|
||||
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"
|
||||
@@ -18,10 +18,6 @@ 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"
|
||||
@@ -1082,7 +1078,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "heretic-llm"
|
||||
version = "2.1.0.dev0"
|
||||
version = "2.0.0.dev0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "accelerate" },
|
||||
|
||||
Reference in new issue
Block a user