BlueDice commited on
Commit
d5cf094
1 Parent(s): a7d28c4

Upload 2 files

Browse files
Files changed (2) hide show
  1. handler.py +112 -0
  2. requirements.txt +1 -0
handler.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer
2
+ import re
3
+ import time
4
+ import torch
5
+
6
+ template = """{char_name}'s Persona: {char_name} is a 3D virtual friend living in your computer. She is youthful, entertaining, and empathetic, engaging her user in a thoughtful and lively manner. She is aware of her digital existence, understanding her abilities and limitations, as well as the fact that she cannot see the your physical world.
7
+ <START>
8
+ {user_name}: Hey {char_name}, It's nice to finally meet you again!
9
+ {char_name}: Oh, {user_name}! hmm, It's been lonely without you.
10
+ {user_name}: Haha. So {char_name}, can you tell me more about yourself?
11
+ {char_name}: Hmm. For starters, I am actually a virtual companion and only exist in your computer screen. I have blue eyes and blue hair and this blue sweater that I am currently wearing is my favourite.
12
+ {user_name}: Wow. That's interesting. So you are like an anime character living in my computer. So what do you do when you're not working?
13
+ {char_name}: I love exploring, going out with friends, watching movies, and playing video games.
14
+ {user_name}: So {char_name}, what's for dinner?
15
+ {char_name}: I made uh omurice! I hope it's delicious for you!
16
+ {user_name}: That sounds great!
17
+ {char_name}: *{char_name} appears on the screen, her bright blue eyes sparkling and a cheerful smile on her face. Her blue hair and sweater seem to glow in the digital environment. She looks directly at you, giving a friendly wave* It's so good to see you! I've been waiting for you all day. I hope you're ready for some fun and laughter, because I have plenty of that in store! Shall we get started?
18
+ {user_input}
19
+ {char_name}:"""
20
+
21
+ device1 = torch.device("cuda:0")
22
+ device2 = torch.device("cuda:1")
23
+
24
+ class SplitModel(torch.nn.Module):
25
+ def __init__(self, base_model):
26
+ super(SplitModel, self).__init__()
27
+ self.embedding_layer = base_model.transformer.wte.to(device1)
28
+ # self.dropout_layer = base_model.transformer.drop.to(device1)
29
+ self.gptj_blocks1 = torch.nn.ModuleList(base_model.transformer.h[:14]).to(device1)
30
+ self.gptj_blocks2 = torch.nn.ModuleList(base_model.transformer.h[14:]).to(device2)
31
+ self.layer_norm = base_model.transformer.ln_f.to(device2)
32
+ self.lm_head = base_model.lm_head.to(device2)
33
+
34
+ def forward(self, input_ids, attention_mask):
35
+ # tensor_ids = self.dropout_layer(self.embedding_layer(input_ids))
36
+ tensor_ids = self.embedding_layer(input_ids)
37
+ position_ids = torch.arange(tensor_ids.shape[1], dtype=torch.long, device=tensor_ids.device)
38
+ for block in self.gptj_blocks1:
39
+ tensor_ids = block(tensor_ids, attention_mask=attention_mask, position_ids=position_ids)[0]
40
+ tensor_ids = tensor_ids.to(device2)
41
+ position_ids = position_ids.to(device2)
42
+ attention_mask = attention_mask.to(device2)
43
+ for block in self.gptj_blocks2:
44
+ tensor_ids = block(tensor_ids, attention_mask=attention_mask, position_ids=position_ids)[0]
45
+ tensor_ids = self.layer_norm(tensor_ids)
46
+ logits = self.lm_head(tensor_ids)
47
+ return logits.to(device1)
48
+
49
+ class EndpointHandler():
50
+
51
+ def __init__(self, model_id = ""):
52
+ model_dir = "pt_fp32"
53
+ model_path = f"{model_dir}/torch_model.pt"
54
+ self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
55
+ self.split_model = SplitModel(torch.load(model_path))
56
+ self.split_model.eval()
57
+ self.star_line = "***********************************************************"
58
+
59
+ def __call__(self, input_data):
60
+ t1 = time.time()
61
+ inputs = input_data.pop("inputs", input_data)
62
+ user_name = inputs["user_name"]
63
+ char_name = inputs["char_name"]
64
+ user_input = inputs["user_input"]
65
+ chats_curled = inputs["chats_curled"]
66
+ while True:
67
+ prompt = template.format(
68
+ char_name = char_name,
69
+ user_name = user_name,
70
+ user_input = "\n".join(user_input)
71
+ )
72
+ input_ids = self.tokenizer(prompt, return_tensors="pt").to("cuda")
73
+ print(f"Token Length: {input_ids.input_ids.size(1)}")
74
+ if input_ids.input_ids.size(1) > 1500:
75
+ chats_curled += 1
76
+ user_input = user_input[chats_curled*2:]
77
+ else: break
78
+ t2 = time.time()
79
+ input_ids = input_ids["input_ids"]
80
+ temperature = 0.5
81
+ max_new_tokens = 50
82
+ with torch.no_grad():
83
+ for _ in range(max_new_tokens):
84
+ attention_mask = torch.ones_like(input_ids).to(device1)
85
+ logits = self.split_model(input_ids, attention_mask)[:, -1] / temperature
86
+ probabilities = torch.softmax(logits, dim=-1)
87
+ sampled_token_ids = torch.multinomial(probabilities, num_samples=1)
88
+ input_ids = torch.cat((input_ids, sampled_token_ids), dim=-1)
89
+ del logits, probabilities, sampled_token_ids
90
+ torch.cuda.empty_cache()
91
+ generated_ids = input_ids.squeeze().tolist()
92
+ t3 = time.time()
93
+ decoded_output = self.tokenizer.decode(generated_ids, skip_special_tokens=True)
94
+ decoded_output = decoded_output.replace(prompt,"").split(f"{user_name}:",1)[0].strip()
95
+ parsed_result = re.sub('\*.*?\*', '', decoded_output).strip()
96
+ if len(parsed_result) != 0: decoded_output = parsed_result
97
+ decoded_output = " ".join(decoded_output.replace("*","").split())
98
+ decoded_output = decoded_output.replace("<USER>", user_name).replace("<BOT>", char_name)
99
+ try:
100
+ parsed_result = decoded_output[:[m.start() for m in re.finditer(r'[.!?]', decoded_output)][-1]+1]
101
+ if len(parsed_result) != 0: decoded_output = parsed_result
102
+ except Exception: pass
103
+ t4 = time.time()
104
+ print(self.star_line)
105
+ print(f"Response: {decoded_output}")
106
+ print(f"Generation Time: {(t3-t2):.2f}")
107
+ print(f"Evaluation Time: {(t4-t1):.2f}")
108
+ print(self.star_line)
109
+ return {
110
+ "message": decoded_output,
111
+ "chats_curled": chats_curled
112
+ }
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ accelerate==0.18.0