Download bhed/model.py from MindMapDigital/Bhed-v0.1: direct link, hf CLI and curl.
- Browser
- Download file 5.42 kB
-
https://huggingface.co/MindMapDigital/Bhed-v0.1/resolve/main/bhed/model.py
- Command line
-
hf download hf://MindMapDigital/Bhed-v0.1/bhed/model.py
-
curl -L -o model.py https://huggingface.co/MindMapDigital/Bhed-v0.1/resolve/main/bhed/model.py
5.42 kB
| """Load Bhed and redact personal data from text.""" | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from bhed.postprocess import redact as _post_redact | |
| from bhed.source import model_dir, resolve_source | |
| INSTRUCTION = ( | |
| "List every piece of personal data in the following legal query as a JSON object " | |
| "mapping typed tags ([PER_1], [ORG_1], [TAX_ID_1], ...) to the exact text." | |
| ) | |
| PROMPT_TEMPLATE = ( | |
| "Below is an instruction that describes a task, paired with an input that provides " | |
| "further context. Write a response that appropriately completes the request.\n\n" | |
| "### Instruction:\n{instruction}\n\n" | |
| "### Input:\n{input}\n\n" | |
| "### Response:\n" | |
| ) | |
| def _backend(): | |
| try: | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| except ImportError as exc: | |
| raise ImportError("Install Bhed with: pip install -e .") from exc | |
| return torch, AutoModelForCausalLM, AutoTokenizer | |
| def _resolve_local_or_hub(source: str) -> str: | |
| path = Path(source) | |
| if path.is_dir(): | |
| return str(path.resolve()) | |
| try: | |
| from huggingface_hub import snapshot_download | |
| return snapshot_download(repo_id=source, repo_type="model") | |
| except Exception: | |
| return source | |
| def _load_stack(source: str, device: str, dtype): | |
| torch, auto_model, auto_tok = _backend() | |
| root = Path(_resolve_local_or_hub(source)) | |
| tok = auto_tok.from_pretrained(str(root), use_fast=True) | |
| if tok.pad_token is None: | |
| tok.pad_token = tok.eos_token | |
| tok.padding_side = "left" | |
| adapter_cfg = root / "adapter_config.json" | |
| full_weights = root / "model.safetensors" | |
| model_kwargs = {"torch_dtype": dtype, "device_map": None} | |
| if full_weights.is_file() and not adapter_cfg.is_file(): | |
| model = auto_model.from_pretrained(str(root), **model_kwargs) | |
| else: | |
| try: | |
| from peft import PeftConfig, PeftModel | |
| except ImportError as exc: | |
| raise ImportError("Install Bhed with: pip install -e .") from exc | |
| if not adapter_cfg.is_file(): | |
| raise FileNotFoundError( | |
| f"No Bhed weights found in {root}. Expected weight files " | |
| "next to the package (see the model card Files section)." | |
| ) | |
| peft_cfg = PeftConfig.from_pretrained(str(root)) | |
| foundation = peft_cfg.base_model_name_or_path | |
| foundation_id = foundation[:-len("-bnb-4bit")] if foundation.endswith("-bnb-4bit") else foundation | |
| try: | |
| core = auto_model.from_pretrained(foundation_id, **model_kwargs) | |
| except Exception: | |
| core = auto_model.from_pretrained(foundation, **model_kwargs) | |
| model = PeftModel.from_pretrained(core, str(root)) | |
| model.to(device) | |
| model.eval() | |
| return model, tok | |
| class Bhed: | |
| """Bhed multilingual PII redaction model.""" | |
| def __init__(self, source=None, device=None, dtype=None): | |
| torch, _model_cls, _tok_cls = _backend() | |
| source = resolve_source(source) | |
| if device is None: | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| if dtype is None: | |
| if device == "cuda" and torch.cuda.is_bf16_supported(): | |
| dtype = torch.bfloat16 | |
| elif device == "cuda": | |
| dtype = torch.float16 | |
| else: | |
| dtype = torch.float32 | |
| self.device = device | |
| self.source = source | |
| self.model, self.tokenizer = _load_stack(source, device=device, dtype=dtype) | |
| def from_pretrained(cls, source, device=None, dtype=None): | |
| return cls(source, device=device, dtype=dtype) | |
| def _prompt(self, text: str) -> str: | |
| return PROMPT_TEMPLATE.format(instruction=INSTRUCTION, input=text) | |
| def extract(self, text: str, max_new_tokens: int = 256) -> str: | |
| """Return the raw JSON mapping proposed for ``text``.""" | |
| torch, _model_cls, _tok_cls = _backend() | |
| prompt = self._prompt(text) | |
| enc = self.tokenizer(prompt, return_tensors="pt") | |
| enc = {k: v.to(self.device) for k, v in enc.items()} | |
| with torch.inference_mode(): | |
| out = self.model.generate( | |
| **enc, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=False, | |
| pad_token_id=self.tokenizer.pad_token_id, | |
| eos_token_id=self.tokenizer.eos_token_id, | |
| ) | |
| new_tokens = out[0][enc["input_ids"].shape[1] :] | |
| return self.tokenizer.decode(new_tokens, skip_special_tokens=True).strip() | |
| def analyze(self, text: str, max_new_tokens: int = 256, use_backstop: bool = True) -> dict: | |
| """ | |
| Redact ``text`` and return a structured result. | |
| Keys: sanitized, mapping, model_output, blocked, flags, entities | |
| """ | |
| raw = self.extract(text, max_new_tokens=max_new_tokens) | |
| result = _post_redact(text, raw, use_backstop=use_backstop) | |
| result["model_output"] = raw | |
| result["blocked"] = (not result["flags"]["parsed"]) or bool(result["flags"]["leaks"]) | |
| return result | |
| def redact(self, text: str, max_new_tokens: int = 256, use_backstop: bool = True) -> str: | |
| """Prepare one query, run greedy decoding, and return the redacted transcript.""" | |
| return self.analyze(text, max_new_tokens=max_new_tokens, use_backstop=use_backstop)["sanitized"] | |