Views
No views yet
pip install torch transformers trl peft1from transformers import AutoTokenizer
2from trl import AutoModelForCausalLMWithValueHead
3from peft import LoraConfig
4
5tokenizer_kwargs = {
6 "padding": "max_length",
7 "truncation": True,
8 "return_tensors": "pt",
9 "padding_side": "left"
10 }
11
12tokenizer = AutoTokenizer.from_pretrained("hanyinwang/layer-project-diagnostic-mistral", **tokenizer_kwargs)
13tokenizer.pad_token = tokenizer.eos_token
14
15generation_kwargs = {
16 "min_length": -1,
17 "top_k": 40,
18 "top_p": 0.95,
19 "do_sample": True,
20 "pad_token_id": tokenizer.eos_token_id,
21 "max_new_tokens":11,
22 "temperature":0.1,
23 "repetition_penalty":1.2
24}
25
26model = AutoModelForCausalLMWithValueHead.from_pretrained("hanyinwang/layer-project-diagnostic-mistral").cuda()
27
28def format_prompt_mistral(text, condition):
29 prompt = """<s>[INST]You are a medical doctor specialized in %s diagnosis.
30From the provided document, assert if the patient historically and currently has %s.
31For each condition, only pick from "YES", "NO", or "MAYBE". And you must follow format without anything further. The results have to be directly parseable with python json.loads().
32Sample output: {"%s": "MAYBE"}
33Never output anything beyond the format.[/INST]
34Provided document: %s"""%(condition, condition, condition, text)
35 return prompt
36
37query_tensors = tokenizer.encode(format_prompt_mistral(<note>, <condition>), return_tensors="pt")
38# <note>: clinical note
39# <condition>: "cancer" or "diabetes"
40prompt_length = query_tensors.shape[1]
41
42outputs = model.generate(query_tensors.cuda(), **generation_kwargs)
43response = tokenizer.decode(outputs[0][prompt_length:])