Views
No views yet
pip install transformers peft torch1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from peft import PeftModel
4
5# Load base model and tokenizer
6base_model = "Qwen/Qwen3-8B"
7tokenizer = AutoTokenizer.from_pretrained(base_model)
8model = AutoModelForCausalLM.from_pretrained(
9 base_model,
10 torch_dtype=torch.bfloat16,
11 device_map="auto",
12)
13
14# Load LoRA adapter
15model = PeftModel.from_pretrained(model, "wjbmattingly/Qwen3-8B-Coref-NER")
16
17# Sample text
18text = """Alcuin of York was an Anglo-Latin scholar and teacher. He was born around 735 and became the student of Archbishop Ecgbert at York. At the invitation of Charlemagne, he became a leading scholar at the Carolingian court.
19
20In this role as adviser, he took issue with the emperor's policy of forcing pagans to be baptised on pain of death. His arguments seem to have prevailed – Charlemagne abolished the death penalty for paganism in 797."""
21
22# Create prompt
23prompt = "Resolve all pronouns in this text, replacing them with the full entity names. Also identify any entity references you find.\n\n" + text
24
25messages = [{"role": "user", "content": prompt}]
26input_text = tokenizer.apply_chat_template(
27 messages,
28 tokenize=False,
29 add_generation_prompt=True,
30 enable_thinking=False # Disable thinking mode
31)
32
33# Generate
34inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
35with torch.no_grad():
36 outputs = model.generate(
37 **inputs,
38 max_new_tokens=2048,
39 do_sample=False,
40 pad_token_id=tokenizer.pad_token_id,
41 )
42
43response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
44print(response)1import torch
2import re
3from transformers import AutoModelForCausalLM, AutoTokenizer
4from peft import PeftModel
5
6def parse_entity_mappings(response):
7 """Parse model response to extract resolved text and entity mappings."""
8 if "NEW ENTITY MAPPINGS:" in response:
9 parts = response.split("NEW ENTITY MAPPINGS:")
10 resolved_text = parts[0].strip()
11 mappings_text = parts[1].strip() if len(parts) > 1 else ""
12
13 entities = {}
14 for line in mappings_text.split("\n"):
15 line = line.strip()
16 if line.startswith("-"):
17 match = re.match(r'-\s*([^:]+):\s*\[([^\]]*)\]', line)
18 if match:
19 entity_name = match.group(1).strip()
20 variants = re.findall(r'"([^"]*)"', match.group(2))
21 if variants:
22 entities[entity_name] = variants
23 return resolved_text, entities
24 return response.strip(), {}
25
26def format_entities_for_prompt(entities):
27 """Format known entities for the prompt."""
28 lines = ["Entities and their possible references:"]
29 for entity_name, variants in entities.items():
30 variants_str = ", ".join(f'"{v}"' for v in variants)
31 lines.append(f"- {entity_name}: [{variants_str}]")
32 return "\n".join(lines)
33
34# Load model
35base_model = "Qwen/Qwen3-8B"
36tokenizer = AutoTokenizer.from_pretrained(base_model)
37model = AutoModelForCausalLM.from_pretrained(base_model, torch_dtype=torch.bfloat16, device_map="auto")
38model = PeftModel.from_pretrained(model, "wjbmattingly/Qwen3-8B-Coref-NER")
39
40# Your document
41text = """Alcuin of York was an Anglo-Latin scholar and teacher. He was born around 735 and became the student of Archbishop Ecgbert at York. At the invitation of Charlemagne, he became a leading scholar at the Carolingian court.
42
43In this role as adviser, he took issue with the emperor's policy of forcing pagans to be baptised on pain of death. His arguments seem to have prevailed – Charlemagne abolished the death penalty for paganism in 797."""
44
45# Split into paragraphs
46paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
47resolved_paragraphs = []
48cumulative_entities = {}
49
50for i, paragraph in enumerate(paragraphs):
51 print(f"Processing paragraph {i+1}/{len(paragraphs)}...")
52
53 # Build prompt
54 if i == 0:
55 prompt = f"Resolve all pronouns in this text, replacing them with the full entity names. Also identify any entity references you find.\n\n{paragraph}"
56 else:
57 context = "\n\n".join(resolved_paragraphs[max(0, i-2):i])
58 if cumulative_entities:
59 known_str = format_entities_for_prompt(cumulative_entities)
60 prompt = f"Known {known_str}\n\nGiven this context of preceding text (already resolved):\n\n{context}\n\nResolve all pronouns in this paragraph using the known entities. Also identify any NEW entity references:\n\n{paragraph}"
61 else:
62 prompt = f"Given this context of preceding text (already resolved):\n\n{context}\n\nResolve all pronouns in this paragraph. Also identify any NEW entity references:\n\n{paragraph}"
63
64 messages = [{"role": "user", "content": prompt}]
65 input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
66 inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
67
68 with torch.no_grad():
69 outputs = model.generate(**inputs, max_new_tokens=2048, do_sample=False, pad_token_id=tokenizer.pad_token_id)
70
71 response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
72
73 # Parse response
74 resolved, new_entities = parse_entity_mappings(response)
75 resolved_paragraphs.append(resolved)
76
77 # Update cumulative entities
78 for entity_name, variants in new_entities.items():
79 if entity_name not in cumulative_entities:
80 cumulative_entities[entity_name] = set()
81 cumulative_entities[entity_name].update(variants)
82
83 if new_entities:
84 print(f" New entities found: {new_entities}")
85
86# Final output
87print("\n" + "="*50)
88print("RESOLVED TEXT:")
89print("="*50)
90print("\n\n".join(resolved_paragraphs))
91
92print("\n" + "="*50)
93print("ALL ENTITIES:")
94print("="*50)
95for entity, variants in cumulative_entities.items():
96 print(f" {entity}: {list(variants)}")Alcuin of York was an Anglo-Latin scholar and teacher. He was born around 735 and became the student of Archbishop Ecgbert at York. At the invitation of Charlemagne, he became a leading scholar at the Carolingian court.
In this role as adviser, he took issue with the emperor's policy of forcing pagans to be baptised on pain of death. His arguments seem to have prevailed – Charlemagne abolished the death penalty for paganism in 797.Alcuin of York was an Anglo-Latin scholar and teacher. Alcuin of York was born around 735 and became the student of Archbishop Ecgbert at York. At the invitation of Charlemagne, Alcuin of York became a leading scholar at the Carolingian court.
In Alcuin of York's role as adviser, Alcuin of York took issue with Charlemagne's policy of forcing pagans to be baptised on pain of death. Alcuin of York's arguments seem to have prevailed – Charlemagne abolished the death penalty for paganism in 797.
NEW ENTITY MAPPINGS:
- Alcuin of York: ["He", "his", "he"]
- Charlemagne: ["the emperor"]