tatihden commited on
Commit
7890994
·
verified ·
1 Parent(s): 188dc99

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -76
app.py CHANGED
@@ -1,84 +1,109 @@
1
  import gradio as gr
2
- import transformers
3
- from torch import bfloat16
4
- # from dotenv import load_dotenv # if you wanted to adapt this for a repo that uses auth
5
- from threading import Thread
6
-
7
-
8
- #HF_AUTH = os.getenv('HF_AUTH')
9
- model_id ="tatihden/gemma_mental_health_7b_it_en"
10
-
11
- bnb_config = transformers.BitsAndBytesConfig(
12
- load_in_4bit=True,
13
- bnb_4bit_quant_type='nf4',
14
- bnb_4bit_use_double_quant=True,
15
- bnb_4bit_compute_dtype=bfloat16
16
- )
17
- model_config = transformers.AutoConfig.from_pretrained(
18
- model_id,
19
- #use_auth_token=HF_AUTH
20
- )
21
-
22
- model = transformers.AutoModelForCausalLM.from_pretrained(
23
- model_id,
24
- trust_remote_code=True,
25
- config=model_config,
26
- quantization_config=bnb_config,
27
- device_map='auto',
28
- #use_auth_token=HF_AUTH
29
- )
30
-
31
- tokenizer = transformers.AutoTokenizer.from_pretrained(
32
- model_id,
33
- #use_auth_token=HF_AUTH
34
- )
35
-
36
-
37
- DESCRIPTION = """
38
- # CalmChat
39
- This is a streaming Chat Interface implementation of [gemma_mental_health_7b_it_en](https://huggingface.co/tatihden/gemma_mental_health_7b_it_en).
40
- Sometimes the model doesn't appropriately hit its stop token. Feel free to hit "stop" and "retry" if this happens to you.
41
- """
42
-
43
- system_prompt = "You are helpful mental health AI."
44
-
45
- def prompt_build(system_prompt, user_inp, hist):
46
- prompt = f"""### System:\n{system_prompt}\n\n"""
47
-
48
- for pair in hist:
49
- prompt += f"""### User:\n{pair[0]}\n\n### Assistant:\n{pair[1]}\n\n"""
50
-
51
- prompt += f"""### User:\n{user_inp}\n\n### Assistant:"""
52
  return prompt
53
 
54
- def chat(user_input, history):
55
 
56
- prompt = prompt_build(system_prompt, user_input, history)
57
- model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
58
-
59
- streamer = transformers.TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
 
 
 
 
60
 
61
  generate_kwargs = dict(
62
- model_inputs,
63
- streamer=streamer,
64
- max_new_tokens=2048,
 
65
  do_sample=True,
66
- top_p=0.95,
67
- temperature=0.8,
68
- top_k=50
69
  )
70
- t = Thread(target=model.generate, kwargs=generate_kwargs)
71
- t.start()
72
-
73
- model_output = ""
74
- for new_text in streamer:
75
- model_output += new_text
76
- yield model_output
77
- return model_output
78
-
79
-
80
- with gr.Blocks() as demo:
81
- gr.Markdown(DESCRIPTION)
82
- chatbot = gr.ChatInterface(fn=chat)
83
-
84
- demo.queue().launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ import random
4
+
5
+ models = [
6
+ "https://huggingface.co/tatihden/gemma_mental_health_7b_it_en",
7
+ "https://huggingface.co/tatihden/gemma_mental_health_2b_en",
8
+ "https://huggingface.co/tatihden/gemma_mental_health_2b_it_en"
9
+ ]
10
+
11
+ clients = []
12
+ for model in models:
13
+ clients.append(InferenceClient(model))
14
+
15
+
16
+ def format_prompt(message, history):
17
+ prompt = ""
18
+ if history:
19
+ for user_prompt, bot_response in history:
20
+ prompt += f"<start_of_turn>user{user_prompt}<end_of_turn>"
21
+ prompt += f"<start_of_turn>model{bot_response}"
22
+ prompt += f"<start_of_turn>user{message}<end_of_turn><start_of_turn>model"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  return prompt
24
 
 
25
 
26
+ def chat_inf(system_prompt, prompt, history, client_choice, seed, temp, tokens, top_p, rep_p):
27
+ client = clients[int(client_choice) - 1]
28
+ if not history:
29
+ history = []
30
+ hist_len = 0
31
+ if history:
32
+ hist_len = len(history)
33
+ print(hist_len)
34
 
35
  generate_kwargs = dict(
36
+ temperature=temp,
37
+ max_new_tokens=tokens,
38
+ top_p=top_p,
39
+ repetition_penalty=rep_p,
40
  do_sample=True,
41
+ seed=seed,
 
 
42
  )
43
+ formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
44
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True,
45
+ return_full_text=False)
46
+ output = ""
47
+
48
+ for response in stream:
49
+ output += response.token.text
50
+ yield [(prompt, output)]
51
+ history.append((prompt, output))
52
+ yield history
53
+
54
+
55
+ def clear_fn():
56
+ return None
57
+
58
+
59
+ rand_val = random.randint(1, 1111111111111111)
60
+
61
+
62
+ def check_rand(inp, val):
63
+ if inp is True:
64
+ return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=random.randint(1, 1111111111111111))
65
+ else:
66
+ return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=int(val))
67
+
68
+
69
+ with gr.Blocks(css=background-color: rgb(74 222 128),theme=gr.themes.Soft()) as app:
70
+ gr.HTML(
71
+ """<center><h1 style='font-size:xx-large;'>Google Gemma Models</h1></center>""")
72
+ with gr.Group():
73
+ with gr.Row():
74
+ client_choice = gr.Dropdown(label="Models", type='index', choices=[c for c in models], value=models[0],
75
+ interactive=True)
76
+ chat_b = gr.Chatbot(height=500)
77
+ with gr.Group():
78
+ with gr.Row():
79
+ with gr.Column(scale=1):
80
+ with gr.Group():
81
+ rand = gr.Checkbox(label="Random Seed", value=True)
82
+ seed = gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, step=1, value=rand_val)
83
+ tokens = gr.Slider(label="Max new tokens", value=6400, minimum=0, maximum=8000, step=64,
84
+ interactive=True, visible=True, info="The maximum number of tokens")
85
+ with gr.Column(scale=1):
86
+ with gr.Group():
87
+ temp = gr.Slider(label="Temperature", step=0.01, minimum=0.01, maximum=1.0, value=0.9)
88
+ top_p = gr.Slider(label="Top-P", step=0.01, minimum=0.01, maximum=1.0, value=0.9)
89
+ rep_p = gr.Slider(label="Repetition Penalty", step=0.1, minimum=0.1, maximum=2.0, value=1.0)
90
+
91
+ with gr.Group():
92
+ with gr.Row():
93
+ with gr.Column(scale=3):
94
+ sys_inp = gr.Textbox(label="System Prompt (optional)")
95
+ inp = gr.Textbox(label="Prompt")
96
+ with gr.Row():
97
+ btn = gr.Button("Chat")
98
+ stop_btn = gr.Button("Stop")
99
+ clear_btn = gr.Button("Clear")
100
+
101
+ chat_sub = inp.submit(check_rand, [rand, seed], seed).then(chat_inf,
102
+ [sys_inp, inp, chat_b, client_choice, seed, temp, tokens,
103
+ top_p, rep_p], chat_b)
104
+ go = btn.click(check_rand, [rand, seed], seed).then(chat_inf,
105
+ [sys_inp, inp, chat_b, client_choice, seed, temp, tokens, top_p,
106
+ rep_p], chat_b)
107
+ stop_btn.click(None, None, None, cancels=[go, chat_sub])
108
+ clear_btn.click(clear_fn, None, [chat_b])
109
+ app.queue(default_concurrency_limit=10).launch()