dreamerdeo commited on
Commit
89dd80e
1 Parent(s): 49c7d6f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -51
app.py CHANGED
@@ -1,63 +1,103 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
27
 
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
42
  """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
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 = 'sail/Sailor-14B-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)
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 = 'assistant'
29
+ assistant_role = "user"
 
 
 
 
 
 
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 Sailor created by Sea AI Lab. \
37
+ As an AI assistant, you need to answer a series of questions next, which may include languages such as English, Chinese, Thai, Vietnamese, Indonesian, Malay, and so on. \
38
+ Your answer should be friendly, unbiased, faithful, informative and detailed.'
39
+ system_prompt = f"<|im_start|>{system_role}\n{system_prompt}<|im_end|>"
40
 
41
+ # Function to generate model predictions.
42
 
43
+ @spaces.GPU()
44
+ def predict(message, history):
45
+ # history = []
46
+ history_transformer_format = history + [[message, ""]]
47
+ stop = StopOnTokens()
 
 
 
48
 
49
+ # Formatting the input for the model.
50
+ 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]])
51
+ for item in history_transformer_format])
52
+ model_inputs = tokenizer([messages], return_tensors="pt").to(device)
53
+ streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
54
+ generate_kwargs = dict(
55
+ model_inputs,
56
+ streamer=streamer,
57
+ max_new_tokens=256,
58
+ do_sample=True,
59
+ top_p= 0.75,
60
+ top_k= 60,
61
+ temperature=0.2,
62
+ num_beams=1,
63
+ stopping_criteria=StoppingCriteriaList([stop]),
64
+ repetition_penalty=1.1,
65
+ )
66
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
67
+ t.start() # Starting the generation in a separate thread.
68
+ partial_message = ""
69
+ for new_token in streamer:
70
+ partial_message += new_token
71
+ if sft_end_token in partial_message: # Breaking the loop if the stop token is generated.
72
+ break
73
+ yield partial_message
74
 
75
+
76
+ css = """
77
+ full-height {
78
+ height: 100%;
79
+ }
80
  """
81
+
82
+ prompt_examples = [
83
+ 'How to cook a fish?',
84
+ 'Cara memanggang ikan',
85
+ 'วิธีย่างปลา',
86
+ 'Cách nướng cá'
87
+ ]
88
+
89
+ placeholder = """
90
+ <div style="opacity: 0.5;">
91
+ <img src="https://raw.githubusercontent.com/sail-sg/sailor-llm/main/misc/banner.jpg" style="width:30%;">
92
+ <br>Sailor models are designed to understand and generate text across diverse linguistic landscapes of these SEA regions:
93
+ <br>🇮🇩Indonesian, 🇹🇭Thai, 🇻🇳Vietnamese, 🇲🇾Malay, and 🇱🇦Lao.
94
+ </div>
95
  """
96
+
97
+ chatbot = gr.Chatbot(label='Sailor', placeholder=placeholder)
98
+ with gr.Blocks(theme=gr.themes.Soft(), fill_height=True) as demo:
99
+ # gr.Markdown("""<center><font size=8>Sailor-Chat Bot⚓</center>""")
100
+ 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>""")
101
+ gr.ChatInterface(predict, chatbot=chatbot, fill_height=True, examples=prompt_examples, css=css)
102
+
103
+ demo.launch() # Launching the web interface.