Download inference.py from gussieIsASuccessfulWarlock/online-integrity-classifier: direct link, hf CLI and curl.
- Browser
- Download file 2.48 kB
-
https://huggingface.co/gussieIsASuccessfulWarlock/online-integrity-classifier/resolve/main/inference.py
- Command line
-
hf download hf://gussieIsASuccessfulWarlock/online-integrity-classifier/inference.py
-
curl -L -o inference.py https://huggingface.co/gussieIsASuccessfulWarlock/online-integrity-classifier/resolve/main/inference.py
2.48 kB
| """Run the Online Integrity Classifier on replies and their discussion context.""" | |
| import json | |
| from pathlib import Path | |
| import torch | |
| from safetensors.torch import load_model | |
| from transformers import AutoConfig, AutoModel, AutoTokenizer | |
| class OnlineIntegrityClassifier(torch.nn.Module): | |
| def __init__(self, config, groups): | |
| super().__init__() | |
| self.enc = AutoModel.from_config(config) | |
| self.heads = torch.nn.ModuleDict({ | |
| group: torch.nn.Linear(config.hidden_size, len(labels)) | |
| for group, labels in groups.items() | |
| }) | |
| def forward(self, **inputs): | |
| hidden = self.enc(**inputs).last_hidden_state | |
| mask = inputs["attention_mask"].unsqueeze(-1).to(hidden.dtype) | |
| pooled = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1) | |
| return {group: head(pooled) for group, head in self.heads.items()} | |
| def load(directory, device="cpu"): | |
| directory = Path(directory) | |
| groups = json.loads((directory / "info.json").read_text())["groups"] | |
| model = OnlineIntegrityClassifier(AutoConfig.from_pretrained(directory), groups) | |
| load_model(model, directory / "model.safetensors", strict=True) | |
| tokenizer = AutoTokenizer.from_pretrained(directory) | |
| return model.to(device).eval(), tokenizer, groups | |
| def classify( | |
| model, | |
| tokenizer, | |
| groups, | |
| *, | |
| title, | |
| replying_to, | |
| reply, | |
| community=None, | |
| subreddit=None, | |
| ): | |
| """Return the primary label and probabilities for each classification head.""" | |
| if (community is None) == (subreddit is None): | |
| raise ValueError("Provide exactly one of community or subreddit.") | |
| location = f"forum: {community}" if subreddit is None else f"r/{subreddit}" | |
| context = f"{location} | post: {title[:240]} | replying to: {replying_to[:900]}" | |
| device = next(model.parameters()).device | |
| inputs = tokenizer( | |
| context, | |
| reply[:1800], | |
| truncation=True, | |
| max_length=384, | |
| return_tensors="pt", | |
| ).to(device) | |
| results = {} | |
| for group, logits in model(**inputs).items(): | |
| labels = groups[group] | |
| scores = logits[0].float() | |
| probabilities = scores.softmax(dim=-1).tolist() | |
| results[group] = { | |
| "primary": labels[scores.argmax().item()], | |
| "probs": { | |
| label: round(probability, 4) | |
| for label, probability in zip(labels, probabilities) | |
| }, | |
| } | |
| return results | |