nakcnx commited on
Commit
d9ff629
β€’
1 Parent(s): 3a683e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -51
app.py CHANGED
@@ -1,64 +1,141 @@
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
- client = InferenceClient("Qwen/Qwen2-7B-Instruct")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
 
 
10
 
11
- def respond(
12
- message,
13
- history: list[tuple[str, str]],
14
- system_message,
15
- max_tokens,
16
- temperature,
17
- top_p,
18
- ):
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- for val in history:
22
- if val[0]:
23
- messages.append({"role": "user", "content": val[0]})
24
- if val[1]:
25
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
26
 
27
- messages.append({"role": "user", "content": message})
28
 
29
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- for message in client.chat_completion(
32
- messages,
33
- max_tokens=max_tokens,
34
- stream=True,
35
- temperature=temperature,
36
- top_p=top_p,
37
- ):
38
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- response += token
41
- yield response
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
 
63
  if __name__ == "__main__":
64
- 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", "Qwen/Qwen2-7B-Instruct-GGUF"),
12
+ filename=os.environ.get("MODEL_FILE", "qwen2-7b-instruct-q5_k_m.gguf"),
13
+ )
14
+ repetitionpenalty = 1.15
15
+ contextlength=4096
16
+ logfile = 'Qwen2-7B-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
+ timestamp = datetime.datetime.now()
79
+ 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"""
80
+ writehistory(logger)
81
+ convHistory = convHistory + prompt + "\n" + generation + "\n"
82
+ print(convHistory)
83
+ return generation, delta, prompt_tokens, answer_tokens, total_tokens
84
+ #return generation, delta
85
 
 
86
 
87
+ # MAIN GRADIO INTERFACE
88
+ with gr.Blocks(theme='Medguy/base2') as demo: #theme=gr.themes.Glass() #theme='remilia/Ghostly'
89
+ #TITLE SECTION
90
+ with gr.Row(variant='compact'):
91
+ with gr.Column(scale=10):
92
+ gr.HTML("<center>"
93
+ + "<h2>🐢 Paotung QWEN2-7b</h2></center>")
94
+ with gr.Row():
95
+ with gr.Column(min_width=80):
96
+ gentime = gr.Textbox(value="", placeholder="Generation Time:", min_width=50, show_label=False)
97
+ with gr.Column(min_width=80):
98
+ prompttokens = gr.Textbox(value="", placeholder="Prompt Tkn:", min_width=50, show_label=False)
99
+ with gr.Column(min_width=80):
100
+ outputokens = gr.Textbox(value="", placeholder="Output Tkn:", min_width=50, show_label=False)
101
+ with gr.Column(min_width=80):
102
+ totaltokens = gr.Textbox(value="", placeholder="Total Tokens:", min_width=50, show_label=False)
103
+ # INTERACTIVE INFOGRAPHIC SECTION
104
+
105
 
106
+ # PLAYGROUND INTERFACE SECTION
107
+ with gr.Row():
108
+ with gr.Column(scale=1):
109
+ gr.Markdown(
110
+ f"""
111
+ ### Tunning Parameters""")
112
+ temp = gr.Slider(label="Temperature",minimum=0.0, maximum=1.0, step=0.01, value=0.42)
113
+ top_p = gr.Slider(label="Top_P",minimum=0.0, maximum=1.0, step=0.01, value=0.8)
114
+ repPen = gr.Slider(label="Repetition Penalty",minimum=0.0, maximum=4.0, step=0.01, value=1.2)
115
+ max_len = gr.Slider(label="Maximum output lenght", minimum=10,maximum=(contextlength-500),step=2, value=900)
116
+ gr.Markdown(
117
+ """
118
+ Fill the System Prompt and User Prompt
119
+ And then click the Button below
120
+ """)
121
+ btn = gr.Button(value="πŸ’ŽπŸ¦œ Generate", variant='primary')
122
+ gr.Markdown(
123
+ f"""
124
+ - **Prompt Template**: Llama-3-8B
125
+ - **Repetition Penalty**: {repetitionpenalty}
126
+ - **Context Lenght**: {contextlength} tokens
127
+ - **LLM Engine**: llama-cpp
128
+ - **Model**: πŸ’ŽπŸ¦œ Llama-3-8B
129
+ - **Log File**: {logfile}
130
+ """)
131
 
 
 
132
 
133
+ with gr.Column(scale=4):
134
+ txt = gr.Textbox(label="System Prompt", value = "", placeholder = "This models does not have any System prompt...",lines=1, interactive = True)
135
+ txt_2 = gr.Textbox(label="User Prompt", lines=5, show_copy_button=True)
136
+ txt_3 = gr.Textbox(value="", label="Output", lines = 10, show_copy_button=True)
137
+ btn.click(combine, inputs=[txt, txt_2,temp,max_len,top_p,repPen], outputs=[txt_3,gentime,prompttokens,outputokens,totaltokens])
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
 
140
  if __name__ == "__main__":
141
+ demo.launch(inbrowser=True)