imperium / inference_example.py
lordpizzo's picture
Upload inference_example.py with huggingface_hub
b5a2c0f verified
Raw History Blame Contribute Delete
4.59 kB
#!/usr/bin/env python3
"""Imperium (triage fine-tune) — inference example that reproduces the
measured numbers: one d3 runtime + three task-specialist LoRA adapters
(urgency / category / decision), selected per question.
Requires: the vllm-sr/d3 model package on disk (it ships d3_runtime.py and
d3_format.py), plus `peft`, `transformers`, `torch`, `flash-linear-attention`
(optional, faster) — see the base model card.
Usage:
python3 inference_example.py --d3 /path/to/d3 --state-file state.txt
"""
import argparse
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent)) # adapters/ lives next to this file
ADAPTERS = {
"urgencia": "adapters/urgency",
"categoria": "adapters/category",
"decisao": "adapters/decision",
}
INSTR = {
"categoria": "Qual a categoria principal do chamado?",
"decisao": "Qual decisão tomar para este caso?",
"urgencia": "Qual a urgência? (0=baixa, 3=crítica)",
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--d3", required=True, help="vllm-sr/d3 package dir (local)")
ap.add_argument("--state-file", required=True, help="plain-text ticket state")
ap.add_argument("--device", default="cuda:0")
args = ap.parse_args()
import torch
import torch.nn.functional as F
from d3_runtime import D3
from d3_format import render as fmt_render
from transformers import AutoTokenizer
from peft import PeftModel
d3 = D3.from_pretrained(args.d3, device=args.device)
tok = AutoTokenizer.from_pretrained(args.d3)
codes = json.loads((Path(args.d3) / "decision_config.json").read_text())["codes"]
# attach the three specialists as named adapters (switch per task)
first = True
for task, path in ADAPTERS.items():
if first:
d3.backbone = PeftModel.from_pretrained(d3.backbone, path, adapter_name=task)
first = False
else:
d3.backbone.load_adapter(path, adapter_name=task)
d3.backbone.eval()
state = Path(args.state_file).read_text()
# default schema (this model was trained on the 3-question support schema;
# any-schema typed questions work with the base d3 prompt contract)
QUESTIONS = {
"categoria": {"type": "choice", "instructions": INSTR["categoria"],
"criteria": {o: None for o in ("reembolso", "troca_devolucao",
"fraude_suspeita", "prazo_envio", "pagamento", "frete",
"produto_defeito", "chargeback", "duvida_comercial", "outro",
"incidente", "whatsapp_meta", "bug_produto", "integracao",
"conta_config", "plano_creditos", "duvida_produto")}},
"decisao": {"type": "choice", "instructions": INSTR["decisao"],
"criteria": {o: None for o in ("aprovar", "rejeitar", "escalar",
"executar_acao", "pedir_mais_info")}},
"urgencia": {"type": "choice", "instructions": INSTR["urgencia"],
"criteria": {o: None for o in ("0 - baixa", "1 - moderada",
"2 - alta", "3 - crítica")}},
}
out = {}
for task, spec in QUESTIONS.items():
d3.backbone.set_adapter(task) # specialist for this question
text = fmt_render(tok, state, spec, codes)
seq = tok.encode(text, add_special_tokens=False)[: (d3.max_length or 8192)]
W = len(seq)
ids = torch.full((1, W), d3.pad_id, dtype=torch.long)
ids[0] = torch.as_tensor(seq, dtype=torch.long)
mask = torch.ones((1, W), dtype=torch.long)
ids, mask = ids.to(d3.device), mask.to(d3.device)
with torch.inference_mode():
embeds = d3.backbone.get_input_embeddings()(ids)
hidden = d3.encoder(embeds, mask)[:, -1]
logits = hidden.float() @ d3.readout.T
limit = torch.as_tensor([[len(spec["criteria"])]], device=d3.device)
logits = logits.masked_fill(
torch.arange(MAX_OPTIONS, device=d3.device)[None] >= limit, float("-inf"))
probs = F.softmax(logits, dim=-1)[0].tolist()
criteria = list(spec["criteria"])
picked = criteria[max(range(len(criteria)), key=lambda i: probs[i])]
out[task] = {"answer": picked,
"probabilities": {criteria[i]: round(probs[i], 4)
for i in range(len(criteria))}}
print(json.dumps(out, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()