shauray commited on
Commit
2cea330
1 Parent(s): d27d78e

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +81 -0
model.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 'abacaj/starcoderbase-1b-sft'
8
+
9
+ if torch.cuda.is_available():
10
+ config = AutoConfig.from_pretrained(model_id)
11
+ config.pretraining_tp = 1
12
+ model = AutoModelForCausalLM.from_pretrained(
13
+ model_id,
14
+ config=config,
15
+ torch_dtype=torch.float16,
16
+ load_in_4bit=True,
17
+ device_map='cuda',
18
+ )
19
+ else:
20
+ config = AutoConfig.from_pretrained(model_id)
21
+ config.pretraining_tp = 1
22
+ model = AutoModelForCausalLM.from_pretrained(
23
+ model_id,
24
+ config=config,
25
+ torch_dtype=torch.float32,
26
+ load_in_4bit=True,
27
+ )
28
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
29
+
30
+
31
+ def get_prompt(message: str, chat_history: list[tuple[str, str]],
32
+ system_prompt: str) -> str:
33
+ texts = [f'[Instructions]:\n{system_prompt}\n\n[Response]:']
34
+ # The first user input is _not_ stripped
35
+ do_strip = False
36
+ for user_input, response in chat_history:
37
+ user_input = user_input.strip() if do_strip else user_input
38
+ do_strip = True
39
+ texts.append(f'{user_input} [Response] {response.strip()} </s><s>[Instructions] ')
40
+ message = message.strip() if do_strip else message
41
+ texts.append(f'{message} [Response]')
42
+ return ''.join(texts)
43
+
44
+
45
+ def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
46
+ prompt = get_prompt(message, chat_history, system_prompt)
47
+ input_ids = tokenizer([prompt], return_tensors='np', add_special_tokens=False)['input_ids']
48
+ return input_ids.shape[-1]
49
+
50
+
51
+ def run(message: str,
52
+ chat_history: list[tuple[str, str]],
53
+ system_prompt: str,
54
+ max_new_tokens: int = 1024,
55
+ temperature: float = 0.1,
56
+ top_p: float = 0.9,
57
+ top_k: int = 50) -> Iterator[str]:
58
+ prompt = get_prompt(message, chat_history, system_prompt)
59
+ inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to(model.device)
60
+
61
+ streamer = TextIteratorStreamer(tokenizer,
62
+ timeout=10.,
63
+ skip_prompt=True,
64
+ skip_special_tokens=True)
65
+ generate_kwargs = dict(
66
+ inputs,
67
+ streamer=streamer,
68
+ max_new_tokens=max_new_tokens,
69
+ do_sample=True,
70
+ top_p=top_p,
71
+ top_k=top_k,
72
+ temperature=temperature,
73
+ num_beams=1,
74
+ )
75
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
76
+ t.start()
77
+
78
+ outputs = []
79
+ for text in streamer:
80
+ outputs.append(text)
81
+ yield ''.join(outputs)