Instructions to use krystv/nomen-ai with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use krystv/nomen-ai with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
Add controlled inference engine
Browse files- nomen_ai/inference.py +44 -0
nomen_ai/inference.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled generation engine: control vector + creativity decoding + anti-dup filter."""
|
| 2 |
+
from typing import List
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
+
from .control import ControlVector, SYSTEM_PROMPT
|
| 6 |
+
from .antidup import AntiDuplicationMatrix
|
| 7 |
+
from .phonetics import count_syllables, char_len
|
| 8 |
+
|
| 9 |
+
def creativity_to_decoding(c: float) -> dict:
|
| 10 |
+
if c <= 0.25:
|
| 11 |
+
return dict(do_sample=False, penalty_alpha=0.6, top_k=5, repetition_penalty=1.2, no_repeat_ngram_size=2)
|
| 12 |
+
return dict(do_sample=True, temperature=round(0.7+c*1.3,2), min_p=round(max(0.02,0.12-c*0.08),3), repetition_penalty=1.25, no_repeat_ngram_size=2)
|
| 13 |
+
|
| 14 |
+
class NomenAI:
|
| 15 |
+
def __init__(self, model_id, base_model=None, device=None, antidup=None):
|
| 16 |
+
self.device=device or ('cuda' if torch.cuda.is_available() else 'cpu')
|
| 17 |
+
self.tok=AutoTokenizer.from_pretrained(model_id if not base_model else base_model)
|
| 18 |
+
if base_model:
|
| 19 |
+
from peft import PeftModel
|
| 20 |
+
base=AutoModelForCausalLM.from_pretrained(base_model, torch_dtype=torch.float16).to(self.device)
|
| 21 |
+
self.model=PeftModel.from_pretrained(base, model_id).to(self.device)
|
| 22 |
+
else:
|
| 23 |
+
self.model=AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16).to(self.device)
|
| 24 |
+
self.model.eval(); self.antidup=antidup or AntiDuplicationMatrix()
|
| 25 |
+
def _prompt_ids(self, cv: ControlVector):
|
| 26 |
+
msgs=[{'role':'system','content':SYSTEM_PROMPT},{'role':'user','content':cv.to_prompt()}]
|
| 27 |
+
text=self.tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
| 28 |
+
return self.tok(text, return_tensors='pt').to(self.device)
|
| 29 |
+
@torch.no_grad()
|
| 30 |
+
def generate(self, cv: ControlVector, n=10, tol_syl=1, tol_len=3, enforce=True, max_new_tokens=12) -> List[dict]:
|
| 31 |
+
cv.validate(); enc=self._prompt_ids(cv); dec=creativity_to_decoding(cv.creativity)
|
| 32 |
+
out=self.model.generate(**enc, num_return_sequences=n*3, max_new_tokens=max_new_tokens, pad_token_id=self.tok.eos_token_id, **dec)
|
| 33 |
+
gen=out[:, enc['input_ids'].shape[1]:]
|
| 34 |
+
results=[]; seen=set()
|
| 35 |
+
for g in gen:
|
| 36 |
+
txt=self.tok.decode(g, skip_special_tokens=True).strip(); name=''.join(ch for ch in (txt.split()[0] if txt else '') if ch.isalpha())
|
| 37 |
+
if not name or name.lower() in seen: continue
|
| 38 |
+
nov=self.antidup.novelty(name); syl=count_syllables(name); clen=char_len(name)
|
| 39 |
+
ok=self.antidup.is_novel(name)
|
| 40 |
+
if enforce: ok=ok and abs(syl-cv.syllables)<=tol_syl and abs(clen-cv.char_len)<=tol_len
|
| 41 |
+
if ok:
|
| 42 |
+
seen.add(name.lower()); results.append({'name':name.capitalize(),'novelty':nov,'syllables':syl,'chars':clen})
|
| 43 |
+
if len(results)>=n: break
|
| 44 |
+
return sorted(results, key=lambda r:-r['novelty'])
|