Views
No views yet
rewritten_termcontext_marked, where the target mention is explicitly enclosed by <mention>...</mention>candidates, a top-10 candidate list containing:
concept_idconcept_namesemantic_tagconcept_id in the <answer>...</answer> blockdo_sample=True<answer>...</answer> span1from transformers import AutoTokenizer, AutoModelForCausalLM
2from peft import PeftModel
3import torch
4import json
5
6base_model_path = "Qwen/Qwen3-8B"
7adapter_path = "Tao-AI-Informatics/Qwen3-8B-LoRA-ContextBioEL-Reranker-SFT"
8
9tokenizer = AutoTokenizer.from_pretrained(base_model_path, trust_remote_code=True)
10base_model = AutoModelForCausalLM.from_pretrained(
11 base_model_path,
12 torch_dtype=torch.bfloat16,
13 device_map="auto",
14 trust_remote_code=True,
15)
16model = PeftModel.from_pretrained(base_model, adapter_path)
17
18cands_json = json.dumps([
19 {"concept_id": "22298006", "concept_name": "myocardial infarction", "semantic_tag": "disorder"},
20 {"concept_id": "57054005", "concept_name": "acute myocardial infarction", "semantic_tag": "disorder"}
21], indent=2)
22
23messages = [
24 {
25 "role": "system",
26 "content": (
27 "You are a clinical concept normalization model that reranks a top-10 candidate list using context and semantic tags.\n\n"
28 "Inputs you will receive:\n"
29 "- rewritten_term\n"
30 "- context_marked with <mention>...</mention>\n"
31 "- candidates: top-10 items (concept_id, concept_name, semantic_tag)\n\n"
32 "Think before answer\n\n"
33 "Output ONLY:\n"
34 "<think>...</think>\n"
35 "<answer>...</answer>\n\n"
36 "In <think>, write a detailed reasoning with these parts:\n"
37 "1) Context interpretation: what the mention means in this note (section cues, negation, experiencer, temporality).\n"
38 "2) Type inference: what semantic type/tag is expected (and why other tags are wrong).\n"
39 "3) Candidate comparison: evaluate multiple candidates. Note over-specific vs too-general, added qualifiers, and tag alignment.\n"
40 "4) Decision: justify the final choice.\n\n"
41 "In <answer>, use exactly one of:\n"
42 "- <answer><concept_id></answer>\n"
43 ),
44 },
45 {
46 "role": "user",
47 "content": (
48 "Task: Choose the best concept_id from candidates.\n\n"
49 "rewritten_term:\nacute myocardial infarction\n\n"
50 "context_marked:\n"
51 "The patient was admitted for <mention>heart attack</mention> yesterday.\n\n"
52 f"candidates (top10; no scores):\n{cands_json}"
53 ),
54 },
55]
56
57text = tokenizer.apply_chat_template(
58 messages,
59 tokenize=False,
60 add_generation_prompt=True,
61)
62
63inputs = tokenizer(text, return_tensors="pt").to(model.device)
64
65with torch.no_grad():
66 outputs = model.generate(
67 **inputs,
68 max_new_tokens=512,
69 do_sample=True,
70 temperature=0.6,
71 top_p=0.95,
72 )
73
74print(tokenizer.decode(outputs[0], skip_special_tokens=False))