Token Classification
Transformers
ONNX
Safetensors
Transformers.js
modernbert
pii
pii-detection
ner
privacy
anonymization
redaction
de-identification
chinese
japanese
korean
cjk
mmbert
个人信息
脱敏
Eval Results (legacy)
Instructions to use CheezOne/pii-detector-cjk-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use CheezOne/pii-detector-cjk-small with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="CheezOne/pii-detector-cjk-small")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("CheezOne/pii-detector-cjk-small") model = AutoModelForTokenClassification.from_pretrained("CheezOne/pii-detector-cjk-small", device_map="auto") - Transformers.js
How to use CheezOne/pii-detector-cjk-small with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('token-classification', 'CheezOne/pii-detector-cjk-small'); - Notebooks
- Google Colab
- Kaggle
Download scripts/export_onnx.py from CheezOne/pii-detector-cjk-small: direct link, hf CLI and curl.
- Browser
- Download file 3.82 kB
-
https://huggingface.co/CheezOne/pii-detector-cjk-small/resolve/main/scripts/export_onnx.py
- Command line
-
hf download hf://CheezOne/pii-detector-cjk-small/scripts/export_onnx.py
-
curl -L -o export_onnx.py https://huggingface.co/CheezOne/pii-detector-cjk-small/resolve/main/scripts/export_onnx.py
3.82 kB
| """Export a token-classification model to ONNX (fp32 + int8 dynamic quant) and check parity. | |
| Layout follows transformers.js / onnx-community conventions: | |
| <model_dir>/onnx/model.onnx, <model_dir>/onnx/model_quantized.onnx | |
| Usage: python export_onnx.py <model_dir> [--test test.jsonl] | |
| """ | |
| import argparse, json, os, sys, time | |
| import numpy as np | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForTokenClassification | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from common import read_jsonl, decode_spans, evaluate | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("model_dir"); ap.add_argument("--test", nargs="*", default=[]); ap.add_argument("--limit", type=int, default=300) | |
| a = ap.parse_args() | |
| out = os.path.join(a.model_dir, "onnx"); os.makedirs(out, exist_ok=True) | |
| tok = AutoTokenizer.from_pretrained(a.model_dir) | |
| model = AutoModelForTokenClassification.from_pretrained(a.model_dir).eval() | |
| dummy = tok(["示例文本 example text 13812345678", "短"], return_tensors="pt", padding=True) | |
| fp32 = os.path.join(out, "model.onnx") | |
| with torch.no_grad(): | |
| torch.onnx.export(model, (dummy["input_ids"], dummy["attention_mask"]), fp32, | |
| input_names=["input_ids", "attention_mask"], output_names=["logits"], | |
| dynamic_axes={"input_ids": {0: "batch", 1: "seq"}, "attention_mask": {0: "batch", 1: "seq"}, "logits": {0: "batch", 1: "seq"}}, | |
| opset_version=17, dynamo=False) | |
| from onnxruntime.quantization import quantize_dynamic, QuantType | |
| q = os.path.join(out, "model_quantized.onnx") | |
| # Selective int8: embeddings (Gather) + attention MatMuls, per-channel. ModernBERT's GeGLU MLPs | |
| # have activation outliers; quantizing them cost ~8 F1 points in our sweep (scripts/quant_sweep.py), | |
| # this recipe costs ~0.4. The classifier head stays fp32. | |
| import onnx | |
| g = onnx.load(fp32, load_external_data=False) | |
| mm = [n.name for n in g.graph.node if n.op_type in ("MatMul", "Gemm")] | |
| exclude = [n for n in mm if "mlp" in n or "classifier" in n or "/head/" in n] | |
| quantize_dynamic(fp32, q, weight_type=QuantType.QInt8, per_channel=True, | |
| op_types_to_quantize=["Gather", "MatMul"], nodes_to_exclude=exclude) | |
| import onnxruntime as ort | |
| report = {"size_mb": {"fp32": round(os.path.getsize(fp32) / 1e6, 1), "int8": round(os.path.getsize(q) / 1e6, 1)}} | |
| for name, path in [("fp32", fp32), ("int8", q)]: | |
| sess = ort.InferenceSession(path, providers=["CPUExecutionProvider"]) | |
| with torch.no_grad(): | |
| ref = model(**dummy).logits.numpy() | |
| got = sess.run(None, {"input_ids": dummy["input_ids"].numpy(), "attention_mask": dummy["attention_mask"].numpy()})[0] | |
| report[f"{name}_max_abs_diff"] = float(np.abs(ref - got).max()) | |
| for t in a.test: | |
| ex = read_jsonl(t, a.limit); preds = []; t0 = time.time() | |
| for e in ex: | |
| enc = tok(e["text"], return_offsets_mapping=True, return_special_tokens_mask=True, truncation=True, max_length=512) | |
| logits = sess.run(None, {"input_ids": np.array([enc["input_ids"]], dtype=np.int64), "attention_mask": np.ones((1, len(enc["input_ids"])), dtype=np.int64)})[0][0] | |
| preds.append(decode_spans(e["text"], enc["offset_mapping"], logits.argmax(-1).tolist(), enc["special_tokens_mask"])) | |
| r = evaluate(ex, preds)["overall"] | |
| report[f"{name}:{os.path.basename(t)}"] = {"f1": r["f1"], "redact_recall": r["redact_recall"], "ms_per_example_bs1": round(1000 * (time.time() - t0) / len(ex), 1)} | |
| print(json.dumps(report, indent=1)) | |
| json.dump(report, open(os.path.join(a.model_dir, "onnx_report.json"), "w"), indent=1) | |
| if __name__ == "__main__": | |
| main() | |