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
File size: 6,974 Bytes
858ec3b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | """Fine-tune a token-classification PII tagger on CPU (bf16 autocast; uses AMX when present).
Usage:
python train.py --base jhu-clsp/mmBERT-small --train a.jsonl b.jsonl --eval x.jsonl y.jsonl \
--out runs/v1 --epochs 1 --bs 16 --lr 5e-5
"""
import argparse, json, math, os, random, sys, time
import numpy as np
import torch
DEV = "cuda" if torch.cuda.is_available() else "cpu"
# bf16 autocast: fast on GPUs and on CPUs with AMX/AVX512-BF16; set PII_FP32=1 to disable.
USE_BF16 = os.environ.get("PII_FP32", "0") != "1"
from transformers import AutoTokenizer, AutoModelForTokenClassification, get_linear_schedule_with_warmup
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import BIO, L2I, read_jsonl, token_labels, decode_spans, evaluate
def encode(tok, ex, max_len):
enc = tok(ex["text"], return_offsets_mapping=True, truncation=True, max_length=max_len, return_special_tokens_mask=True)
labels = token_labels(ex["text"], ex["spans"], enc["offset_mapping"], enc["special_tokens_mask"])
# compact storage: only what training needs
return {"input_ids": np.asarray(enc["input_ids"], dtype=np.int32), "labels": np.asarray(labels, dtype=np.int16)}
def batches(encs, bs, rng, shuffle=True):
"""Length-grouped batching: sort within buckets of 50 batches to cut padding."""
idx = list(range(len(encs)))
if shuffle: rng.shuffle(idx)
chunk = bs * 50
out = []
for i in range(0, len(idx), chunk):
part = sorted(idx[i:i + chunk], key=lambda j: len(encs[j]["input_ids"]))
out += [part[k:k + bs] for k in range(0, len(part), bs)]
if shuffle: rng.shuffle(out)
return out
def collate(encs, ids, pad_id):
L = max(len(encs[i]["input_ids"]) for i in ids)
L = ((L + 31) // 32) * 32 # few distinct shapes -> bounded oneDNN cache / fragmentation
x = torch.full((len(ids), L), pad_id); m = torch.zeros((len(ids), L), dtype=torch.long); y = torch.full((len(ids), L), -100)
for r, i in enumerate(ids):
n = len(encs[i]["input_ids"])
x[r, :n] = torch.as_tensor(np.asarray(encs[i]["input_ids"], dtype=np.int64)); m[r, :n] = 1; y[r, :n] = torch.as_tensor(np.asarray(encs[i]["labels"], dtype=np.int64))
return x, m, y
@torch.no_grad()
def predict(model, tok, examples, max_len=512, bs=32):
model.eval()
encs = [tok(e["text"], return_offsets_mapping=True, truncation=True, max_length=max_len, return_special_tokens_mask=True) for e in examples]
preds = [None] * len(examples)
order = sorted(range(len(encs)), key=lambda i: len(encs[i]["input_ids"]))
for k in range(0, len(order), bs):
ids = order[k:k + bs]
for i in ids: encs[i]["labels"] = [0] * len(encs[i]["input_ids"])
x, m, _ = collate(encs, ids, tok.pad_token_id); x, m = x.to(DEV), m.to(DEV)
with torch.autocast(DEV, dtype=torch.bfloat16, enabled=USE_BF16):
logits = model(input_ids=x, attention_mask=m).logits
p = logits.argmax(-1).tolist()
for r, i in enumerate(ids):
n = len(encs[i]["input_ids"])
preds[i] = decode_spans(examples[i]["text"], encs[i]["offset_mapping"], p[r][:n], encs[i]["special_tokens_mask"])
return preds
def run_eval(model, tok, eval_sets, limit=None):
out = {}
for path in eval_sets:
ex = read_jsonl(path, limit)
out[os.path.basename(path)] = evaluate(ex, predict(model, tok, ex))
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base", default="jhu-clsp/mmBERT-small")
ap.add_argument("--train", nargs="+", required=True); ap.add_argument("--eval", nargs="+", required=True)
ap.add_argument("--out", required=True); ap.add_argument("--epochs", type=float, default=1.0)
ap.add_argument("--bs", type=int, default=16); ap.add_argument("--lr", type=float, default=5e-5)
ap.add_argument("--max-len", type=int, default=256); ap.add_argument("--max-steps", type=int, default=0)
ap.add_argument("--eval-every", type=int, default=2000); ap.add_argument("--eval-limit", type=int, default=400)
ap.add_argument("--freeze-emb", action="store_true"); ap.add_argument("--seed", type=int, default=42)
a = ap.parse_args()
torch.manual_seed(a.seed); rng = random.Random(a.seed); torch.set_num_threads(os.cpu_count())
os.makedirs(a.out, exist_ok=True)
tok = AutoTokenizer.from_pretrained(a.base)
model = AutoModelForTokenClassification.from_pretrained(a.base, num_labels=len(BIO), id2label=dict(enumerate(BIO)), label2id=L2I)
model.to(DEV); print("device:", DEV, flush=True)
if a.freeze_emb:
model.get_input_embeddings().weight.requires_grad_(False)
train = [e for p in a.train for e in read_jsonl(p)]
t0 = time.time(); encs = [encode(tok, e, a.max_len) for e in train]
print(f"encoded {len(encs)} train examples in {time.time()-t0:.0f}s", flush=True)
steps_per_epoch = math.ceil(len(encs) / a.bs)
total = a.max_steps or int(steps_per_epoch * a.epochs)
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=a.lr, weight_decay=0.01)
sch = get_linear_schedule_with_warmup(opt, int(0.06 * total), total)
log = open(os.path.join(a.out, "train_log.jsonl"), "a")
step, t0 = 0, time.time(); model.train()
while step < total:
for ids in batches(encs, a.bs, rng):
x, m, y = collate(encs, ids, tok.pad_token_id); x, m, y = x.to(DEV), m.to(DEV), y.to(DEV)
with torch.autocast(DEV, dtype=torch.bfloat16, enabled=USE_BF16):
loss = model(input_ids=x, attention_mask=m, labels=y).loss
loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); sch.step(); opt.zero_grad(); step += 1
if step % 50 == 0:
rec = {"step": step, "total": total, "loss": round(loss.item(), 4), "lr": sch.get_last_lr()[0], "elapsed_min": round((time.time() - t0) / 60, 1)}
print(json.dumps(rec), flush=True); log.write(json.dumps(rec) + "\n"); log.flush()
if step % a.eval_every == 0 or step == total:
r = run_eval(model, tok, a.eval, a.eval_limit); model.train()
summ = {k: {"f1": v["overall"]["f1"], "redact_recall": v["overall"]["redact_recall"]} for k, v in r.items()}
print(json.dumps({"step": step, "eval": summ}), flush=True); log.write(json.dumps({"step": step, "eval": summ}) + "\n"); log.flush()
model.save_pretrained(os.path.join(a.out, "ckpt")); tok.save_pretrained(os.path.join(a.out, "ckpt"))
if step >= total:
break
model.save_pretrained(a.out); tok.save_pretrained(a.out)
full = run_eval(model, tok, a.eval)
json.dump(full, open(os.path.join(a.out, "eval_full.json"), "w"), indent=1)
print(json.dumps({k: v["overall"] for k, v in full.items()}, indent=1))
print(f"done in {(time.time()-t0)/60:.1f} min")
if __name__ == "__main__":
main()
|