davidrgleason commited on
Commit
1bfea62
β€’
1 Parent(s): 5e8e0db

Update app.py

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