Remove inference.py
Browse files- inference.py +0 -174
inference.py
DELETED
|
@@ -1,174 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Bhed · MindMap Sovereign — reference inference
|
| 4 |
-
|
| 5 |
-
Install (GPU):
|
| 6 |
-
pip install "torch" "transformers>=4.45" "peft>=0.13" "accelerate" "sentencepiece" "protobuf"
|
| 7 |
-
# optional 4-bit path matching training:
|
| 8 |
-
pip install "bitsandbytes"
|
| 9 |
-
|
| 10 |
-
Install (CPU / Apple):
|
| 11 |
-
pip install "torch" "transformers>=4.45" "peft>=0.13" "accelerate" "sentencepiece" "protobuf"
|
| 12 |
-
|
| 13 |
-
Usage:
|
| 14 |
-
python inference.py "I'm Dana Brooks, account 4470912233."
|
| 15 |
-
python inference.py --base unsloth/gemma-2-2b-it --dtype bf16 "मेरा नाम दीपक चौहान है…"
|
| 16 |
-
python inference.py --compare # print Bhed vs notes for a few fixed examples
|
| 17 |
-
"""
|
| 18 |
-
from __future__ import annotations
|
| 19 |
-
|
| 20 |
-
import argparse
|
| 21 |
-
import json
|
| 22 |
-
import sys
|
| 23 |
-
from pathlib import Path
|
| 24 |
-
|
| 25 |
-
import torch
|
| 26 |
-
from peft import PeftConfig, PeftModel
|
| 27 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 28 |
-
|
| 29 |
-
# Local post-process shipped next to this file (also works after `pip install` if on PYTHONPATH)
|
| 30 |
-
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 31 |
-
import pii_postprocess as pp # noqa: E402
|
| 32 |
-
|
| 33 |
-
DEFAULT_ADAPTER = Path(__file__).resolve().parent
|
| 34 |
-
# Prefer the full-precision Unsloth twin for local Mac / CPU; 4-bit matches Colab training.
|
| 35 |
-
DEFAULT_BASE_BF16 = "unsloth/gemma-2-2b-it"
|
| 36 |
-
DEFAULT_BASE_4BIT = "unsloth/gemma-2-2b-it-bnb-4bit"
|
| 37 |
-
|
| 38 |
-
INSTRUCTION = (
|
| 39 |
-
"List every piece of personal data in the following legal query as a JSON object "
|
| 40 |
-
"mapping typed tags ([PER_1], [ORG_1], [TAX_ID_1], ...) to the exact text."
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
PROMPT_TEMPLATE = (
|
| 44 |
-
"Below is an instruction that describes a task, paired with an input that provides "
|
| 45 |
-
"further context. Write a response that appropriately completes the request.\n\n"
|
| 46 |
-
"### Instruction:\n{instruction}\n\n"
|
| 47 |
-
"### Input:\n{input}\n\n"
|
| 48 |
-
"### Response:\n"
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
def build_prompt(text: str) -> str:
|
| 53 |
-
return PROMPT_TEMPLATE.format(instruction=INSTRUCTION, input=text)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def load_bhed(
|
| 57 |
-
adapter_path: str | Path = DEFAULT_ADAPTER,
|
| 58 |
-
base_model: str | None = None,
|
| 59 |
-
load_in_4bit: bool = False,
|
| 60 |
-
dtype: str = "auto",
|
| 61 |
-
device_map: str | dict | None = "auto",
|
| 62 |
-
):
|
| 63 |
-
"""
|
| 64 |
-
Load base Gemma 2 2B IT + Bhed LoRA.
|
| 65 |
-
|
| 66 |
-
Returns (model, tokenizer).
|
| 67 |
-
"""
|
| 68 |
-
adapter_path = str(adapter_path)
|
| 69 |
-
peft_cfg = PeftConfig.from_pretrained(adapter_path)
|
| 70 |
-
|
| 71 |
-
if base_model is None:
|
| 72 |
-
base_model = peft_cfg.base_model_name_or_path if load_in_4bit else DEFAULT_BASE_BF16
|
| 73 |
-
|
| 74 |
-
tok = AutoTokenizer.from_pretrained(adapter_path, use_fast=True)
|
| 75 |
-
if tok.pad_token is None:
|
| 76 |
-
tok.pad_token = tok.eos_token
|
| 77 |
-
tok.padding_side = "left"
|
| 78 |
-
|
| 79 |
-
model_kwargs: dict = {"device_map": device_map, "trust_remote_code": False}
|
| 80 |
-
if load_in_4bit:
|
| 81 |
-
model_kwargs["quantization_config"] = BitsAndBytesConfig(
|
| 82 |
-
load_in_4bit=True,
|
| 83 |
-
bnb_4bit_compute_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float16,
|
| 84 |
-
bnb_4bit_use_double_quant=True,
|
| 85 |
-
bnb_4bit_quant_type="nf4",
|
| 86 |
-
)
|
| 87 |
-
else:
|
| 88 |
-
if dtype == "auto":
|
| 89 |
-
model_kwargs["torch_dtype"] = (
|
| 90 |
-
torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported()
|
| 91 |
-
else torch.float16 if torch.cuda.is_available()
|
| 92 |
-
else torch.float32
|
| 93 |
-
)
|
| 94 |
-
elif dtype == "bf16":
|
| 95 |
-
model_kwargs["torch_dtype"] = torch.bfloat16
|
| 96 |
-
elif dtype == "fp16":
|
| 97 |
-
model_kwargs["torch_dtype"] = torch.float16
|
| 98 |
-
else:
|
| 99 |
-
model_kwargs["torch_dtype"] = torch.float32
|
| 100 |
-
if device_map is None:
|
| 101 |
-
model_kwargs.pop("device_map")
|
| 102 |
-
|
| 103 |
-
base = AutoModelForCausalLM.from_pretrained(base_model, **model_kwargs)
|
| 104 |
-
model = PeftModel.from_pretrained(base, adapter_path)
|
| 105 |
-
model.eval()
|
| 106 |
-
return model, tok
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
@torch.inference_mode()
|
| 110 |
-
def generate_mapping(model, tok, text: str, max_new_tokens: int = 256) -> str:
|
| 111 |
-
prompt = build_prompt(text)
|
| 112 |
-
enc = tok(prompt, return_tensors="pt")
|
| 113 |
-
enc = {k: v.to(model.device) for k, v in enc.items()}
|
| 114 |
-
out = model.generate(
|
| 115 |
-
**enc,
|
| 116 |
-
max_new_tokens=max_new_tokens,
|
| 117 |
-
do_sample=False,
|
| 118 |
-
pad_token_id=tok.pad_token_id,
|
| 119 |
-
eos_token_id=tok.eos_token_id,
|
| 120 |
-
)
|
| 121 |
-
gen = out[0][enc["input_ids"].shape[1] :]
|
| 122 |
-
return tok.decode(gen, skip_special_tokens=True).strip()
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def redact(model, tok, text: str, use_backstop: bool = True) -> dict:
|
| 126 |
-
raw = generate_mapping(model, tok, text)
|
| 127 |
-
result = pp.redact(text, raw, use_backstop=use_backstop)
|
| 128 |
-
result["model_output"] = raw
|
| 129 |
-
result["blocked"] = (not result["flags"]["parsed"]) or bool(result["flags"]["leaks"])
|
| 130 |
-
return result
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
def main() -> None:
|
| 134 |
-
ap = argparse.ArgumentParser(description="Bhed · MindMap Sovereign PII redaction")
|
| 135 |
-
ap.add_argument("text", nargs="*", help="Query to redact")
|
| 136 |
-
ap.add_argument("--adapter", default=str(DEFAULT_ADAPTER), help="Path or HF id of the Bhed adapter")
|
| 137 |
-
ap.add_argument("--base", default=None, help=f"Base model id (default: {DEFAULT_BASE_BF16} or adapter config if --4bit)")
|
| 138 |
-
ap.add_argument("--4bit", dest="fourbit", action="store_true", help=f"Load {DEFAULT_BASE_4BIT} in 4-bit")
|
| 139 |
-
ap.add_argument("--dtype", choices=["auto", "bf16", "fp16", "fp32"], default="auto")
|
| 140 |
-
ap.add_argument("--no-backstop", action="store_true")
|
| 141 |
-
ap.add_argument("--json", action="store_true", help="Print full JSON result")
|
| 142 |
-
args = ap.parse_args()
|
| 143 |
-
|
| 144 |
-
text = " ".join(args.text).strip() or sys.stdin.read().strip()
|
| 145 |
-
if not text:
|
| 146 |
-
ap.error("pass text as arguments or on stdin")
|
| 147 |
-
|
| 148 |
-
model, tok = load_bhed(
|
| 149 |
-
adapter_path=args.adapter,
|
| 150 |
-
base_model=args.base,
|
| 151 |
-
load_in_4bit=args.fourbit,
|
| 152 |
-
dtype=args.dtype,
|
| 153 |
-
)
|
| 154 |
-
result = redact(model, tok, text, use_backstop=not args.no_backstop)
|
| 155 |
-
|
| 156 |
-
if args.json:
|
| 157 |
-
print(json.dumps({
|
| 158 |
-
"blocked": result["blocked"],
|
| 159 |
-
"sanitized": result["sanitized"],
|
| 160 |
-
"mapping": result["mapping"],
|
| 161 |
-
"model_output": result["model_output"],
|
| 162 |
-
"flags": {k: v for k, v in result["flags"].items() if v and k != "parsed"},
|
| 163 |
-
}, ensure_ascii=False, indent=2))
|
| 164 |
-
else:
|
| 165 |
-
print(result["sanitized"])
|
| 166 |
-
print("---")
|
| 167 |
-
print(json.dumps(result["mapping"], ensure_ascii=False))
|
| 168 |
-
if result["blocked"]:
|
| 169 |
-
print("BLOCKED:", result["flags"].get("leaks") or "unparseable", file=sys.stderr)
|
| 170 |
-
sys.exit(2)
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
if __name__ == "__main__":
|
| 174 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|