Ashishkr commited on
Commit
59e3834
1 Parent(s): d397ed2

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +72 -0
model.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from threading import Thread
2
+ from typing import Iterator
3
+
4
+ import torch
5
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
+
7
+ model_id = 'Ashishkr/llama2_medical_consultation'
8
+
9
+ from peft import PeftModel, PeftConfig
10
+ from transformers import AutoModelForCausalLM
11
+ from transformers import AutoTokenizer
12
+ import torch
13
+
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+
16
+ config = PeftConfig.from_pretrained("Ashishkr/llama2_medical_consultation")
17
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
18
+ model = PeftModel.from_pretrained(model, "Ashishkr/llama2_medical_consultation").to(device)
19
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
20
+
21
+
22
+ def get_prompt(message: str, chat_history: list[tuple[str, str]],
23
+ system_prompt: str) -> str:
24
+ texts = [f'<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n']
25
+ # The first user input is _not_ stripped
26
+ do_strip = False
27
+ for user_input, response in chat_history:
28
+ user_input = user_input.strip() if do_strip else user_input
29
+ do_strip = True
30
+ texts.append(f'{user_input} [/INST] {response.strip()} </s><s>[INST] ')
31
+ message = message.strip() if do_strip else message
32
+ texts.append(f'{message} [/INST]')
33
+ return ''.join(texts)
34
+
35
+
36
+ def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
37
+ prompt = get_prompt(message, chat_history, system_prompt)
38
+ input_ids = tokenizer([prompt], return_tensors='np', add_special_tokens=False)['input_ids']
39
+ return input_ids.shape[-1]
40
+
41
+
42
+ def run(message: str,
43
+ chat_history: list[tuple[str, str]],
44
+ system_prompt: str,
45
+ max_new_tokens: int = 1024,
46
+ temperature: float = 0.8,
47
+ top_p: float = 0.95,
48
+ top_k: int = 50) -> Iterator[str]:
49
+ prompt = get_prompt(message, chat_history, system_prompt)
50
+ inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')
51
+
52
+ streamer = TextIteratorStreamer(tokenizer,
53
+ timeout=10.,
54
+ skip_prompt=True,
55
+ skip_special_tokens=True)
56
+ generate_kwargs = dict(
57
+ inputs,
58
+ streamer=streamer,
59
+ max_new_tokens=max_new_tokens,
60
+ do_sample=True,
61
+ top_p=top_p,
62
+ top_k=top_k,
63
+ temperature=temperature,
64
+ num_beams=1,
65
+ )
66
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
67
+ t.start()
68
+
69
+ outputs = []
70
+ for text in streamer:
71
+ outputs.append(text)
72
+ yield ''.join(outputs)