autofit2 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- autofit2-1.0.0/LICENSE +9 -0
- autofit2-1.0.0/PKG-INFO +314 -0
- autofit2-1.0.0/README.md +278 -0
- autofit2-1.0.0/pyproject.toml +52 -0
- autofit2-1.0.0/setup.cfg +4 -0
- autofit2-1.0.0/src/autofit2/__init__.py +3 -0
- autofit2-1.0.0/src/autofit2/__main__.py +3 -0
- autofit2-1.0.0/src/autofit2/eval-data/ar-corpus.tsv +184 -0
- autofit2-1.0.0/src/autofit2/eval-data/ar-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/bg-corpus.tsv +153 -0
- autofit2-1.0.0/src/autofit2/eval-data/bg-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ca-corpus.tsv +213 -0
- autofit2-1.0.0/src/autofit2/eval-data/ca-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/cs-corpus.tsv +142 -0
- autofit2-1.0.0/src/autofit2/eval-data/cs-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/da-corpus.tsv +224 -0
- autofit2-1.0.0/src/autofit2/eval-data/da-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/de-corpus.tsv +234 -0
- autofit2-1.0.0/src/autofit2/eval-data/de-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/el-corpus.tsv +200 -0
- autofit2-1.0.0/src/autofit2/eval-data/el-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/en-corpus.tsv +241 -0
- autofit2-1.0.0/src/autofit2/eval-data/en-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/es-corpus.tsv +233 -0
- autofit2-1.0.0/src/autofit2/eval-data/es-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/et-corpus.tsv +174 -0
- autofit2-1.0.0/src/autofit2/eval-data/et-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/fa-corpus.tsv +189 -0
- autofit2-1.0.0/src/autofit2/eval-data/fa-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/fi-corpus.tsv +221 -0
- autofit2-1.0.0/src/autofit2/eval-data/fi-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/fr-corpus.tsv +228 -0
- autofit2-1.0.0/src/autofit2/eval-data/fr-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/gl-corpus.tsv +217 -0
- autofit2-1.0.0/src/autofit2/eval-data/gl-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/gu-corpus.tsv +177 -0
- autofit2-1.0.0/src/autofit2/eval-data/gu-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/he-corpus.tsv +94 -0
- autofit2-1.0.0/src/autofit2/eval-data/he-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/hi-corpus.tsv +182 -0
- autofit2-1.0.0/src/autofit2/eval-data/hi-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/hr-corpus.tsv +196 -0
- autofit2-1.0.0/src/autofit2/eval-data/hr-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/hu-corpus.tsv +217 -0
- autofit2-1.0.0/src/autofit2/eval-data/hu-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/hy-corpus.tsv +196 -0
- autofit2-1.0.0/src/autofit2/eval-data/hy-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/id-corpus.tsv +178 -0
- autofit2-1.0.0/src/autofit2/eval-data/id-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/it-corpus.tsv +224 -0
- autofit2-1.0.0/src/autofit2/eval-data/it-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ja-corpus.tsv +199 -0
- autofit2-1.0.0/src/autofit2/eval-data/ja-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ka-corpus.tsv +184 -0
- autofit2-1.0.0/src/autofit2/eval-data/ka-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ko-corpus.tsv +111 -0
- autofit2-1.0.0/src/autofit2/eval-data/ko-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ku-corpus.tsv +170 -0
- autofit2-1.0.0/src/autofit2/eval-data/ku-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/lt-corpus.tsv +177 -0
- autofit2-1.0.0/src/autofit2/eval-data/lt-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/lv-corpus.tsv +209 -0
- autofit2-1.0.0/src/autofit2/eval-data/lv-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/mk-corpus.tsv +214 -0
- autofit2-1.0.0/src/autofit2/eval-data/mk-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/mn-corpus.tsv +156 -0
- autofit2-1.0.0/src/autofit2/eval-data/mn-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/mr-corpus.tsv +153 -0
- autofit2-1.0.0/src/autofit2/eval-data/mr-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ms-corpus.tsv +197 -0
- autofit2-1.0.0/src/autofit2/eval-data/ms-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/my-corpus.tsv +119 -0
- autofit2-1.0.0/src/autofit2/eval-data/my-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/nl-corpus.tsv +228 -0
- autofit2-1.0.0/src/autofit2/eval-data/nl-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/no-corpus.tsv +216 -0
- autofit2-1.0.0/src/autofit2/eval-data/no-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/pl-corpus.tsv +217 -0
- autofit2-1.0.0/src/autofit2/eval-data/pl-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/pt-corpus.tsv +226 -0
- autofit2-1.0.0/src/autofit2/eval-data/pt-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ro-corpus.tsv +220 -0
- autofit2-1.0.0/src/autofit2/eval-data/ro-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ru-corpus.tsv +221 -0
- autofit2-1.0.0/src/autofit2/eval-data/ru-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/sk-corpus.tsv +121 -0
- autofit2-1.0.0/src/autofit2/eval-data/sk-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/sl-corpus.tsv +162 -0
- autofit2-1.0.0/src/autofit2/eval-data/sl-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/sq-corpus.tsv +163 -0
- autofit2-1.0.0/src/autofit2/eval-data/sq-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/sr-corpus.tsv +166 -0
- autofit2-1.0.0/src/autofit2/eval-data/sr-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/sv-corpus.tsv +225 -0
- autofit2-1.0.0/src/autofit2/eval-data/sv-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/th-corpus.tsv +182 -0
- autofit2-1.0.0/src/autofit2/eval-data/th-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/tr-corpus.tsv +202 -0
- autofit2-1.0.0/src/autofit2/eval-data/tr-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/uk-corpus.tsv +153 -0
- autofit2-1.0.0/src/autofit2/eval-data/uk-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/ur-corpus.tsv +187 -0
- autofit2-1.0.0/src/autofit2/eval-data/ur-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/vi-corpus.tsv +199 -0
- autofit2-1.0.0/src/autofit2/eval-data/vi-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/eval-data/zh-corpus.tsv +159 -0
- autofit2-1.0.0/src/autofit2/eval-data/zh-terms.txt +242 -0
- autofit2-1.0.0/src/autofit2/export_onnx.py +141 -0
- autofit2-1.0.0/src/autofit2/loaders.py +50 -0
- autofit2-1.0.0/src/autofit2/serve.py +226 -0
- autofit2-1.0.0/src/autofit2/train.py +553 -0
- autofit2-1.0.0/src/autofit2.egg-info/PKG-INFO +314 -0
- autofit2-1.0.0/src/autofit2.egg-info/SOURCES.txt +115 -0
- autofit2-1.0.0/src/autofit2.egg-info/dependency_links.txt +1 -0
- autofit2-1.0.0/src/autofit2.egg-info/entry_points.txt +4 -0
- autofit2-1.0.0/src/autofit2.egg-info/requires.txt +19 -0
- autofit2-1.0.0/src/autofit2.egg-info/top_level.txt +1 -0
autofit2-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright © 2019 Stefan Pernes <stefan@pernes.net>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
autofit2-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: autofit2
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Few-shot text classification with sentence-transformers: contrastive fine-tuning, shortcut detection, model cards, ONNX export and serving
|
|
5
|
+
Author: Stefan Pernes
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/neospe/autofit2
|
|
8
|
+
Project-URL: Issues, https://github.com/neospe/autofit2/issues
|
|
9
|
+
Keywords: few-shot,text classification,sentence-transformers,setfit,content moderation,onnx
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: sentence-transformers<7,>=6.3
|
|
19
|
+
Requires-Dist: transformers>=5
|
|
20
|
+
Requires-Dist: datasets
|
|
21
|
+
Requires-Dist: accelerate
|
|
22
|
+
Requires-Dist: codecarbon
|
|
23
|
+
Requires-Dist: scikit-learn
|
|
24
|
+
Requires-Dist: joblib
|
|
25
|
+
Requires-Dist: pandas
|
|
26
|
+
Requires-Dist: numpy
|
|
27
|
+
Requires-Dist: torch>=2.14
|
|
28
|
+
Provides-Extra: dataload
|
|
29
|
+
Requires-Dist: dataload>=0.3; extra == "dataload"
|
|
30
|
+
Provides-Extra: onnx
|
|
31
|
+
Requires-Dist: onnx>=1.23; extra == "onnx"
|
|
32
|
+
Requires-Dist: onnxscript; extra == "onnx"
|
|
33
|
+
Requires-Dist: onnxruntime>=1.26; extra == "onnx"
|
|
34
|
+
Requires-Dist: tokenizers; extra == "onnx"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# autofit2
|
|
39
|
+
|
|
40
|
+
[](https://hackergit.org/r/neospe/autofit2)
|
|
41
|
+
|
|
42
|
+
Few-shot text classification. Massively multilingual (50+ languages), fully automated pipeline built on `setfit` and SBERT embeddings.
|
|
43
|
+
|
|
44
|
+
## Key Features
|
|
45
|
+
|
|
46
|
+
* **Few-Shot Learning:** High precision (95–99%) with a few dozen labeled examples.
|
|
47
|
+
* **Multilingual Support:** Pretrained models for 20 languages; evaluation corpora for 50+. Scalable to 100+ via Common Crawl.
|
|
48
|
+
* **Automated Pipeline:** End-to-end preprocessing, fine-tuning, evaluation, and deployment from a single JSON config.
|
|
49
|
+
* **Reproducibility & Transparency:** Model cards and COâ‚‚ tracking for every run.
|
|
50
|
+
* **Shortcut Detection:** Flags words the model learned to rely on and optionally retrains without them (see below).
|
|
51
|
+
|
|
52
|
+
## Quickstart
|
|
53
|
+
|
|
54
|
+
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:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install autofit2
|
|
58
|
+
curl -O https://raw.githubusercontent.com/neospe/autofit2/master/examples/demo.json # the config is moved to history/ after the run
|
|
59
|
+
autofit2 demo.json
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
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`:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
uv tool install "autofit2[onnx]" # add dataload as well: "autofit2[onnx,dataload]"
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
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).
|
|
69
|
+
|
|
70
|
+
Output:
|
|
71
|
+
* `history/demo.log`: accuracy and F1 per target.
|
|
72
|
+
* `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).
|
|
73
|
+
* `models-in/demo-mod-en`: the fine-tuned embedding (sentence-transformers folder), usable as a base model for custom targets.
|
|
74
|
+
* `models-in/demo-mod-en.joblib`: the classifier on its embeddings.
|
|
75
|
+
|
|
76
|
+
Or in a container:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
docker build -t autofit2 .
|
|
80
|
+
docker run --rm -v "$PWD":/service autofit2 autofit2 demo.json
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Serving
|
|
84
|
+
|
|
85
|
+
Export the embedding to ONNX and the classifier to a weight file, then serve them over HTTP:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
pip install "autofit2[onnx]" # or: uv tool install "autofit2[onnx]"
|
|
89
|
+
autofit2-export models-in/demo-mod-en onnx/demo-mod-en models-in/demo-mod-en.joblib
|
|
90
|
+
docker build -f packaging/Dockerfile.serve -t autofit2-serve . # in a clone of this repository
|
|
91
|
+
docker run --rm -p 8080:8080 -v "$PWD/onnx":/models:ro autofit2-serve
|
|
92
|
+
curl -d '{"model id": "demo-mod-en", "queries": ["have a nice day"]}' localhost:8080
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
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).
|
|
96
|
+
|
|
97
|
+
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.
|
|
98
|
+
|
|
99
|
+
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.
|
|
100
|
+
|
|
101
|
+
## Shortcut Detection
|
|
102
|
+
|
|
103
|
+

|
|
104
|
+
|
|
105
|
+
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*.
|
|
106
|
+
|
|
107
|
+
## Usage
|
|
108
|
+
|
|
109
|
+
**1. Prepare Data**
|
|
110
|
+
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.
|
|
111
|
+
|
|
112
|
+
**2. Configure**
|
|
113
|
+
Create `myproject.json` specifying dataset paths, model settings, and output directories. Supports multi-language/task blocks.
|
|
114
|
+
|
|
115
|
+
**3. Run**
|
|
116
|
+
|
|
117
|
+
The pipeline supports resumable execution.
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
autofit2 myproject.json
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
**4. Output**
|
|
124
|
+
* Fine-tuned embedding and classifier, exportable to ONNX and served from a container (see Serving).
|
|
125
|
+
* Generated model card (training details, intended use, performance metrics, bias evaluation).
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
## Configuration
|
|
129
|
+
|
|
130
|
+
`myproject.json` defines the training parameters. Its structure depends on the target type: **Base Models** (`all`) or **Custom Models** (`custom`).
|
|
131
|
+
|
|
132
|
+
### General Structure
|
|
133
|
+
|
|
134
|
+
```json
|
|
135
|
+
{
|
|
136
|
+
"<task-key>": {
|
|
137
|
+
"<language-key>": {
|
|
138
|
+
"base": {
|
|
139
|
+
"model file": "<path>", // Relative path, no trailing slash (e.g. "models-in/all-MiniLM-L6-v2")
|
|
140
|
+
"model type": "<string>", // e.g., "bert"
|
|
141
|
+
"pretraining task": "<string>", // e.g., "sentence similarity"
|
|
142
|
+
"downstream task": "<string>" // e.g., "binary text classification"
|
|
143
|
+
},
|
|
144
|
+
"targets": {
|
|
145
|
+
"<id-key>": { ... } // See Target Options below
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Target Types
|
|
153
|
+
|
|
154
|
+
The `"targets"` dictionary supports three specific key types:
|
|
155
|
+
|
|
156
|
+
1. **`all`** (Base Model)
|
|
157
|
+
* Generates a full set of artifacts: model folder, classifier, and card.
|
|
158
|
+
* **Model ID:** Derived from the config filename (`{config_name}-{task}-{lang}`). The config filename must be stable.
|
|
159
|
+
2. **`custom`** (Custom Model)
|
|
160
|
+
* Generates a full set of artifacts: model folder, classifier, and card.
|
|
161
|
+
* **Model ID:** can be auto-generated as a 14–16 character lowercase alphanumeric string.
|
|
162
|
+
3. **`benchmark 1..N`** (Benchmarking Only)
|
|
163
|
+
* Does **not** generate model artifacts.
|
|
164
|
+
* Outputs only score logs.
|
|
165
|
+
* Must be used in conjunction with an `all` target to produce output.
|
|
166
|
+
|
|
167
|
+
### Target Options
|
|
168
|
+
|
|
169
|
+
Each entry in the `"targets"` dictionary supports `description`, `link`, `loader` and an optional `options` object:
|
|
170
|
+
|
|
171
|
+
```json
|
|
172
|
+
"custom": {
|
|
173
|
+
"options": {"train embedding": false, "base clf": "98sdfkjhw3r8sf"},
|
|
174
|
+
"loader": ["en_hate1()"]
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
| Key | Type | Description |
|
|
179
|
+
| :--- | :--- | :--- |
|
|
180
|
+
| `description` | `string` | Free-form description of the target. |
|
|
181
|
+
| `link` | `string` | URL to source data or documentation. |
|
|
182
|
+
| `options` → `train embedding` | `bool` | Fine-tune embeddings during training (default: `true`). |
|
|
183
|
+
| `options` → `base clf` | `string` | ID string pointing to a `.joblib` file located in `BASE_PATH`. Must match exactly. |
|
|
184
|
+
| `options` → `sample ratio` | `float` | Random sample of total data for full training (e.g., `0.5` = 50%). |
|
|
185
|
+
| `options` → `embedding sample ratio` | `float` | Random sample of data used **only** for embedding fine-tuning (e.g., `0.1` = 10%). |
|
|
186
|
+
| `options` → `neutral class` | `int` or `string` | The class of harmless texts, for the bias evaluation (default: `0` with classes 0 and 1, else none). |
|
|
187
|
+
| `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. |
|
|
188
|
+
|
|
189
|
+
### Loaders
|
|
190
|
+
|
|
191
|
+
The `"loader"` field defines how data is ingested and transformed. It expects a list of commands (functions or transformations):
|
|
192
|
+
|
|
193
|
+
```json
|
|
194
|
+
"loader": ["command_1", "command_2"]
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
* **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).
|
|
198
|
+
* **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.
|
|
199
|
+
* `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})"`.
|
|
200
|
+
* `csv(path, text='text', label='label', labels=None, sep=',')` and `jsonl(path, text='text', label='label', labels=None)`: local files.
|
|
201
|
+
* 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.
|
|
202
|
+
* **Data Splitting Logic:**
|
|
203
|
+
* **If 2 commands AND target != `all`:**
|
|
204
|
+
* Command 1 → Training Data
|
|
205
|
+
* Command 2 → Evaluation Data
|
|
206
|
+
* **Else (Target = `all`):**
|
|
207
|
+
* All commands are concatenated into a single dataset.
|
|
208
|
+
* Split: **100/100** (No split; entire set used for training).
|
|
209
|
+
* **Else (Other Targets, e.g., `custom` or benchmarks with 1 command):**
|
|
210
|
+
* All commands are concatenated into a single dataset.
|
|
211
|
+
* Split: **70/30** (Train/Test).
|
|
212
|
+
* **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:
|
|
213
|
+
```json
|
|
214
|
+
"loader": [
|
|
215
|
+
"[r for r in csv('posts.csv', labels={'spam': 1, 'ham': 0}) if len(r['text']) < 280]",
|
|
216
|
+
"[{'text': r['text'].lower(), 'label': r['label']} for r in hf('some/dataset')]",
|
|
217
|
+
"hf('some/dataset') + jsonl('extra.jsonl')"
|
|
218
|
+
]
|
|
219
|
+
```
|
|
220
|
+
A config is code: only run configs you trust.
|
|
221
|
+
|
|
222
|
+
### Multiple Classes
|
|
223
|
+
|
|
224
|
+
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:
|
|
225
|
+
|
|
226
|
+
```json
|
|
227
|
+
"all": {
|
|
228
|
+
"options": {"neutral class": "neither"},
|
|
229
|
+
"loader": ["hf('tdavidson/hate_speech_offensive', text='tweet', label='class', labels={0: 'hate', 1: 'offensive', 2: 'neither'})"]
|
|
230
|
+
}
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
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.
|
|
234
|
+
|
|
235
|
+
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.
|
|
236
|
+
|
|
237
|
+
## Configuration Example
|
|
238
|
+
|
|
239
|
+
```json
|
|
240
|
+
{
|
|
241
|
+
"mod": {
|
|
242
|
+
"el": {
|
|
243
|
+
"base": {
|
|
244
|
+
"model file": "models-in/paraphrase-multilingual-MiniLM-L12-v2",
|
|
245
|
+
"model type": "bert",
|
|
246
|
+
"pretraining task": "sentence similarity",
|
|
247
|
+
"downstream task": "binary text classification"
|
|
248
|
+
},
|
|
249
|
+
"targets": {
|
|
250
|
+
"benchmark 1": {
|
|
251
|
+
"description": "Pitenis et al. - Offensive Language Identification in Greek",
|
|
252
|
+
"link": "https://arxiv.org/abs/2003.07459",
|
|
253
|
+
"loader": [
|
|
254
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-training-v1/offenseval-gr-training-v1.tsv'])",
|
|
255
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-testsetv1/offenseval-gr-test-v1-combined.tsv'])"
|
|
256
|
+
]
|
|
257
|
+
},
|
|
258
|
+
"all": {
|
|
259
|
+
"loader": [
|
|
260
|
+
"el_offense20()"
|
|
261
|
+
]
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
### Breakdown: Finetuning a Sentence Transformer
|
|
270
|
+
|
|
271
|
+
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.
|
|
272
|
+
|
|
273
|
+
**Base Model Setup**
|
|
274
|
+
|
|
275
|
+
```json
|
|
276
|
+
"base": {
|
|
277
|
+
"model file": "models-in/paraphrase-multilingual-MiniLM-L12-v2",
|
|
278
|
+
"model type": "bert",
|
|
279
|
+
"pretraining task": "sentence similarity",
|
|
280
|
+
"downstream task": "binary text classification"
|
|
281
|
+
}
|
|
282
|
+
```
|
|
283
|
+
- Model file: Path to the pretrained transformer.
|
|
284
|
+
- Model type: Architecture type (e.g., BERT).
|
|
285
|
+
- Pretraining task: Original task the model was trained on.
|
|
286
|
+
- Downstream task: Task you're adapting it to (e.g., moderation, sentiment analysis).
|
|
287
|
+
|
|
288
|
+
**Targets**
|
|
289
|
+
|
|
290
|
+
You can specify multiple finetuning targets. Each target defines a dataset and training strategy.
|
|
291
|
+
|
|
292
|
+
1. `benchmark 1`
|
|
293
|
+
```json
|
|
294
|
+
"benchmark 1": {
|
|
295
|
+
"description": "Pitenis et al. - Offensive Language Identification in Greek",
|
|
296
|
+
"link": "https://arxiv.org/abs/2003.07459",
|
|
297
|
+
"loader": [
|
|
298
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-training-v1/offenseval-gr-training-v1.tsv'])",
|
|
299
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-testsetv1/offenseval-gr-test-v1-combined.tsv'])"
|
|
300
|
+
]
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
- Uses a train/test split for evaluation.
|
|
304
|
+
- Based on a published benchmark dataset.
|
|
305
|
+
|
|
306
|
+
2. `all`
|
|
307
|
+
```json
|
|
308
|
+
"all": {
|
|
309
|
+
"loader": ["el_offense20()"]
|
|
310
|
+
}
|
|
311
|
+
```
|
|
312
|
+
- Uses the full dataset for training.
|
|
313
|
+
- No explicit evaluation—this is for production-grade finetuning.
|
|
314
|
+
|
autofit2-1.0.0/README.md
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
|
|
2
|
+
# autofit2
|
|
3
|
+
|
|
4
|
+
[](https://hackergit.org/r/neospe/autofit2)
|
|
5
|
+
|
|
6
|
+
Few-shot text classification. Massively multilingual (50+ languages), fully automated pipeline built on `setfit` and SBERT embeddings.
|
|
7
|
+
|
|
8
|
+
## Key Features
|
|
9
|
+
|
|
10
|
+
* **Few-Shot Learning:** High precision (95–99%) with a few dozen labeled examples.
|
|
11
|
+
* **Multilingual Support:** Pretrained models for 20 languages; evaluation corpora for 50+. Scalable to 100+ via Common Crawl.
|
|
12
|
+
* **Automated Pipeline:** End-to-end preprocessing, fine-tuning, evaluation, and deployment from a single JSON config.
|
|
13
|
+
* **Reproducibility & Transparency:** Model cards and COâ‚‚ tracking for every run.
|
|
14
|
+
* **Shortcut Detection:** Flags words the model learned to rely on and optionally retrains without them (see below).
|
|
15
|
+
|
|
16
|
+
## Quickstart
|
|
17
|
+
|
|
18
|
+
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:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install autofit2
|
|
22
|
+
curl -O https://raw.githubusercontent.com/neospe/autofit2/master/examples/demo.json # the config is moved to history/ after the run
|
|
23
|
+
autofit2 demo.json
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
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`:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
uv tool install "autofit2[onnx]" # add dataload as well: "autofit2[onnx,dataload]"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
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).
|
|
33
|
+
|
|
34
|
+
Output:
|
|
35
|
+
* `history/demo.log`: accuracy and F1 per target.
|
|
36
|
+
* `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).
|
|
37
|
+
* `models-in/demo-mod-en`: the fine-tuned embedding (sentence-transformers folder), usable as a base model for custom targets.
|
|
38
|
+
* `models-in/demo-mod-en.joblib`: the classifier on its embeddings.
|
|
39
|
+
|
|
40
|
+
Or in a container:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
docker build -t autofit2 .
|
|
44
|
+
docker run --rm -v "$PWD":/service autofit2 autofit2 demo.json
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Serving
|
|
48
|
+
|
|
49
|
+
Export the embedding to ONNX and the classifier to a weight file, then serve them over HTTP:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install "autofit2[onnx]" # or: uv tool install "autofit2[onnx]"
|
|
53
|
+
autofit2-export models-in/demo-mod-en onnx/demo-mod-en models-in/demo-mod-en.joblib
|
|
54
|
+
docker build -f packaging/Dockerfile.serve -t autofit2-serve . # in a clone of this repository
|
|
55
|
+
docker run --rm -p 8080:8080 -v "$PWD/onnx":/models:ro autofit2-serve
|
|
56
|
+
curl -d '{"model id": "demo-mod-en", "queries": ["have a nice day"]}' localhost:8080
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
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).
|
|
60
|
+
|
|
61
|
+
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.
|
|
62
|
+
|
|
63
|
+
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.
|
|
64
|
+
|
|
65
|
+
## Shortcut Detection
|
|
66
|
+
|
|
67
|
+

|
|
68
|
+
|
|
69
|
+
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*.
|
|
70
|
+
|
|
71
|
+
## Usage
|
|
72
|
+
|
|
73
|
+
**1. Prepare Data**
|
|
74
|
+
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.
|
|
75
|
+
|
|
76
|
+
**2. Configure**
|
|
77
|
+
Create `myproject.json` specifying dataset paths, model settings, and output directories. Supports multi-language/task blocks.
|
|
78
|
+
|
|
79
|
+
**3. Run**
|
|
80
|
+
|
|
81
|
+
The pipeline supports resumable execution.
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
autofit2 myproject.json
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**4. Output**
|
|
88
|
+
* Fine-tuned embedding and classifier, exportable to ONNX and served from a container (see Serving).
|
|
89
|
+
* Generated model card (training details, intended use, performance metrics, bias evaluation).
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
## Configuration
|
|
93
|
+
|
|
94
|
+
`myproject.json` defines the training parameters. Its structure depends on the target type: **Base Models** (`all`) or **Custom Models** (`custom`).
|
|
95
|
+
|
|
96
|
+
### General Structure
|
|
97
|
+
|
|
98
|
+
```json
|
|
99
|
+
{
|
|
100
|
+
"<task-key>": {
|
|
101
|
+
"<language-key>": {
|
|
102
|
+
"base": {
|
|
103
|
+
"model file": "<path>", // Relative path, no trailing slash (e.g. "models-in/all-MiniLM-L6-v2")
|
|
104
|
+
"model type": "<string>", // e.g., "bert"
|
|
105
|
+
"pretraining task": "<string>", // e.g., "sentence similarity"
|
|
106
|
+
"downstream task": "<string>" // e.g., "binary text classification"
|
|
107
|
+
},
|
|
108
|
+
"targets": {
|
|
109
|
+
"<id-key>": { ... } // See Target Options below
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Target Types
|
|
117
|
+
|
|
118
|
+
The `"targets"` dictionary supports three specific key types:
|
|
119
|
+
|
|
120
|
+
1. **`all`** (Base Model)
|
|
121
|
+
* Generates a full set of artifacts: model folder, classifier, and card.
|
|
122
|
+
* **Model ID:** Derived from the config filename (`{config_name}-{task}-{lang}`). The config filename must be stable.
|
|
123
|
+
2. **`custom`** (Custom Model)
|
|
124
|
+
* Generates a full set of artifacts: model folder, classifier, and card.
|
|
125
|
+
* **Model ID:** can be auto-generated as a 14–16 character lowercase alphanumeric string.
|
|
126
|
+
3. **`benchmark 1..N`** (Benchmarking Only)
|
|
127
|
+
* Does **not** generate model artifacts.
|
|
128
|
+
* Outputs only score logs.
|
|
129
|
+
* Must be used in conjunction with an `all` target to produce output.
|
|
130
|
+
|
|
131
|
+
### Target Options
|
|
132
|
+
|
|
133
|
+
Each entry in the `"targets"` dictionary supports `description`, `link`, `loader` and an optional `options` object:
|
|
134
|
+
|
|
135
|
+
```json
|
|
136
|
+
"custom": {
|
|
137
|
+
"options": {"train embedding": false, "base clf": "98sdfkjhw3r8sf"},
|
|
138
|
+
"loader": ["en_hate1()"]
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
| Key | Type | Description |
|
|
143
|
+
| :--- | :--- | :--- |
|
|
144
|
+
| `description` | `string` | Free-form description of the target. |
|
|
145
|
+
| `link` | `string` | URL to source data or documentation. |
|
|
146
|
+
| `options` → `train embedding` | `bool` | Fine-tune embeddings during training (default: `true`). |
|
|
147
|
+
| `options` → `base clf` | `string` | ID string pointing to a `.joblib` file located in `BASE_PATH`. Must match exactly. |
|
|
148
|
+
| `options` → `sample ratio` | `float` | Random sample of total data for full training (e.g., `0.5` = 50%). |
|
|
149
|
+
| `options` → `embedding sample ratio` | `float` | Random sample of data used **only** for embedding fine-tuning (e.g., `0.1` = 10%). |
|
|
150
|
+
| `options` → `neutral class` | `int` or `string` | The class of harmless texts, for the bias evaluation (default: `0` with classes 0 and 1, else none). |
|
|
151
|
+
| `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. |
|
|
152
|
+
|
|
153
|
+
### Loaders
|
|
154
|
+
|
|
155
|
+
The `"loader"` field defines how data is ingested and transformed. It expects a list of commands (functions or transformations):
|
|
156
|
+
|
|
157
|
+
```json
|
|
158
|
+
"loader": ["command_1", "command_2"]
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
* **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).
|
|
162
|
+
* **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.
|
|
163
|
+
* `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})"`.
|
|
164
|
+
* `csv(path, text='text', label='label', labels=None, sep=',')` and `jsonl(path, text='text', label='label', labels=None)`: local files.
|
|
165
|
+
* 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.
|
|
166
|
+
* **Data Splitting Logic:**
|
|
167
|
+
* **If 2 commands AND target != `all`:**
|
|
168
|
+
* Command 1 → Training Data
|
|
169
|
+
* Command 2 → Evaluation Data
|
|
170
|
+
* **Else (Target = `all`):**
|
|
171
|
+
* All commands are concatenated into a single dataset.
|
|
172
|
+
* Split: **100/100** (No split; entire set used for training).
|
|
173
|
+
* **Else (Other Targets, e.g., `custom` or benchmarks with 1 command):**
|
|
174
|
+
* All commands are concatenated into a single dataset.
|
|
175
|
+
* Split: **70/30** (Train/Test).
|
|
176
|
+
* **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:
|
|
177
|
+
```json
|
|
178
|
+
"loader": [
|
|
179
|
+
"[r for r in csv('posts.csv', labels={'spam': 1, 'ham': 0}) if len(r['text']) < 280]",
|
|
180
|
+
"[{'text': r['text'].lower(), 'label': r['label']} for r in hf('some/dataset')]",
|
|
181
|
+
"hf('some/dataset') + jsonl('extra.jsonl')"
|
|
182
|
+
]
|
|
183
|
+
```
|
|
184
|
+
A config is code: only run configs you trust.
|
|
185
|
+
|
|
186
|
+
### Multiple Classes
|
|
187
|
+
|
|
188
|
+
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:
|
|
189
|
+
|
|
190
|
+
```json
|
|
191
|
+
"all": {
|
|
192
|
+
"options": {"neutral class": "neither"},
|
|
193
|
+
"loader": ["hf('tdavidson/hate_speech_offensive', text='tweet', label='class', labels={0: 'hate', 1: 'offensive', 2: 'neither'})"]
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
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.
|
|
198
|
+
|
|
199
|
+
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.
|
|
200
|
+
|
|
201
|
+
## Configuration Example
|
|
202
|
+
|
|
203
|
+
```json
|
|
204
|
+
{
|
|
205
|
+
"mod": {
|
|
206
|
+
"el": {
|
|
207
|
+
"base": {
|
|
208
|
+
"model file": "models-in/paraphrase-multilingual-MiniLM-L12-v2",
|
|
209
|
+
"model type": "bert",
|
|
210
|
+
"pretraining task": "sentence similarity",
|
|
211
|
+
"downstream task": "binary text classification"
|
|
212
|
+
},
|
|
213
|
+
"targets": {
|
|
214
|
+
"benchmark 1": {
|
|
215
|
+
"description": "Pitenis et al. - Offensive Language Identification in Greek",
|
|
216
|
+
"link": "https://arxiv.org/abs/2003.07459",
|
|
217
|
+
"loader": [
|
|
218
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-training-v1/offenseval-gr-training-v1.tsv'])",
|
|
219
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-testsetv1/offenseval-gr-test-v1-combined.tsv'])"
|
|
220
|
+
]
|
|
221
|
+
},
|
|
222
|
+
"all": {
|
|
223
|
+
"loader": [
|
|
224
|
+
"el_offense20()"
|
|
225
|
+
]
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Breakdown: Finetuning a Sentence Transformer
|
|
234
|
+
|
|
235
|
+
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.
|
|
236
|
+
|
|
237
|
+
**Base Model Setup**
|
|
238
|
+
|
|
239
|
+
```json
|
|
240
|
+
"base": {
|
|
241
|
+
"model file": "models-in/paraphrase-multilingual-MiniLM-L12-v2",
|
|
242
|
+
"model type": "bert",
|
|
243
|
+
"pretraining task": "sentence similarity",
|
|
244
|
+
"downstream task": "binary text classification"
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
- Model file: Path to the pretrained transformer.
|
|
248
|
+
- Model type: Architecture type (e.g., BERT).
|
|
249
|
+
- Pretraining task: Original task the model was trained on.
|
|
250
|
+
- Downstream task: Task you're adapting it to (e.g., moderation, sentiment analysis).
|
|
251
|
+
|
|
252
|
+
**Targets**
|
|
253
|
+
|
|
254
|
+
You can specify multiple finetuning targets. Each target defines a dataset and training strategy.
|
|
255
|
+
|
|
256
|
+
1. `benchmark 1`
|
|
257
|
+
```json
|
|
258
|
+
"benchmark 1": {
|
|
259
|
+
"description": "Pitenis et al. - Offensive Language Identification in Greek",
|
|
260
|
+
"link": "https://arxiv.org/abs/2003.07459",
|
|
261
|
+
"loader": [
|
|
262
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-training-v1/offenseval-gr-training-v1.tsv'])",
|
|
263
|
+
"el_offense20(files=['offenseval2020-greek/offenseval-gr-testsetv1/offenseval-gr-test-v1-combined.tsv'])"
|
|
264
|
+
]
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
- Uses a train/test split for evaluation.
|
|
268
|
+
- Based on a published benchmark dataset.
|
|
269
|
+
|
|
270
|
+
2. `all`
|
|
271
|
+
```json
|
|
272
|
+
"all": {
|
|
273
|
+
"loader": ["el_offense20()"]
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
- Uses the full dataset for training.
|
|
277
|
+
- No explicit evaluation—this is for production-grade finetuning.
|
|
278
|
+
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "autofit2"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Few-shot text classification with sentence-transformers: contrastive fine-tuning, shortcut detection, model cards, ONNX export and serving"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Stefan Pernes" }]
|
|
13
|
+
requires-python = ">=3.11"
|
|
14
|
+
keywords = ["few-shot", "text classification", "sentence-transformers", "setfit", "content moderation", "onnx"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Intended Audience :: Science/Research",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
"Topic :: Text Processing :: Linguistic",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"sentence-transformers>=6.3,<7",
|
|
24
|
+
"transformers>=5",
|
|
25
|
+
"datasets",
|
|
26
|
+
"accelerate",
|
|
27
|
+
"codecarbon",
|
|
28
|
+
"scikit-learn",
|
|
29
|
+
"joblib",
|
|
30
|
+
"pandas",
|
|
31
|
+
"numpy",
|
|
32
|
+
"torch>=2.14",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
dataload = ["dataload>=0.3"] # loaders for moderation corpora, e.g. en_hate1()
|
|
37
|
+
onnx = ["onnx>=1.23", "onnxscript", "onnxruntime>=1.26", "tokenizers"] # autofit2-export and autofit2-serve
|
|
38
|
+
|
|
39
|
+
[project.scripts]
|
|
40
|
+
autofit2 = "autofit2.train:main"
|
|
41
|
+
autofit2-export = "autofit2.export_onnx:main"
|
|
42
|
+
autofit2-serve = "autofit2.serve:main"
|
|
43
|
+
|
|
44
|
+
[project.urls]
|
|
45
|
+
Homepage = "https://github.com/neospe/autofit2"
|
|
46
|
+
Issues = "https://github.com/neospe/autofit2/issues"
|
|
47
|
+
|
|
48
|
+
[tool.setuptools.dynamic]
|
|
49
|
+
version = { attr = "autofit2.__version__" }
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.package-data]
|
|
52
|
+
autofit2 = ["eval-data/*"]
|
autofit2-1.0.0/setup.cfg
ADDED