dreamerdeo commited on
Commit
28d60d1
1 Parent(s): bd0b987

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.system('pip install torch')
4
+ os.system('pip install transformers==4.37.1')
5
+
6
+ import gradio as gr
7
+ import torch
8
+ from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
9
+ from threading import Thread
10
+
11
+ model_path = 'sail/Sailor-7B-Chat'
12
+
13
+ # Loading the tokenizer and model from Hugging Face's model hub.
14
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
15
+ model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
16
+
17
+ # using CUDA for an optimal experience
18
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
19
+ model = model.to(device)
20
+
21
+ # Defining a custom stopping criteria class for the model's text generation.
22
+ class StopOnTokens(StoppingCriteria):
23
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
24
+ stop_ids = [151645] # IDs of tokens where the generation should stop.
25
+ for stop_id in stop_ids:
26
+ if input_ids[0][-1] == stop_id: # Checking if the last generated token is a stop token.
27
+ return True
28
+ return False
29
+
30
+
31
+ system_role= 'system'
32
+ user_role = 'question'
33
+ assistant_role = "answer"
34
+
35
+ sft_start_token = "<|im_start|>"
36
+ sft_end_token = "<|im_end|>"
37
+ ct_end_token = "<|endoftext|>"
38
+
39
+ system_prompt= \
40
+ 'You are an AI assistant named Sailor created by Sea AI Lab. \
41
+ Your answer should be friendly, unbiased, faithful, informative and detailed.'
42
+ system_prompt = f"<|im_start|>{system_role}\n{system_prompt}<|im_end|>"
43
+
44
+ # Function to generate model predictions.
45
+ def predict(message, history):
46
+ # history = []
47
+ history_transformer_format = history + [[message, ""]]
48
+ stop = StopOnTokens()
49
+
50
+ # Formatting the input for the model.
51
+ messages = system_prompt + sft_end_token.join([sft_end_token.join([f"\n{sft_start_token}{user_role}\n" + item[0], f"\n{sft_start_token}{assistant_role}\n" + item[1]])
52
+ for item in history_transformer_format])
53
+ model_inputs = tokenizer([messages], return_tensors="pt").to(device)
54
+ streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
55
+ generate_kwargs = dict(
56
+ model_inputs,
57
+ streamer=streamer,
58
+ max_new_tokens=256,
59
+ do_sample=True,
60
+ top_p= 0.75,
61
+ top_k= 60,
62
+ temperature=0.2,
63
+ num_beams=1,
64
+ stopping_criteria=StoppingCriteriaList([stop]),
65
+ repetition_penalty=1.1,
66
+ )
67
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
68
+ t.start() # Starting the generation in a separate thread.
69
+ partial_message = ""
70
+ for new_token in streamer:
71
+ partial_message += new_token
72
+ if sft_end_token in partial_message: # Breaking the loop if the stop token is generated.
73
+ break
74
+ yield partial_message
75
+
76
+
77
+ css = """
78
+ full-height {
79
+ height: 100%;
80
+ }
81
+ """
82
+
83
+ prompt_examples = [
84
+ 'How to cook a fish?',
85
+ 'Cara memanggang ikan',
86
+ 'วิธีย่างปลา',
87
+ 'Cách nướng cá'
88
+ ]
89
+
90
+ with gr.Blocks(theme=gr.themes.Soft(), fill_height=True) as demo:
91
+ gr.Markdown("""<center><font size=8>Sailor-Chat Bot⚓</center>""")
92
+ gr.ChatInterface(predict, fill_height=True, examples=prompt_examples, css=css)
93
+ gr.Markdown("""<p align="center"><img src="https://github.com/sail-sg/sailor-llm/raw/main/misc/banner.jpg" style="height: 180px"/><p>""")
94
+
95
+
96
+ demo.launch(share=True) # Launching the web interface.