nakcnx commited on
Commit
fe8bfde
β€’
1 Parent(s): d44f8f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -49
app.py CHANGED
@@ -1,63 +1,144 @@
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 gradio as gr
2
+ from llama_cpp import Llama
3
+ import datetime
4
+ import os
5
+ import datetime
6
+ from huggingface_hub import hf_hub_download
7
+
8
+ #MODEL SETTINGS also for DISPLAY
9
+ convHistory = ''
10
+ modelfile = hf_hub_download(
11
+ repo_id=os.environ.get("REPO_ID", "RichardErkhov/scb10x_-_llama-3-typhoon-v1.5-8b-instruct-gguf"),
12
+ filename=os.environ.get("MODEL_FILE", "llama-3-typhoon-v1.5-8b-instruct.Q4_K_M.gguf"),
13
+ )
14
+ repetitionpenalty = 1.15
15
+ contextlength=8192
16
+ logfile = 'typhoon-v1.5-8b-instruct_logs.txt'
17
+ print("loading model...")
18
+ stt = datetime.datetime.now()
19
+ # Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system.
20
+ llm = Llama(
21
+ model_path=modelfile, # Download the model file first
22
+ n_ctx=contextlength, # The max sequence length to use - note that longer sequence lengths require much more resources
23
+ n_threads=2, # The number of CPU threads to use, tailor to your system and the resulting performance
24
+ )
25
+ dt = datetime.datetime.now() - stt
26
+ print(f"Model loaded in {dt}")
27
+
28
+ def writehistory(text):
29
+ with open(logfile, 'a') as f:
30
+ f.write(text)
31
+ f.write('\n')
32
+ f.close()
33
 
34
  """
35
+ gr.themes.Base()
36
+ gr.themes.Default()
37
+ gr.themes.Glass()
38
+ gr.themes.Monochrome()
39
+ gr.themes.Soft()
40
  """
41
+ def combine(a, b, c, d,e,f):
42
+ global convHistory
43
+ import datetime
44
+ SYSTEM_PROMPT = f"""{a}
45
+ """
46
+ temperature = c
47
+ max_new_tokens = d
48
+ repeat_penalty = f
49
+ top_p = e
50
+ prompt = f"<|user|>\n{b}<|endoftext|>\n<|assistant|>"
51
+
52
+ # prompt = [
53
+ # {"role": "system", "content": SYSTEM_PROMPT} ,
54
+ # {"role": "user", "content": b},
55
+ # ]
56
+ prompt = f"""{prompt}"""
57
+ start = datetime.datetime.now()
58
+ generation = ""
59
+ delta = ""
60
+ prompt_tokens = f"Prompt Tokens: {len(llm.tokenize(bytes(prompt,encoding='utf-8')))}"
61
+ generated_text = ""
62
+ answer_tokens = ''
63
+ total_tokens = ''
64
+ for character in llm(prompt,
65
+ max_tokens=max_new_tokens,
66
+ #stop=["<|eot_id|>"],
67
+ temperature = temperature,
68
+ repeat_penalty = repeat_penalty,
69
+ top_p = top_p, # Example stop token - not necessarily correct for this specific model! Please check before using.
70
+ echo=False,
71
+ stream=True):
72
+ generation += character["choices"][0]["text"]
73
 
74
+ answer_tokens = f"Out Tkns: {len(llm.tokenize(bytes(generation,encoding='utf-8')))}"
75
+ total_tokens = f"Total Tkns: {len(llm.tokenize(bytes(prompt,encoding='utf-8'))) + len(llm.tokenize(bytes(generation,encoding='utf-8')))}"
76
+ delta = datetime.datetime.now() - start
77
+ yield generation, delta, prompt_tokens, answer_tokens, total_tokens
 
 
 
 
 
78
 
79
+ print(f"Response: {generation}")
80
+
81
+ timestamp = datetime.datetime.now()
82
+ logger = f"""time: {timestamp}\n Temp: {temperature} - MaxNewTokens: {max_new_tokens} - RepPenalty: 1.5 \nPROMPT: \n{prompt}\nStableZephyr3B: {generation}\nGenerated in {delta}\nPromptTokens: {prompt_tokens} Output Tokens: {answer_tokens} Total Tokens: {total_tokens}\n\n---\n\n"""
83
+ writehistory(logger)
84
+ convHistory = convHistory + prompt + "\n" + generation + "\n"
85
+ print(convHistory)
86
+ return generation, delta, prompt_tokens, answer_tokens, total_tokens
87
+ #return generation, delta
88
 
 
89
 
90
+ # MAIN GRADIO INTERFACE
91
+ with gr.Blocks(theme='Medguy/base2') as demo: #theme=gr.themes.Glass() #theme='remilia/Ghostly'
92
+ #TITLE SECTION
93
+ with gr.Row(variant='compact'):
94
+ with gr.Column(scale=10):
95
+ gr.HTML("<center>"
96
+ + "<h2>🐢 Paotung Typhoon</h2></center>")
97
+ with gr.Row():
98
+ with gr.Column(min_width=80):
99
+ gentime = gr.Textbox(value="", placeholder="Generation Time:", min_width=50, show_label=False)
100
+ with gr.Column(min_width=80):
101
+ prompttokens = gr.Textbox(value="", placeholder="Prompt Tkn:", min_width=50, show_label=False)
102
+ with gr.Column(min_width=80):
103
+ outputokens = gr.Textbox(value="", placeholder="Output Tkn:", min_width=50, show_label=False)
104
+ with gr.Column(min_width=80):
105
+ totaltokens = gr.Textbox(value="", placeholder="Total Tokens:", min_width=50, show_label=False)
106
+ # INTERACTIVE INFOGRAPHIC SECTION
107
+
108
 
109
+ # PLAYGROUND INTERFACE SECTION
110
+ with gr.Row():
111
+ with gr.Column(scale=1):
112
+ gr.Markdown(
113
+ f"""
114
+ ### Tunning Parameters""")
115
+ temp = gr.Slider(label="Temperature",minimum=0.0, maximum=1.0, step=0.01, value=0.42)
116
+ top_p = gr.Slider(label="Top_P",minimum=0.0, maximum=1.0, step=0.01, value=0.8)
117
+ repPen = gr.Slider(label="Repetition Penalty",minimum=0.0, maximum=4.0, step=0.01, value=1.2)
118
+ max_len = gr.Slider(label="Maximum output lenght", minimum=10,maximum=(contextlength-500),step=2, value=900)
119
+ gr.Markdown(
120
+ """
121
+ Fill the System Prompt and User Prompt
122
+ And then click the Button below
123
+ """)
124
+ btn = gr.Button(value="πŸ’ŽπŸ¦œ Generate", variant='primary')
125
+ gr.Markdown(
126
+ f"""
127
+ - **Prompt Template**: Llama-3-8B
128
+ - **Repetition Penalty**: {repetitionpenalty}
129
+ - **Context Lenght**: {contextlength} tokens
130
+ - **LLM Engine**: llama-cpp
131
+ - **Model**: πŸ’ŽπŸ¦œ Llama-3-8B + typhoon-v1.5-8b-instruct
132
+ - **Log File**: {logfile}
133
+ """)
134
 
 
 
135
 
136
+ with gr.Column(scale=4):
137
+ txt = gr.Textbox(label="System Prompt", value = "", placeholder = "This models does not have any System prompt...",lines=1, interactive = True)
138
+ txt_2 = gr.Textbox(label="User Prompt", lines=5, show_copy_button=True)
139
+ txt_3 = gr.Textbox(value="", label="Output", lines = 10, show_copy_button=True)
140
+ btn.click(combine, inputs=[txt, txt_2,temp,max_len,top_p,repPen], outputs=[txt_3,gentime,prompttokens,outputokens,totaltokens])
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
 
143
  if __name__ == "__main__":
144
+ demo.launch(inbrowser=True)