Views
No views yet
1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM
3from peft import PeftModel
4
5BASE_MODEL = "microsoft/phi-2"
6ADAPTER_MODEL = "MinaGabriel/fol-parser-phi2-lora-adapter"
7
8# tokenizer
9tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
10
11if tokenizer.pad_token is None:
12 tokenizer.pad_token = tokenizer.eos_token
13
14base_model = AutoModelForCausalLM.from_pretrained(
15 BASE_MODEL,
16 torch_dtype=torch.float16,
17 device_map="auto",
18)
19
20base_model.config.pad_token_id = tokenizer.pad_token_id
21base_model.generation_config.pad_token_id = tokenizer.pad_token_id
22# attach the adapter
23model = PeftModel.from_pretrained(
24 base_model,
25 ADAPTER_MODEL,
26 device_map="auto",
27)
28model.eval()
29
30def generate(context: str, question: str, max_new_tokens: int = 300) -> str:
31 prompt = (
32 "<SYS>\nYou are a precise logic parser. Output [FOL] then [CONCLUSION_FOL].\n</SYS>\n"
33 "<USER>\n"
34 f"[CONTEXT]\n{context}\n\n"
35 f"[QUESTION]\n{question}\n\n"
36 "Produce the two blocks exactly as specified.\n"
37 "</USER>\n"
38 "<ASSISTANT>\n"
39 )
40
41 inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
42
43 with torch.no_grad():
44 output_ids = model.generate(
45 **inputs,
46 max_new_tokens=max_new_tokens,
47 do_sample=False,
48 temperature=0.0,
49 eos_token_id=tokenizer.eos_token_id, # explicit
50 pad_token_id=tokenizer.pad_token_id # explicit
51 )
52
53 full_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
54 return full_text.split("<ASSISTANT>\n")[-1].strip()
551print(
2 generate(
3 context="Cats are animal. dogs are animal. human are not animal. animal are awesome",
4 question="dogs awesome?"
5 )
6)1[FOL]
2cat(animal)
3dog(animal)
4¬human(animal)
5∀x (animal(x) → awesome(x))
6
7[CONCLUSION_FOL]
8awesome(dog)
9</ASSISTANT>