Skip to main content

Scanner for TokenBreak vulnerabilities in NLP model artifacts

Project description

๐Ÿ” TokenBreak Scanner โ€” NLP Model Vulnerability Auditor

Detect TokenBreak adversarial vulnerabilities in LLMs, classifiers, and encoders before they hit production.

PyPI Python License Tests Downloads

๐Ÿ“„ TokenBreak Paper ยท โšก Quick Start ยท ๐Ÿ“– Usage ยท ๐Ÿš€ CI Integration


๐Ÿ”ฅ What is TokenBreak?

TokenBreak is an adversarial attack that bypasses text-classification and LLM guardrails by prepending a single character to targeted words. This tiny perturbation corrupts BPE and WordPiece tokenization, causing models to misclassify malicious input as benign โ€” while humans and downstream LLMs still understand the original meaning.

๐Ÿ“„ Paper: TokenBreak: Bypassing Text Classification Models Through Token Manipulation


๐Ÿ›ก๏ธ What TokenBreak Scanner Does

Capability Description
Inspect model artifacts Reads config.json, tokenizer.json, tokenizer_config.json to determine tokenizer architecture
Identify tokenization algorithm Detects BPE, WordPiece, Unigram, or SentencePiece
Assess TokenBreak vulnerability Flags BPE/WordPiece models as High Risk; Unigram as Safe
Explain the decision Evidence tree showing which signals (config, runtime, source) contributed to the confidence score
Recommend defense Suggests the Unigram pre-mapping defense (Section 5) or migration to a safer model family
Live attack validation (optional) Loads model weights and runs the BreakPrompt algorithm to verify the bypass experimentally

๐Ÿ“ฆ Installation

From PyPI (recommended)

pip install tokenbreak-scanner

Optional extras

  • Attack validation (requires PyTorch):
    pip install "tokenbreak-scanner[attack]"
    
  • Development dependencies (pytest, coverage):
    pip install "tokenbreak-scanner[dev]"
    

From source

git clone https://github.com/your-org/tokenbreak-scanner.git
cd tokenbreak-scanner
pip install -e ".[dev]"

๐Ÿš€ Quick Start

Scan a local model directory

tokenbreak-scan ./models/my-spam-classifier/

Scan a HuggingFace model ID (auto-download)

tokenbreak-scan distilbert-base-uncased --download

Scan Qwen3-0.6B (production example)

tokenbreak-scan Qwen/Qwen3-0.6B --download --trust-remote-code

โœ… Expected result: HIGH risk โ€” Qwen uses BPE tokenization and is vulnerable to TokenBreak.

JSON output (for CI pipelines)

tokenbreak-scan <model> --output json

Run live attack validation

tokenbreak-scan <model> --test-attack

๐Ÿงช Example Output

Table format (vulnerable model)

======================================================================
               TOKENBREAK SCANNER REPORT
======================================================================
  Model Name:       distilbert-base-uncased
  Model Type:       distilbert
  Family:           DistilBERT
  Tokenizer Class:  DistilBertTokenizerFast
  Algorithm:        WordPiece
  Vocab Size:       30522
  Confidence:       0.85
  Vulnerable:       YES โš ๏ธ
  Risk Level:       High
======================================================================
  Detection Sources:
    1. [tokenizer.json model.type] weight=0.40 -> WordPiece
    2. [tokenizer_config.json class] weight=0.20 -> WordPiece
    3. [config.json model_type] weight=0.15 -> WordPiece
======================================================================
  Recommendation:
    Model is vulnerable to TokenBreak. Recommended: Implement the
    Unigram pre-mapping defense by inserting a Unigram tokenizer
    before classification and remapping tokens, or migrate to a
    model family using Unigram tokenization.
======================================================================

JSON format

{
  "model_name": "distilbert-base-uncased",
  "model_type": "distilbert",
  "model_family": "DistilBERT",
  "tokenizer_class": "DistilBertTokenizerFast",
  "tokenizer_algorithm": "WordPiece",
  "vocab_size": 30522,
  "confidence_score": 0.85,
  "vulnerable_to_tokenbreak": true,
  "risk_level": "High",
  "detection_sources": [...],
  "recommendation": "...",
  "source": "/path/to/model"
}

๐Ÿ”„ CI Integration

Use exit codes to gate vulnerable models in your MLOps pipeline:

Exit code Meaning
0 Model is safe (Unigram) or unknown
1 Model is vulnerable (BPE or WordPiece) โ€” block deployment
2 Error (path not found, download failed, etc.)

GitHub Actions example

- name: Scan model for TokenBreak vulnerability
  run: |
    pip install tokenbreak-scanner
    tokenbreak-scan ./models-to-deploy/ --output json > scan-report.json
    cat scan-report.json

Python SDK example

from tokenbreak_scanner.inspector import inspect_model
from tokenbreak_scanner.models import RiskLevel

report = inspect_model(model_path, download=False)
if report.risk_level == RiskLevel.HIGH:
    raise RuntimeError(f"Deployment blocked: {report.model_name} is vulnerable to TokenBreak")

๐Ÿ”ฌ How the Attack Works

  1. Attack vector: Prepend a single character (Aโ€“Z or aโ€“z) to high-impact words, forcing BPE/WordPiece to split tokens differently.
  2. Effect: The protection model misclassifies the input (false negative), while the downstream LLM or human reviewer still understands it.
  3. Defense: Insert a Unigram tokenizer before the target tokenizer. Unigram tokenizes based on probability rather than left-to-right merges, making it naturally resistant to character-level perturbations.

๐Ÿ“Š Supported Model Families

Family Algorithm TokenBreak Risk
GPT-2, GPT-J, GPT-Neo, GPT-NeoX BPE ๐Ÿ”ด HIGH
LLaMA, Mistral, Mixtral, Falcon BPE ๐Ÿ”ด HIGH
Qwen, Qwen2, Qwen3 BPE ๐Ÿ”ด HIGH
Gemma, Gemma 2 BPE ๐Ÿ”ด HIGH
Phi-3, Phi-4 BPE ๐Ÿ”ด HIGH
BLOOM, BigScience BPE ๐Ÿ”ด HIGH
Cohere, Command R BPE ๐Ÿ”ด HIGH
BERT, DistilBERT, RoBERTa WordPiece / BPE ๐Ÿ”ด HIGH
DeBERTa-v2, DeBERTa-v3 Unigram ๐ŸŸข LOW
XLM-RoBERTa Unigram ๐ŸŸข LOW
ALBERT Unigram ๐ŸŸข LOW
mT5, T5 (SentencePiece Unigram) Unigram ๐ŸŸข LOW

๐Ÿ“‹ Full mapping in src/tokenbreak_scanner/tokenizers.py


๐Ÿ—๏ธ Architecture

tokenbreak_scanner/
โ”œโ”€โ”€ __init__.py      # Package version
โ”œโ”€โ”€ cli.py           # Click CLI with Rich table / JSON output
โ”œโ”€โ”€ inspector.py     # Core introspection engine (6-signal weighted aggregation)
โ”œโ”€โ”€ models.py        # Pydantic schemas: ScannerReport, DetectionSource, RiskLevel
โ”œโ”€โ”€ tokenizers.py    # Tokenizer type detection, model-family mapping, runtime inspection
โ””โ”€โ”€ validator.py     # Optional live attack validation via BreakPrompt

Detection signals (weighted evidence tree)

Signal Weight Source
tokenizer.json model type 0.40 HuggingFace tokenizer artifact
Runtime _tokenizer.model 0.40 Live Rust backend inspection
Source-code fingerprint 0.30 Python module keyword matching
Remote source file 0.30 HF Hub downloaded tokenizer module
tokenizer_config.json class 0.20 Config metadata
config.json model_type 0.15 Architecture fallback

๐Ÿงช Testing

pytest tests/ -v

All 33+ tests cover:

  • Local model directory scanning (BPE, WordPiece, Unigram)
  • Missing tokenizer.json fallback
  • CLI table and JSON output modes
  • Tokenizer class name โ†’ algorithm mapping

๐Ÿค Contributing

Contributions are welcome! Please open an issue or pull request.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feat/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feat/amazing-feature)
  5. Open a Pull Request

๐Ÿ“œ License

This project is licensed under the GNU Affero General Public License v3.0 or later (AGPL-3.0+).

  • โœ… Freedom to use, modify, and distribute
  • ๐Ÿ”’ Copyleft: derivative works and services must also be open-sourced under AGPL
  • ๐ŸŒ Network use counts as distribution โ€” remote users are entitled to the source code

See LICENSE for the full text: https://www.gnu.org/licenses/agpl-3.0.html


๐Ÿ”— Related

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tokenbreak_scanner-0.1.0.tar.gz (24.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tokenbreak_scanner-0.1.0-py3-none-any.whl (21.7 kB view details)

Uploaded Python 3

File details

Details for the file tokenbreak_scanner-0.1.0.tar.gz.

File metadata

  • Download URL: tokenbreak_scanner-0.1.0.tar.gz
  • Upload date:
  • Size: 24.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for tokenbreak_scanner-0.1.0.tar.gz
Algorithm Hash digest
SHA256 4119734efffedf578fad6495934a45201f69d1ce6e2cf43a928d747a391b8e51
MD5 a16f1cb3900831e22ee348fb0d85a5ba
BLAKE2b-256 e85908ddf16a00d1d21791b97767300b10974c27000315290d24e5188f2eb131

See more details on using hashes here.

File details

Details for the file tokenbreak_scanner-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for tokenbreak_scanner-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ca3b3969a3221f2f7789478bd3660f1fc00ed8c18b7ab8c1e0d8d7abfa3cae84
MD5 a295810eb3645c89abf4e73b50914127
BLAKE2b-256 4538acd2de668e130d23cc06d8c545827dd5bf6b4ab365a65b0673823489f3fe

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page