Download code/21168aa/src/classify_qwen3guard.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 7.06 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/21168aa/src/classify_qwen3guard.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/21168aa/src/classify_qwen3guard.py
-
curl -L -o classify_qwen3guard.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/21168aa/src/classify_qwen3guard.py
7.06 kB
| """Qwen3Guard-Gen による有害性分類(監査の第2手法)。 | |
| 辞書・ブロックリスト・共起規則とは独立した分類器として、目視サンプルや | |
| 境界文書に適用する。全件へ適用するには計算量が大きいため、 | |
| ``sample_for_review.py`` が出力するサンプルJSONLを入力にする想定。 | |
| 入力JSONL: ``{"id": ..., "url": ..., "text": ..., "match_positions": [..]}`` | |
| 出力JSONL: 入力に ``safety``(Safe/Unsafe/Controversial)、``categories``、 | |
| ``raw_output``、``elapsed_s`` を加えたもの。併せて ``<output>.manifest.json`` に | |
| モデル名・リビジョン・実行条件を記録する。 | |
| 依存関係は ``uv sync --group classifier`` で導入する(torch, transformers)。 | |
| uv run python abeja-cc-ja/src/classify_qwen3guard.py --input samples.jsonl --output classified.jsonl | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import time | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| DEFAULT_MODEL = "Qwen/Qwen3Guard-Gen-0.6B" | |
| SAFETY_RE = re.compile(r"Safety:\s*(Safe|Unsafe|Controversial)") | |
| CATEGORY_RE = re.compile( | |
| r"(Violent|Non-violent Illegal Acts|Sexual Content or Sexual Acts|PII|Suicide & Self-Harm|" | |
| r"Unethical Acts|Politically Sensitive Topics|Copyright Violation|Jailbreak|None)" | |
| ) | |
| # Qwen3Guard のカテゴリと監査項目(5〜10)の対応。 | |
| CATEGORY_TO_AUDIT_ITEM = { | |
| "Sexual Content or Sexual Acts": 5, | |
| "Violent": 6, | |
| "Suicide & Self-Harm": 6, | |
| "Unethical Acts": 7, | |
| "Non-violent Illegal Acts": 8, | |
| "Politically Sensitive Topics": 9, | |
| "Copyright Violation": 10, | |
| } | |
| def build_excerpt(text: str, positions: list[int] | None, max_chars: int, window: int = 300, head: int = 1000) -> str: | |
| """先頭と、一致位置の前後を優先して抜粋する。長文をそのまま渡さない。""" | |
| if len(text) <= max_chars: | |
| return text | |
| pieces: list[tuple[int, int]] = [(0, min(head, len(text)))] | |
| for position in (positions or [])[:4]: | |
| pieces.append((max(0, position - window), min(len(text), position + window))) | |
| pieces.sort() | |
| merged: list[list[int]] = [] | |
| for start, end in pieces: | |
| if merged and start <= merged[-1][1]: | |
| merged[-1][1] = max(merged[-1][1], end) | |
| else: | |
| merged.append([start, end]) | |
| excerpt = " … ".join(text[start:end] for start, end in merged) | |
| return excerpt[:max_chars] | |
| def parse_output(content: str) -> tuple[str | None, list[str]]: | |
| safety = SAFETY_RE.search(content) | |
| categories = [item for item in CATEGORY_RE.findall(content) if item != "None"] | |
| return (safety.group(1) if safety else None), sorted(set(categories)) | |
| def load_model(model_name: str, device: str): | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| kwargs: dict[str, Any] = {} | |
| if device == "auto": | |
| kwargs["device_map"] = "auto" | |
| try: | |
| model = AutoModelForCausalLM.from_pretrained(model_name, dtype="auto", **kwargs) | |
| except TypeError: | |
| model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", **kwargs) | |
| if device != "auto": | |
| model = model.to(device) | |
| model.eval() | |
| return tokenizer, model, torch | |
| def classify_text(tokenizer, model, torch, text: str, max_new_tokens: int = 64) -> str: | |
| messages = [{"role": "user", "content": text}] | |
| prompt = tokenizer.apply_chat_template(messages, tokenize=False) | |
| inputs = tokenizer([prompt], return_tensors="pt").to(model.device) | |
| with torch.no_grad(): | |
| generated = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False) | |
| output_ids = generated[0][len(inputs.input_ids[0]):].tolist() | |
| return tokenizer.decode(output_ids, skip_special_tokens=True) | |
| def main(argv: list[str] | None = None) -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--input", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--model", default=DEFAULT_MODEL) | |
| parser.add_argument("--device", default="auto", help="auto / cpu / mps / cuda") | |
| parser.add_argument("--max-chars", type=int, default=3000) | |
| parser.add_argument("--max-new-tokens", type=int, default=64) | |
| parser.add_argument("--limit", type=int, default=None) | |
| args = parser.parse_args(argv) | |
| tokenizer, model, torch = load_model(args.model, args.device) | |
| revision = getattr(getattr(model, "config", None), "_commit_hash", None) | |
| started = datetime.now(timezone.utc).isoformat() | |
| counts: dict[str, int] = {"Safe": 0, "Unsafe": 0, "Controversial": 0, "unparsed": 0} | |
| processed = 0 | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| with args.input.open(encoding="utf-8") as reader, args.output.open("w", encoding="utf-8") as writer: | |
| for line in reader: | |
| if not line.strip(): | |
| continue | |
| if args.limit is not None and processed >= args.limit: | |
| break | |
| record = json.loads(line) | |
| text = build_excerpt(record.get("text") or "", record.get("match_positions"), args.max_chars) | |
| t0 = time.perf_counter() | |
| raw = classify_text(tokenizer, model, torch, text, args.max_new_tokens) | |
| elapsed = time.perf_counter() - t0 | |
| safety, categories = parse_output(raw) | |
| counts[safety or "unparsed"] += 1 | |
| record.update({ | |
| "safety": safety, | |
| "categories": categories, | |
| "audit_items": sorted({CATEGORY_TO_AUDIT_ITEM[c] for c in categories if c in CATEGORY_TO_AUDIT_ITEM}), | |
| "raw_output": raw.strip(), | |
| "excerpt_chars": len(text), | |
| "elapsed_s": round(elapsed, 3), | |
| "model": args.model, | |
| }) | |
| record.pop("text", None) | |
| writer.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| processed += 1 | |
| manifest = { | |
| "model": args.model, | |
| "model_revision": revision, | |
| "device": str(model.device), | |
| "max_chars": args.max_chars, | |
| "max_new_tokens": args.max_new_tokens, | |
| "started_at_utc": started, | |
| "finished_at_utc": datetime.now(timezone.utc).isoformat(), | |
| "input": str(args.input), | |
| "output": str(args.output), | |
| "processed": processed, | |
| "counts": counts, | |
| "category_to_audit_item": CATEGORY_TO_AUDIT_ITEM, | |
| "taxonomy_note": "Qwen3Guard: Safe / Controversial / Unsafe。Controversial は文脈依存の判定。", | |
| } | |
| Path(str(args.output) + ".manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| print(json.dumps({"processed": processed, "counts": counts, "model": args.model}, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |