nakcnx commited on
Commit
2bb2938
Β·
verified Β·
1 Parent(s): 7b5a0ee

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -0
app.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", "QuantFactory/Meta-Llama-3-8B-Instruct-GGUF"),
12
+ filename=os.environ.get("MODEL_FILE", "Meta-Llama-3-8B-Instruct.Q4_K_M.gguf"),
13
+ )
14
+ repetitionpenalty = 1.15
15
+ contextlength=4096
16
+ logfile = 'Meta-Llama-3-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=["</s>"],
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 Llama-3-8B</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)