Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
001dc18
Add initial training with bert
rjavadi Oct 5, 2026
06ad182
update training script
rjavadi Oct 6, 2026
d1f1ae6
Add normalization for AGE and MONET
rjavadi Oct 8, 2026
6a5fb0f
Add tests for normalized spans
rjavadi Oct 8, 2026
5fbbc45
Document DistilBERT batch and logit shapes.
rjavadi Oct 13, 2026
3386f9b
minor refactoring
rjavadi Oct 13, 2026
69abd16
Add currency and full name spans
rjavadi Oct 14, 2026
c3a96dd
Remove the unused UniNER and FastChat path.
rjavadi Oct 14, 2026
d4ad698
Add support for onnx models
rjavadi Oct 15, 2026
db5d91b
Fix sanitizer for money values with comma
rjavadi Oct 15, 2026
bf30ce5
Add demo notebook
rjavadi Oct 15, 2026
fe5d8b1
Fix pre-commit findings in the sanitizer and demo.
rjavadi Oct 15, 2026
7cb59f5
Point docs and coverage at preempt.
rjavadi Oct 15, 2026
3f4efd8
refactoring and documentation
rjavadi Oct 16, 2026
7ffb81a
Keep the training scripts off the main merge.
rjavadi Oct 16, 2026
76ccbea
Simplify the sanitizer and drop unused contract types.
rjavadi Oct 20, 2026
c38f8f4
Ignore local env files, generated benchmark data, and the old demo no…
rjavadi Oct 21, 2026
e87211b
Add pydantic, json-repair, and pyyaml for the PII benchmark.
rjavadi Oct 21, 2026
d884dd7
Add pii-bench skeleton, schemas, and the preempt sanitizer adapter.
rjavadi Oct 21, 2026
1918876
Add OpenAI-compatible LLM clients for generator, dataset, and judge m…
rjavadi Oct 21, 2026
335b7aa
Generate PII prompt templates with the dataset model.
rjavadi Oct 21, 2026
c033d58
Build the benchmark dataset by filling templates with seeded PII values.
rjavadi Oct 21, 2026
19a7339
Validate recognizer detection and sanitizer leakage against gold spans.
rjavadi Oct 21, 2026
b324ae3
Map names through fixed lists so surrogates depend only on the name.
rjavadi Oct 22, 2026
0ea5cbf
Add a GLiNER recognizer and the gliner dependency.
rjavadi Oct 22, 2026
057fb99
Merge feat/core-preempt-with-distilbert: fixed-list name surrogates a…
rjavadi Oct 22, 2026
072f6b4
Make Torch, GLiNER, and ONNX export optional so the default install s…
rjavadi Oct 23, 2026
c7cd4c9
Merge feat/benchmark-pii-conversion into feat/core-preempt-with-disti…
rjavadi Oct 23, 2026
83014e8
Update README with project overview, demo link, and branch table
rjavadi Nov 3, 2026
d8c5936
Organize branch dependency groups in pyproject.toml and update uv.lock
rjavadi Nov 3, 2026
037b2ba
Add project rules and LESSONS.md synthesizing past decisions and cons…
rjavadi Nov 6, 2026
c9fb5ec
Prepare library for OSS release: required key, env-based demo, pii-be…
rjavadi Nov 6, 2026
1a4391e
Allow the typos checker to keep look-alikes and the demo surname Mata.
rjavadi Nov 6, 2026
ad12b02
Add the missing trailing newline in .cursorrules.
rjavadi Nov 6, 2026
db38e23
Bump locked dependencies flagged by pip-audit.
rjavadi Nov 6, 2026
7e5852f
Fix fail-open paths flagged in PR review
rjavadi Nov 12, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .cursorrules
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Retrofit Project Rules & Guidelines

## 1. Architectural Integrity
- The project follows a modular structure. Do not introduce cross-layer or sideways imports in new or refactored code.
- Always check existing module boundaries before adding new dependencies.

## 2. Change Scope & Safety
- Keep PRs/changes small and targeted.
- Before finishing any task, ensure existing tests pass and types are valid.

## 3. Session Continuity
- At the end of a session or a major bug fix, document key decisions, quirks, or edge cases in `docs/LESSONS.md`.
13 changes: 13 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Copy to .env and fill in. .env is gitignored.
# uv run --env-file .env jupyter nbconvert --execute --inplace src/preempt/demo.ipynb

# Hugging Face model id, or a local directory that contains model.onnx.
PREEMPT_MODEL_PATH=

# FF3 key and tweak, as hex. The key is 32, 48, or 64 hex characters
# (128, 192, or 256 bits). The tweak is 16 hex characters (64 bits).
# Anyone with this pair can reverse FPE names and amounts.
# Generate a pair with:
# uv run python -c "from preempt import generate_key; print(*generate_key())"
PREEMPT_KEY=
PREEMPT_TWEAK=
2 changes: 1 addition & 1 deletion .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ jobs:
python-version-file: ".python-version"

- name: Install the project
run: uv sync --all-extras --group docs
run: uv sync --all-extras --group docs --group train

- name: Build docs
run: uv run mkdocs build
Expand Down
9 changes: 7 additions & 2 deletions .github/workflows/integration_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,18 @@ jobs:

- name: Install dependencies and check code
run: |
uv run pytest -m "integration_test" --cov src/aieng_template_uv --cov-report=xml tests
uv run pytest -m "integration_test" --cov src/preempt --cov-report=xml tests || code=$?
if [ "${code:-0}" -eq 5 ]; then
echo "No integration tests collected"
exit 0
fi
exit "${code:-0}"

# Uncomment this once this repo is configured on Codecov
- name: Upload coverage to Codecov
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5
with:
token: ${{ secrets.CODECOV_TOKEN }}
slug: VectorInstitute/aieng-template-uv
slug: VectorInstitute/preempt
fail_ci_if_error: false
verbose: true
2 changes: 1 addition & 1 deletion .github/workflows/unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ jobs:

- name: Install dependencies and check code
run: |
uv run pytest -m "not integration_test" --cov src/aieng_template_uv --cov-report=xml tests
uv run pytest -m "not integration_test" --cov src/preempt --cov-report=xml tests

# Uncomment this once this repo is configured on Codecov
- name: Upload coverage to Codecov
Expand Down
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,10 @@ wheels/
# macos
*.DS_Store
site/
runs/

.env
pii-bench/data/
src/preempt/demo-old.ipynb
# Local training downloads. Not used by the library.
training-data/
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ repos:
rev: v1.50.3
hooks:
- id: typos
args: []
args: [--force-exclude]

- repo: https://github.com/nbQA-dev/nbQA
rev: 1.9.1
Expand All @@ -59,7 +59,7 @@ repos:
- id: doctest
name: doctest
entry: python3 -m doctest -o NORMALIZE_WHITESPACE
files: "^src/aieng_template_uv/"
files: "^src/preempt/"
language: system

- repo: local
Expand Down
58 changes: 53 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# AI Engineering template (with uv)
# Preempt-Guardrail

----------------------------------------------------------------------------------------

Expand All @@ -9,10 +9,45 @@
[![codecov](https://codecov.io/github/VectorInstitute/aieng-template-uv/graph/badge.svg?token=83MYFZ3UPA)](https://codecov.io/github/VectorInstitute/aieng-template-uv)
![GitHub License](https://img.shields.io/github/license/VectorInstitute/aieng-template-uv)

A template repo for AI Engineering projects (using ``python``) and ``uv``. This
template is like our original AI Engineering [template](https://github.com/VectorInstitute/aieng-template),
however, unlike how that template uses poetry, this one uses uv for dependency
management (as well as packaging and publishing).
Preempt-Guardrail is PII detractor, removing age, money, name values from the user prompt before passing it to the LLM API.

For a usage example, see [`demo.ipynb`](src/preempt/demo.ipynb).

## Configuration

The demo reads the model path and the cipher key from the environment. Copy the example and fill it in:

```bash
cp .env.example .env
```

| Variable | Meaning |
| --- | --- |
| `PREEMPT_MODEL_PATH` | Hugging Face model id, or a local directory that contains `model.onnx` |
| `PREEMPT_KEY` | Hex FF3 key: 32, 48, or 64 hex characters (128, 192, or 256 bits) |
| `PREEMPT_TWEAK` | Hex FF3 tweak: 16 hex characters (64 bits) |

`.env` is gitignored. Anyone with the key and tweak can reverse FPE names and amounts. Generate a pair with:

```bash
uv run python -c "from preempt import generate_key; print(*generate_key())"
```

Run the notebook with those values:

```bash
uv run --env-file .env --with nbconvert --with ipywidgets jupyter nbconvert --execute --inplace src/preempt/demo.ipynb
```

## Key Branches

The following branches serve dedicated training and benchmarking workflows and are kept separate from `main`, each with its own `uv` dependency group in `pyproject.toml`:

| Branch | Dependency Group | Install Command | Purpose |
| --- | --- | --- | --- |
| `feat/training` | `train` | `uv sync --group train` | Training pipeline and scripts for fine-tuning the custom DistilBERT NER model for PII recognition (`NAME`, `AGE`, `MONEY`). |
| `feat/ner-bench` | `ner-bench` | `uv sync --group ner-bench` | Benchmarking and evaluation suite for the DistilBERT NER recognizer (detection accuracy, quantization, and latency). |
| `feat/pii-bench` | `pii-bench` | `uv sync --group pii-bench` | End-to-end downstream utility and privacy benchmark (`pii-bench/`), comparing LLM responses on original vs. sanitized prompts across $\epsilon$ values using verifiable tasks and LLM-as-a-judge. |

## 🧑🏿‍💻 Developing

Expand Down Expand Up @@ -42,6 +77,19 @@ run:
uv sync --no-group docs
```

`uv sync` installs the ONNX runtime. Running an exported ONNX file does not
need PyTorch or Optimum. The heavier recognizer and export stacks are extras:

```bash
uv sync --extra torch # PyTorch DistilBERT backend
uv sync --extra gliner # zero-shot GLiNER recognizer
uv sync --extra export # export a checkpoint to ONNX
```

`DistilBertRecognizer` defaults to the PyTorch backend, so that constructor
needs the `torch` extra. Pass `backend="onnx"` to run an exported graph with
the default install.

If you're coming from `poetry` then you'll notice that the virtual environment
is actually stored in the project root folder and is by default named as `.venv`.
The other important note is that while `poetry` uses a "flat" layout of the project,
Expand Down
67 changes: 67 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Release notes

## 0.1.0

First open-source release of the library. It finds names, ages, and money amounts in a prompt, replaces them, and can put the originals back after the model call.

### Install

```bash
uv sync
```

That install runs an exported ONNX graph. It does not install PyTorch.

```bash
uv sync --extra torch # PyTorch backend for DistilBertRecognizer
uv sync --extra gliner # GlinerRecognizer
uv sync --extra export # export a checkpoint to ONNX
```

`DistilBertRecognizer` defaults to `backend="pytorch"`. Pass `backend="onnx"` when you only have the default install.

### Breaking change

`Sanitizer` no longer has a default key.

```python
from preempt import Sanitizer, generate_key

key, tweak = generate_key()
sanitizer = Sanitizer(recognizer, key, tweak)
```

The name permutation and the FF3 money cipher are both derived from `key` and `tweak`. Anyone who has the pair can undo FPE names and amounts. Keep the pair with your other secrets. `generate_key()` returns a 256-bit key and a 64-bit tweak, as hex.

A recognizer with a `recognize()` method can be passed straight in. `Sanitizer` wraps it. `LegacyNERShim` is still there if you want to call `extract()` yourself.

`from preempt import Sanitizer, generate_key, LegacyNERShim, EntitySpan` works. The recognizers stay on their own modules, because importing them loads `transformers` or the `gliner` extra.

### Demo

`src/preempt/demo.ipynb` reads three environment variables, listed in `.env.example`:

| Variable | Meaning |
| --- | --- |
| `PREEMPT_MODEL_PATH` | Hugging Face model id, or a local directory with an ONNX graph |
| `PREEMPT_KEY` | Hex FF3 key (32, 48, or 64 hex characters) |
| `PREEMPT_TWEAK` | Hex FF3 tweak (16 hex characters) |

The notebook loads `model.onnx`, the full-precision graph, not `model.int8.onnx`.

### Not in this release

- Training scripts stay on `feat/training`.
- NER evaluation stays on `feat/ner-bench`.
- The end-to-end privacy and utility benchmark stays on `feat/pii-bench`. This branch does not contain that code. The README table and the `pyproject.toml` dependency groups still name those branches.
- `training-data/` is gitignored. A local copy of the PII-masking train set can live there (`pii_masking_200k_en_fr_de_train.json`, 110,790 labeled conversations, about 85 MB). No code in this branch reads it, and it is not part of the package.

### Known limitations

- Replacement is a plain substring. A short value can match inside a longer word, and some decrypt paths restore only the first match.
- FPE money drops thousands separators. `$10,000` comes back as `$10000`.
- Ages, and money when you pass `use_fpe=False`, are noised with m-LDP. Restoring them needs the same `Sanitizer` instance that encrypted them. A new instance with the same key is not enough.
- Names that are not in the fixed lists also need that saved state. `decrypt` restores only surrogates from the last `encrypt` on that instance. Pass `key_only=True` to invert listed names and FPE amounts with the key alone. Key-only money skips an amount FF3 rejects instead of failing the batch. Ages have no key-only inverse.
- A value that cannot be encrypted is replaced with `[REDACTED]`. Its row index is still returned. Other values in that text are still replaced.
- DistilBERT and GLiNER read text longer than the model window in overlapping pieces. An entity longer than the overlap (`stride` tokens for DistilBERT, `overlap` words for GLiNER) can still be split.
- The sanitizer only replaces `Name`, `Money`, and `Age`. The recognizer can also emit email, phone, address, and id spans, and those are left as they are.
61 changes: 61 additions & 0 deletions docs/LESSONS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Lessons

Constraints and history for later sessions. Sources: `README.md`, `pii-bench/reports/limitations.md`, and the pre-Milestone-8 questions in `pii_sanitizer_benchmark_plan.md`.

## Architecture & Design Decisions

- Preempt-Guardrail removes `AGE`, `MONEY`, and `NAME` from the user prompt before the LLM call. Usage example: `src/preempt/demo.ipynb`.
- Training, NER evaluation, and the end-to-end benchmark stay on separate branches off `main`, each with its own `uv` group:
- `feat/training` (`train`) — fine-tune the DistilBERT NER for `NAME`, `AGE`, `MONEY`.
- `feat/ner-bench` (`ner-bench`) — detection accuracy, quantization, and latency.
- `feat/pii-bench` (`pii-bench`) — utility and privacy across ε, verifiable tasks, and an LLM judge.
- The default install runs an exported ONNX graph. `DistilBertRecognizer` defaults to PyTorch and needs the `torch` extra. Pass `backend="onnx"` on a default install. GLiNER and checkpoint export are the `gliner` and `export` extras.
- Benchmark data is synthetic. Keep real personal data, including public chat corpora, out of ground-truth metrics. A later sanity-check corpus needs a license check and a separate PII relabel.
- Scored detection set: 36 templates × 10 fills = 360 prompts in `data/dataset.jsonl`. 240 are incidental (email drafts, general explanations). 120 are verifiable (retirement, age gates, savings rate, raise). Recognizer and sanitizer ran on all 360 at ε = 1 via `metrics.detection`.
- Values this round generates: integer ages; money as `$12,000`, `$12k`, or `12,000 dollars`.
- Partial recall uses IoU ≥ 0.5. Per-item rows are in `runs/detection_validation.jsonl`. Strict money F1 is 0.40 because the recognizer labels the digits inside `$12,000` while the gold span includes `$`. Partial money F1 is 0.83. Quote the partial figure for money detection.
- `Sanitizer(ner_model, key, tweak)` has no default key. The name permutation and FF3 money cipher are seeded only by `key:tweak`, so a published default would let anyone reverse surrogates. Use `preempt.generate_key()` for a fresh pair. Library tests pass a fixed key. `feat/pii-bench` still calls `Sanitizer` with no key and needs the same change; this branch does not contain that code.
- `Sanitizer` accepts a `Recognizer` directly and wraps it in `LegacyNERShim`. `preempt/__init__.py` re-exports `Sanitizer`, `generate_key`, `LegacyNERShim`, and the contracts, but not the recognizers, which load transformers or the `gliner` extra.
- `demo.ipynb` reads `PREEMPT_MODEL_PATH`, `PREEMPT_KEY`, and `PREEMPT_TWEAK` (see `.env.example`) and loads `model.onnx`, not the int8 graph. Re-execute it with `uv run --env-file .env --with nbconvert --with ipywidgets jupyter nbconvert --execute --inplace src/preempt/demo.ipynb`. Without `ipywidgets` a tqdm warning writes a local path into the outputs. The kernel cannot start inside the agent sandbox.
- Compare configurations with a paired bootstrap on per-prompt means. Claim a difference only when the confidence interval excludes zero.
- The generator model and the judge model must be from different families.
- Offline CI path: `MockSanitizer` plus a stub LLM, 10 items, under 60 seconds. Seed the dataset, each sanitizer draw, and the bootstrap. Content-address the LLM cache and store model name and version on every record. Log full prompts; keep them off CI stdout.
- Bench tests that must exist before a run is trusted: slot spans, normalized leakage (`85k` / `85,000` / `eighty-five thousand`), name rehydration (possessives, case, partial names), `FINAL_ANSWER` parsing, each `answer_fn`, threshold distance, bootstrap CIs, judge JSON schema, and a golden file of the rendered judge prompt.

## Gotchas & Edge Cases

- `12,000 dollars` is the money format NER misses: 15/119 found (failure 0.87). `$12,000` is 107/107 and `$12k` is 134/134.
- Integer ages: 201/210 found (failure 0.04). Full names: 408/470 found (failure 0.13).
- After sanitization at ε = 1, an original value remains in 145/360 prompts (0.40). Money accounts for 117/360 prompts; names account for 64/470 name spans. Those denominators differ — prompts versus spans.
- Look-alikes (`metrics.lookalikes`, 20 non-record lines): 3 spans, all `NAME` — "Jordan" as a destination, "Jordan" as a person asked for notes, and "Bill". Left untagged: Apple, "the bill for dinner", Mark 4:12, version 52, Route 66, iPhone 15, "the age of the universe", China, Turkey, Georgia.
- The PII-masking train download (110,790 conversation rows, 54 label types, about 85 MB) lives in `training-data/`, which `.gitignore` excludes. Nothing in this branch reads it. A fresh clone does not have it, and it sits outside `src/preempt`, so it cannot land in the wheel.
- On `model.onnx` (run 407944) the demo sentence "Ben Parker and John Doe" yields `Ben Parker` and misses `John Doe`, so "John Doe" is left in place. The same graph does detect `Hamid Aziz` and `Jose Santiago` in the longer passage, and those round-trip. FPE money loses thousands separators (`$10,000` is sanitized with no comma and decrypts to `$10000`).
- Long text is scanned in overlapping windows (`DistilBertRecognizer.stride`, default 128 content tokens; `GlinerRecognizer.overlap`, default 32 words). `tokenizers` `return_overflowing_tokens` only returns one extra chunk, so the windows are built from the untruncated offsets. An entity longer than the overlap can still be split. If a long text has no character offsets, recognition raises instead of returning a silent prefix.
- One value FF3 or the parser cannot encrypt is replaced with `[REDACTED]` (`preempt.sanitizer.REDACTED`). The row is still listed in `invalid`, and the other values in that text are still replaced. FF3 money appends `999999` (`MONEY_FPE_SUFFIX`) rather than prefixing it: a prefix made the right half of a round amount (`$1,000,000`) all zeros, and pyfpe raises `ValueError: string 000000 is not within base/radix`. Decrypt strips that suffix.
- `decrypt` restores only surrogates saved by the last `encrypt` on that instance. A name the recognizer missed, or an amount the model reply added, is left as written. `key_only=True` is the explicit path that inverts listed names and FPE amounts with the key alone. In that mode an amount FF3 rejects is skipped, so one value cannot fail the batch. `use_cache` is still accepted and does not change this. Ages stay stateful either way.
- Leave ordinary look-alikes alone this round. A later hard-negative slice is place names that are also given names.
- Unsupported, so absent from the dataset: ages as words, birth dates, birth years, decades ("early 50s"), relative ages ("I'll be 60 next month"); money as words, slang ("about 85 grand"), ranges, or relations ("2x my spouse's salary").
- `runs/sweep-v2/` is the earlier 90-prompt sweep. It is a different run from the 360-prompt detection pass.

## Tooling & Environment Quirks

- Package manager is `uv`. The environment is `.venv` at the repo root. Layout is `src`, which differs from Poetry's flat layout.
- `typos` splits on hyphens, so `look-alikes` is reported as `alikes`. `Mata` in `demo.ipynb` is a generated surname. Both are allowlisted in `typos.toml` under `extend-ignore-words-re`. A new notebook run can introduce another surname that the checker rejects.
- `uv sync` installs the ONNX runtime. An exported ONNX file runs without PyTorch or Optimum.
- `pyfpe` 0.10.3 requires `pycryptodome==3.10.1`. pip-audit flags that release (PYSEC-2026-1811, fixed in 3.19.1). `tool.uv.override-dependencies` lifts it. The FF3 round-trip tests pass on pycryptodome 4.x.
- Extras: `uv sync --extra torch`, `--extra gliner`, `--extra export`.
- Dev and test dependencies: `uv sync --dev`. Drop a group with `uv sync --no-group docs`.
- Branch stacks, checked out on that branch: `uv sync --group train`, `--group ner-bench`, or `--group pii-bench`.

## Active & Pending Technical Debt

- Resolve before Milestone 8, when the real sanitizer is wired:
1. Sanitizer transport (Python function, REST, or CLI), and whether it returns the substitution map and spans.
2. ε range and parameterization, and the distance metric mLDP uses.
3. Which generator and judge models to use (different families).
4. Whether FPE name mapping preserves gender, culture, and length. That answer decides whether to add pronoun-consistency checks.
5. Whether this round includes non-English prompts.
- Still unrun on the 360-prompt set: generator, judge, a full ε sweep, privacy attacks, human labels for the judge, bootstrap intervals, and per-type ablations.
- Open quality gaps from the ε = 1 detection pass: `N dollars` recognition (failure 0.87) and residual original values in 0.40 of prompts. Strict versus partial money spans still disagree on the `$`.
- Large runs need a dry-run cost estimate and a confirmation prompt. Pilot is 50 items, 2 ε values, k = 2, and that report is reviewed before the full run.
- Milestones 1–3 come first. Stop for review before spending LLM budget on the full run.
Loading
Loading