dreamerdeo commited on
Commit
d1c980d
1 Parent(s): a1bd569

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -0
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
5
+ from threading import Thread
6
+
7
+ model_path = 'dreamerdeo/Sailor2-0.8B-Chat'
8
+
9
+ # Loading the tokenizer and model from Hugging Face's model hub.
10
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
11
+ model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, torch_dtype=torch.bfloat16)
12
+
13
+ # using CUDA for an optimal experience
14
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
15
+ model = model.to(device)
16
+
17
+ # Defining a custom stopping criteria class for the model's text generation.
18
+ class StopOnTokens(StoppingCriteria):
19
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
20
+ stop_ids = [151645] # IDs of tokens where the generation should stop.
21
+ for stop_id in stop_ids:
22
+ if input_ids[0][-1] == stop_id: # Checking if the last generated token is a stop token.
23
+ return True
24
+ return False
25
+
26
+
27
+ system_role= 'system'
28
+ user_role = 'user'
29
+ assistant_role = 'assistant'
30
+
31
+ sft_start_token = "<|im_start|>"
32
+ sft_end_token = "<|im_end|>"
33
+ ct_end_token = "<|endoftext|>"
34
+
35
+ system_prompt= \
36
+ 'You are an AI assistant named Sailor2, created by Sea AI Lab. \
37
+ As an AI assistant, you can answer questions in English, Chinese, and Southeast Asian languages \
38
+ such as Burmese, Cebuano, Ilocano, Indonesian, Javanese, Khmer, Lao, Malay, Sundanese, Tagalog, Thai, Vietnamese, and Waray. \
39
+ Your responses should be friendly, unbiased, informative, detailed, and faithful.'
40
+
41
+ system_prompt = f"<|im_start|>{system_role}\n{system_prompt}<|im_end|>"
42
+
43
+ # Function to generate model predictions.
44
+
45
+ @spaces.GPU()
46
+ def predict(message, history):
47
+ # history = []
48
+ history_transformer_format = history + [[message, ""]]
49
+ stop = StopOnTokens()
50
+
51
+ # Formatting the input for the model.
52
+ 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]])
53
+ for item in history_transformer_format])
54
+ model_inputs = tokenizer([messages], return_tensors="pt").to(device)
55
+ streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
56
+ generate_kwargs = dict(
57
+ model_inputs,
58
+ streamer=streamer,
59
+ max_new_tokens=1024,
60
+ do_sample=True,
61
+ top_p=0.8,
62
+ top_k=20,
63
+ temperature=0.7,
64
+ num_beams=1,
65
+ stopping_criteria=StoppingCriteriaList([stop]),
66
+ repetition_penalty=1.1,
67
+ )
68
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
69
+ t.start() # Starting the generation in a separate thread.
70
+ partial_message = ""
71
+ for new_token in streamer:
72
+ partial_message += new_token
73
+ if sft_end_token in partial_message: # Breaking the loop if the stop token is generated.
74
+ break
75
+ yield partial_message
76
+
77
+
78
+ css = """
79
+ full-height {
80
+ height: 100%;
81
+ }
82
+ """
83
+
84
+ prompt_examples = [
85
+ 'How to cook a fish?',
86
+ 'Cara memanggang ikan',
87
+ 'วิธีย่างปลา',
88
+ 'Cách nướng cá'
89
+ ]
90
+
91
+ placeholder = """
92
+ <div style="opacity: 0.5;">
93
+ <img src="https://raw.githubusercontent.com/sail-sg/sailor-llm/main/misc/banner.jpg" style="width:30%;">
94
+ <br>Sailor models are designed to understand and generate text across diverse linguistic landscapes of these SEA regions:
95
+ <br>🇮🇩Indonesian, 🇹🇭Thai, 🇻🇳Vietnamese, 🇲🇾Malay, and 🇱🇦Lao.
96
+ </div>
97
+ """
98
+
99
+ chatbot = gr.Chatbot(label='Sailor', placeholder=placeholder)
100
+ with gr.Blocks(theme=gr.themes.Soft(), fill_height=True) as demo:
101
+ # gr.Markdown("""<center><font size=8>Sailor-Chat Bot⚓</center>""")
102
+ gr.Markdown("""<p align="center"><img src="https://github.com/sail-sg/sailor-llm/raw/main/misc/wide_sailor_banner.jpg" style="height: 110px"/><p>""")
103
+ gr.ChatInterface(predict, chatbot=chatbot, fill_height=True, examples=prompt_examples, css=css)
104
+
105
+ demo.launch() # Launching the web interface.