Instructions to use neigezhu/llm-redact-detector-mini with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use neigezhu/llm-redact-detector-mini with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="neigezhu/llm-redact-detector-mini")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("neigezhu/llm-redact-detector-mini") model = AutoModelForTokenClassification.from_pretrained("neigezhu/llm-redact-detector-mini", device_map="auto") - Notebooks
- Google Colab
- Kaggle
llm-redact-detector-mini · v0.1
用 MiniLM-L12-H384 在本地检测准备发往外部 LLM 的敏感片段。配合 llm-redact,规则处理确定性格式,模型补充依赖语境的跨度。
Run MiniLM-L12-H384 locally to locate sensitive spans before sending text to an external LLM. The classifier returns BIO labels; the gateway applies the redaction policy. No external inference service is required.
评测 / Evaluation
| 任务 / Protocol | 结果 / Result |
|---|---|
| 同分布,FP32 模型;472 个验证原例,1,416 个金标;类别和区间必须都正确 / Exact typed micro-F1 | 71.89% (TP 1134, FP 605, FN 282) |
| 网关:仅规则 / Rules only | Exact interval F1 44.56%; 266/900 gold intervals matched |
| 网关:规则 + 本版 INT8 / Rules + this INT8 model | Exact interval F1 71.36%; 735/900 matched |
| Gretel 官方 validation,FP32 工号 / Employee ID | 4/988 exact typed recall (0.40%) |
| Gretel 官方 validation,FP32 客户号 / Customer ID | 0/1025 exact typed recall (0.00%) |
网关两行使用同一组 300 个开发原例(30 个虚构组织);不要求类别相同,只比可执行发现的精确字节区间。阈值 0.05 由另外 20 个组织的 172 个原例选定,仅用于模型类别。Gretel 数字来自 1,578 篇含可唯一定位目标编号的英语文档;部分标注不能估算整体精确率。
Both gateway rows use the same held-out groups and ignore type when matching exact intervals. Model-only F1 uses the original BIO decoder; the convenience pipeline's aggregation can place boundaries differently. The Gretel evaluation source provides partial labels for the transfer evaluation. Its recall is not a general PII F1 score.
在相同 Gretel 子集,INT8 网关按正确类别和边界命中工号 0/988、客户号 0/1,025。忽略预测类别检查实际出站内容:仅规则完整覆盖 / 部分覆盖 / 原样外发为 0 / 0 / 2,013;规则加 INT8 为 909 / 342 / 762。
For the shipped mini INT8 gateway, none of these IDs matched both type and span. An outbound-body check counted 909 fully covered, 342 partly covered and 762 unchanged IDs; rules alone left all 2,013 unchanged.
用法 / Examples
Install torch transformers==5.13.0 onnxruntime tokenizers numpy huggingface_hub. The examples default to the Hugging Face repository. For a ModelScope download or an offline copy, set MODEL_DIR to its local snapshot directory. 中文文本直接传入,不要先把字符偏移转为字节。
1. Transformers:文本 → 合并跨度 / Text to spans
import os
from transformers import pipeline
model = os.environ.get("MODEL_DIR", "neigezhu/llm-redact-detector-mini")
tagger = pipeline("token-classification", model=model, tokenizer=model, aggregation_strategy="simple", device=-1)
text = "姓名: Morgan 赵辰文;员工编号: DEMO-9271。"
spans = tagger(text)
print([(x["entity_group"], text[x["start"]:x["end"]]) for x in spans])
2. ONNX Runtime:查看 token 预测 / Inspect token predictions
import json, os
from pathlib import Path
import numpy as np
import onnxruntime as ort
from huggingface_hub import snapshot_download
from tokenizers import Tokenizer
root = Path(os.environ.get("MODEL_DIR") or snapshot_download("neigezhu/llm-redact-detector-mini", allow_patterns=["config.json", "tokenizer.json", "model_int8.onnx"]))
text = "姓名: Morgan 赵辰文;员工编号: DEMO-9271。"
enc = Tokenizer.from_file(str(root / "tokenizer.json")).encode(text)
x = np.array([enc.ids], dtype=np.int64)
session = ort.InferenceSession(str(root / "model_int8.onnx"), providers=["CPUExecutionProvider"])
logits = session.run(["logits"], {"input_ids": x, "attention_mask": np.ones_like(x)})[0]
labels = json.loads((root / "config.json").read_text(encoding="utf8"))["id2label"]
assert logits.shape == (1, len(enc.ids), 51) and np.isfinite(logits).all()
print([(text[a:b], labels[str(k)]) for (a,b), k, special in zip(enc.offsets, logits[0].argmax(-1), enc.special_tokens_mask) if not special and k])
model.onnx is FP32; model_int8.onnx uses dynamic INT8 quantization. Both accept int64 input_ids and attention_mask of shape [batch, sequence]. Limit each sequence to 512 tokens. The gateway example handles longer inputs with overlapping windows.
3. llm-redact:实际网关 dry-run / Local gateway
先安装 llm-redact,把可执行文件加入 PATH,或用 LLM_REDACT_BIN 指定路径。下面的脚本启动回环检测器,分别运行纯规则与混合策略,并比较实际出站正文;不会访问外部 LLM。Requires the llm-redact executable. This runs the packaged localhost detector and the gateway's OpenAI Responses dry-run on the same request. Offsets in the detector HTTP response are half-open UTF-8 byte intervals.
import os, subprocess, sys
from pathlib import Path
from huggingface_hub import snapshot_download
root = Path(os.environ.get("MODEL_DIR") or snapshot_download("neigezhu/llm-redact-detector-mini", allow_patterns=["*.py", "policy.json", "config.json", "tokenizer.json", "model_int8.onnx"]))
subprocess.run([sys.executable, str(root / "gateway_example.py"), "--binary", os.environ.get("LLM_REDACT_BIN", "llm-redact")], check=True)
标签 / Labels
0 = O(非敏感 / outside);下表给出 B/I 的标签编号。B begins an entity; I continues it.
| B / I | Type | 含义 |
|---|---|---|
| 1 / 2 | person_name |
姓名 |
| 3 / 4 | street_address |
街道地址 |
| 5 / 6 | personal_email |
个人邮箱 |
| 7 / 8 | cn_mobile |
中国手机号 |
| 9 / 10 | landline |
固定电话 |
| 11 / 12 | cn_id_card |
中国身份证号 |
| 13 / 14 | passport |
护照号 |
| 15 / 16 | employee_id |
员工编号 |
| 17 / 18 | customer_id |
客户编号 |
| 19 / 20 | payment_card |
支付卡号 |
| 21 / 22 | bank_account |
银行账户 |
| 23 / 24 | cn_uscc |
统一社会信用代码 |
| 25 / 26 | license_plate |
车牌号 |
| 27 / 28 | account_name |
账号名称 |
| 29 / 30 | geo_coordinate |
地理坐标 |
| 31 / 32 | password |
密码 |
| 33 / 34 | cloud_access_key |
云访问密钥 |
| 35 / 36 | code_host_token |
代码托管令牌 |
| 37 / 38 | im_bot_token |
即时通信机器人令牌 |
| 39 / 40 | api_key_other |
其他接口密钥 |
| 41 / 42 | session_token |
会话令牌 |
| 43 / 44 | private_key |
私钥 |
| 45 / 46 | internal_domain |
内部域名 |
| 47 / 48 | internal_ip |
内部IP |
| 49 / 50 | project_codename |
项目代号 |
训练与权重 / Training and weights
底座:原始权重与固定版本。训练集为 llm-redact-synth-v1 的 9,000 个训练根样本,各取原例及反事实负例,共 18,000 篇。未混入 OpenPII 或 Gretel 转换稿。单轮全参数微调,窗口长 512、重叠 64、学习率 3e-5;4,500 次优化更新。BIO 头直接映射到标准 BertForTokenClassification.classifier。
One epoch of full fine-tuning used BIO token supervision plus a field-name classification loss (weight 0.25). field_head.safetensors contains a separate linear classifier (weight, bias) on the first hidden vector when the encoder input is a field name. Its 26 outputs are O followed by the 25 types in table order. The standard pipeline and ONNX files use only the BIO head.
局限 / Limitations
- 合成模板上的严格 F1 高于换用 Gretel 编号写法时的识别水平。New identifier formats and wording can be missed even when synthetic validation scores are high.
- 部分覆盖仍会暴露部分值;不能只看是否触发过脱敏。A partial redaction is not full coverage.
- 未在私有生产流量上评测。No private production traffic was evaluated.
- v0.2 计划增加未见作者的文本和自由叙述样本,以改善迁移;本版不包含这些结果。v0.2 targets transfer to new writing styles; no improvement is claimed for this release.
许可 / License
本次发布的微调贡献与示例使用 Apache-2.0。Upstream weights retain their MIT terms; see base notices and attribution.
- Downloads last month
- -
Model tree for neigezhu/llm-redact-detector-mini
Base model
microsoft/Multilingual-MiniLM-L12-H384