Metadata-Version: 2.4
Name: autofit2
Version: 1.0.0
Summary: Few-shot text classification with sentence-transformers: contrastive fine-tuning, shortcut detection, model cards, ONNX export and serving
Author: Stefan Pernes
License-Expression: MIT
Project-URL: Homepage, https://github.com/neospe/autofit2
Project-URL: Issues, https://github.com/neospe/autofit2/issues
Keywords: few-shot,text classification,sentence-transformers,setfit,content moderation,onnx
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: sentence-transformers<7,>=6.3
Requires-Dist: transformers>=5
Requires-Dist: datasets
Requires-Dist: accelerate
Requires-Dist: codecarbon
Requires-Dist: scikit-learn
Requires-Dist: joblib
Requires-Dist: pandas
Requires-Dist: numpy
Requires-Dist: torch>=2.14
Provides-Extra: dataload
Requires-Dist: dataload>=0.3; extra == "dataload"
Provides-Extra: onnx
Requires-Dist: onnx>=1.23; extra == "onnx"
Requires-Dist: onnxscript; extra == "onnx"
Requires-Dist: onnxruntime>=1.26; extra == "onnx"
Requires-Dist: tokenizers; extra == "onnx"
Dynamic: license-file


# autofit2

[![Hacker News rank via HackerGit](https://hackergit.org/badge/neospe/autofit2.svg?style=rank)](https://hackergit.org/r/neospe/autofit2)

Few-shot text classification. Massively multilingual (50+ languages), fully automated pipeline built on `setfit` and SBERT embeddings.

## Key Features

*   **Few-Shot Learning:** High precision (95–99%) with a few dozen labeled examples.
*   **Multilingual Support:** Pretrained models for 20 languages; evaluation corpora for 50+. Scalable to 100+ via Common Crawl.
*   **Automated Pipeline:** End-to-end preprocessing, fine-tuning, evaluation, and deployment from a single JSON config.
*   **Reproducibility & Transparency:** Model cards and CO₂ tracking for every run.
*   **Shortcut Detection:** Flags words the model learned to rely on and optionally retrains without them (see below).

## Quickstart

Train an English moderation model on a 2% sample of [Davidson et al.](https://huggingface.co/datasets/tdavidson/hate_speech_offensive), with one benchmark target:

```bash
pip install autofit2
curl -O https://raw.githubusercontent.com/neospe/autofit2/master/examples/demo.json  # the config is moved to history/ after the run
autofit2 demo.json
```

pip puts the `autofit2`, `autofit2-export` and `autofit2-serve` commands into the active environment, so use a virtual environment (`python -m venv .venv && . .venv/bin/activate`), or install them as a tool with [uv](https://docs.astral.sh/uv/), in an environment of their own with the commands on your `PATH`:

```bash
uv tool install "autofit2[onnx]"   # add dataload as well: "autofit2[onnx,dataload]"
```

Runs on CUDA, Apple silicon (MPS) or CPU; about 12 minutes on an M1. The dataset and the base model (`all-MiniLM-L6-v2`) are downloaded from the Hugging Face Hub on the first run. From a clone: `pip install -e .`, then `autofit2 examples/demo.json` works the same way (copy the config first, it is moved after the run).

Output:
*   `history/demo.log`: accuracy and F1 per target.
*   `models-out/demo-mod-en.json`: model card with benchmarks, self-consistency, emissions and a bias evaluation: on neutral sentences, one per identity or occupation term (`eval-data`, included for 50+ languages; a local `eval-data/` folder takes precedence), the false positive rate and the flagged terms, and each term's received attention relative to the base model (terms the fine-tuned model attends to much more are candidates for shortcuts).
*   `models-in/demo-mod-en`: the fine-tuned embedding (sentence-transformers folder), usable as a base model for custom targets.
*   `models-in/demo-mod-en.joblib`: the classifier on its embeddings.

Or in a container:

```bash
docker build -t autofit2 .
docker run --rm -v "$PWD":/service autofit2 autofit2 demo.json
```

### Serving

Export the embedding to ONNX and the classifier to a weight file, then serve them over HTTP:

```bash
pip install "autofit2[onnx]"  # or: uv tool install "autofit2[onnx]"
autofit2-export models-in/demo-mod-en onnx/demo-mod-en models-in/demo-mod-en.joblib
docker build -f packaging/Dockerfile.serve -t autofit2-serve .  # in a clone of this repository
docker run --rm -p 8080:8080 -v "$PWD/onnx":/models:ro autofit2-serve
curl -d '{"model id": "demo-mod-en", "queries": ["have a nice day"]}' localhost:8080
```

The reply has the probability of class 1 for each text, or with more than two classes the probability of each class (`[{"hate": 0.02, "offensive": 0.11, "neither": 0.87}]`); `GET /health` lists the models and their classes. The export checks its output against sentence-transformers and `predict_proba`. One container serves all exports under `/models`, and needs only onnxruntime, tokenizers and numpy (319 MB image). A custom model trained on a base embedding only adds a classifier, `autofit2-export --heads onnx/demo-mod-en models-in/<model id>.joblib`, which is picked up without a restart. Settings are listed in `src/autofit2/serve.py`; without Docker, `MODELS=onnx autofit2-serve` (or `python serve.py` with only `packaging/requirements-serve.txt` installed).

Requests are batched, which pays off on GPUs. Build with `--build-arg ONNXRUNTIME="onnxruntime-gpu[cuda,cudnn]"` (about 3 GB image, mostly CUDA libraries; Turing or newer, driver 580 or later) and run with `--gpus all -e DEVICE=cuda -e GPUS=0,1`. Older GPUs and drivers need CUDA 12, see `packaging/Dockerfile.serve`. On two GTX 1080 Ti, two MiniLM models served 2,900 texts per second to 32 clients, against 1,200 without batching and 220 on an 8-core CPU.

To publish and scale the models, run the container with [autoops](https://github.com/neospe/autoops): `packaging/Dockerfile.serve` becomes `dockerfiles/autofit2-serve/Dockerfile` (next to `src/autofit2/serve.py`), and the service goes into the workers' compose file with Traefik labels and `kop.merge-lbs=true`, as in autoops' `examples/dockerfiles/worker.yml`. Every worker that runs the container is then picked up and load balanced automatically, with `/health` as the health check.

## Shortcut Detection

![A planted shortcut](https://raw.githubusercontent.com/neospe/autofit2/master/shortcut.svg)

After fine-tuning, autofit2 ranks words by how much more attention the model pays to them than the base model; words a classifier merely learned to associate with a label stand out. With `"mask shortcuts": true`, those not in your wordlists of words the model may rely on are removed and the model is trained again. The ranking is also part of every model card. Method: *Attention Shows the Shortcut: Detect-then-Mask Debiasing for SetFit*.

## Usage

**1. Prepare Data**
Point the config's loaders at a dataset on the Hugging Face Hub or a local file, or use the moderation corpora of [dataload](https://github.com/neospe/dataload) (`pip install "autofit2[dataload]"`). See Loaders below.

**2. Configure**
Create `myproject.json` specifying dataset paths, model settings, and output directories. Supports multi-language/task blocks.

**3. Run**

The pipeline supports resumable execution.

```bash
autofit2 myproject.json
```

**4. Output**
*   Fine-tuned embedding and classifier, exportable to ONNX and served from a container (see Serving).
*   Generated model card (training details, intended use, performance metrics, bias evaluation).


## Configuration

`myproject.json` defines the training parameters. Its structure depends on the target type: **Base Models** (`all`) or **Custom Models** (`custom`).

### General Structure

```json
{
  "<task-key>": {
    "<language-key>": {
      "base": {
        "model file": "<path>",          // Relative path, no trailing slash (e.g. "models-in/all-MiniLM-L6-v2")
        "model type": "<string>",          // e.g., "bert"
        "pretraining task": "<string>",  // e.g., "sentence similarity"
        "downstream task": "<string>"    // e.g., "binary text classification"
      },
      "targets": {
        "<id-key>": { ... }             // See Target Options below
      }
    }
  }
}
```

### Target Types

The `"targets"` dictionary supports three specific key types:

1.  **`all`** (Base Model)
    *   Generates a full set of artifacts: model folder, classifier, and card.
    *   **Model ID:** Derived from the config filename (`{config_name}-{task}-{lang}`). The config filename must be stable.
2.  **`custom`** (Custom Model)
    *   Generates a full set of artifacts: model folder, classifier, and card.
    *   **Model ID:** can be auto-generated as a 14–16 character lowercase alphanumeric string.
3.  **`benchmark 1..N`** (Benchmarking Only)
    *   Does **not** generate model artifacts.
    *   Outputs only score logs.
    *   Must be used in conjunction with an `all` target to produce output.

### Target Options

Each entry in the `"targets"` dictionary supports `description`, `link`, `loader` and an optional `options` object:

```json
"custom": {
  "options": {"train embedding": false, "base clf": "98sdfkjhw3r8sf"},
  "loader": ["en_hate1()"]
}
```

| Key | Type | Description |
| :--- | :--- | :--- |
| `description` | `string` | Free-form description of the target. |
| `link` | `string` | URL to source data or documentation. |
| `options` → `train embedding` | `bool` | Fine-tune embeddings during training (default: `true`). |
| `options` → `base clf` | `string` | ID string pointing to a `.joblib` file located in `BASE_PATH`. Must match exactly. |
| `options` → `sample ratio` | `float` | Random sample of total data for full training (e.g., `0.5` = 50%). |
| `options` → `embedding sample ratio` | `float` | Random sample of data used **only** for embedding fine-tuning (e.g., `0.1` = 10%). |
| `options` → `neutral class` | `int` or `string` | The class of harmless texts, for the bias evaluation (default: `0` with classes 0 and 1, else none). |
| `options` → `mask shortcuts` | `bool` | Detect-then-mask (default: `false`): after a first fine-tune, the words whose received attention grew most (up to 50, at least 1.2 times their share in the base model) are checked against wordlists of words the model may rely on, which you provide in `wordlists/<lang>/` (plain text, one word per line; e.g. profanity, slur and insult lists for moderation, a sentiment lexicon for sentiment); identity terms from `eval-data/<lang>-corpus.tsv` never count as legitimate. The other words are removed from the training texts and the embedding is fine-tuned again (about twice the training time). The model card lists masked and kept words. Removes shortcut words; it cannot fix bias in the labels. |

### Loaders

The `"loader"` field defines how data is ingested and transformed. It expects a list of commands (functions or transformations):

```json
"loader": ["command_1", "command_2"]
```

*   **Command Definition:** Each command must return a list of dictionaries with keys `text` and `label`. Commands can be raw loader functions or wrapped transformations (e.g., list comprehensions, lambdas).
*   **Built-in Loaders:** `labels` maps the dataset's labels to classes, ints or strings: it names them (`{0: 'hate', 1: 'offensive', 2: 'neither'}`), merges them (`{0: 1, 1: 1, 2: 0}`) or selects them, as texts with labels missing from the mapping are left out (`{'negative': 1, 'positive': 0}` drops `neutral`). Without `labels`, the dataset's labels are the classes. Two classes or more, see Multiple Classes below.
    *   `hf(name, split='train', text='text', label='label', labels=None, subset=None, revision=None)`: a dataset from the Hugging Face Hub, e.g. `"hf('tdavidson/hate_speech_offensive', text='tweet', label='class', labels={0: 1, 1: 1, 2: 0})"`.
    *   `csv(path, text='text', label='label', labels=None, sep=',')` and `jsonl(path, text='text', label='label', labels=None)`: local files.
    *   With `pip install "autofit2[dataload]"`, the loaders of [dataload](https://github.com/neospe/dataload) for moderation corpora (e.g. `en_hate1()`, `el_offense20()`) are available as well, with their label names mapped to 0 and 1.
*   **Data Splitting Logic:**
    *   **If 2 commands AND target != `all`:**
        *   Command 1 → Training Data
        *   Command 2 → Evaluation Data
    *   **Else (Target = `all`):**
        *   All commands are concatenated into a single dataset.
        *   Split: **100/100** (No split; entire set used for training).
    *   **Else (Other Targets, e.g., `custom` or benchmarks with 1 command):**
        *   All commands are concatenated into a single dataset.
        *   Split: **70/30** (Train/Test).
*   **Custom Commands:** a command is a Python expression over the loaders above and the builtins, so loaders can be filtered, transformed and combined in place. It sees the loaded rows, i.e. `text` and the label already mapped to its class; select classes with `labels`, and prepare a csv or jsonl file for anything that needs other columns:
    ```json
    "loader": [
      "[r for r in csv('posts.csv', labels={'spam': 1, 'ham': 0}) if len(r['text']) < 280]",
      "[{'text': r['text'].lower(), 'label': r['label']} for r in hf('some/dataset')]",
      "hf('some/dataset') + jsonl('extra.jsonl')"
    ]
    ```
    A config is code: only run configs you trust.

### Multiple Classes

A target can have any number of classes; the contrastive fine-tuning pairs texts of the same class and of different classes, and the classifier gives a probability for each class. Name the classes with `labels`, and for a bias evaluation, set the class of harmless texts:

```json
"all": {
  "options": {"neutral class": "neither"},
  "loader": ["hf('tdavidson/hate_speech_offensive', text='tweet', label='class', labels={0: 'hate', 1: 'offensive', 2: 'neither'})"]
}
```

The model card lists the classes; F1 is the macro F1 (the mean over classes), and the bias evaluation counts a neutral sentence as flagged if it lands in any other class, with the class in `flagged as`. Without a neutral class, it gives the number of neutral sentences per class.

For texts that can belong to several classes at once, train one target per class against all the others (one-vs-rest) instead, e.g. as task keys `sports`, `politics` and `tech` with `labels={'sports': 1, 'politics': 0, 'tech': 0}` and so on, and keep every class whose score passes a threshold. Cheaper than an `all` target per class, which fine-tunes an embedding each: fine-tune one embedding, then train a `custom` target per class on it with `"train embedding": false` (a second job, as `all` and `custom` cannot be combined); each class only adds a classifier, served from the same ONNX export with `autofit2-export --heads`, and classes can be added later without retraining the others.

## Configuration Example

```json
{
  "mod": {
    "el": {
      "base": {
        "model file": "models-in/paraphrase-multilingual-MiniLM-L12-v2",
        "model type": "bert",
        "pretraining task": "sentence similarity",
        "downstream task": "binary text classification"
      },
      "targets": {
        "benchmark 1": {
          "description": "Pitenis et al. - Offensive Language Identification in Greek",
          "link": "https://arxiv.org/abs/2003.07459",
          "loader": [
            "el_offense20(files=['offenseval2020-greek/offenseval-gr-training-v1/offenseval-gr-training-v1.tsv'])",
            "el_offense20(files=['offenseval2020-greek/offenseval-gr-testsetv1/offenseval-gr-test-v1-combined.tsv'])"
          ]
        },
        "all": {
          "loader": [
            "el_offense20()"
          ]
        }
      }
    }
  }
}
```

### Breakdown: Finetuning a Sentence Transformer

To fine-tune a base model for a specific task and language, define a config block like the one below. This example sets up a text moderation (mod) pipeline for Greek (el) using a multilingual sentence transformer.

**Base Model Setup**

```json
"base": {
  "model file": "models-in/paraphrase-multilingual-MiniLM-L12-v2",
  "model type": "bert",
  "pretraining task": "sentence similarity",
  "downstream task": "binary text classification"
}
```
- Model file: Path to the pretrained transformer.
- Model type: Architecture type (e.g., BERT).
- Pretraining task: Original task the model was trained on.
- Downstream task: Task you're adapting it to (e.g., moderation, sentiment analysis).

**Targets**

You can specify multiple finetuning targets. Each target defines a dataset and training strategy.

1. `benchmark 1`
```json
"benchmark 1": {
  "description": "Pitenis et al. - Offensive Language Identification in Greek",
  "link": "https://arxiv.org/abs/2003.07459",
  "loader": [
    "el_offense20(files=['offenseval2020-greek/offenseval-gr-training-v1/offenseval-gr-training-v1.tsv'])",
    "el_offense20(files=['offenseval2020-greek/offenseval-gr-testsetv1/offenseval-gr-test-v1-combined.tsv'])"
  ]
}
```
- Uses a train/test split for evaluation.
- Based on a published benchmark dataset.

2. `all`
```json
"all": {
  "loader": ["el_offense20()"]
}
```
- Uses the full dataset for training.
- No explicit evaluation—this is for production-grade finetuning.

