cmcmaster commited on
Commit
07348d6
·
verified ·
1 Parent(s): 6d04c66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -53
app.py CHANGED
@@ -1,64 +1,97 @@
 
 
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("google/medgemma-27b-text-it")
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
- """
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 helpful medical assistant.", 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 gc
2
+ import threading
3
  import gradio as gr
4
+ import torch
5
+ from transformers import pipeline, TextIteratorStreamer, AutoTokenizer
6
+ import spaces
7
 
8
+ # Single-model configuration
9
+ MODEL_REPO = "google/medgemma-27b-text-it"
 
 
10
 
11
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO)
12
+ # Choose best dtype available
13
+ dtype = (torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported()
14
+ else torch.float16 if torch.cuda.is_available()
15
+ else torch.float32)
16
+ pipe = pipeline(
17
+ task="text-generation",
18
+ model=MODEL_REPO,
19
+ tokenizer=tokenizer,
20
+ trust_remote_code=True,
21
+ torch_dtype=dtype,
22
+ device_map="auto" if torch.cuda.is_available() else None
23
+ )
24
+ pipe.to('cuda')
25
 
26
+ # Cancellation event for streaming
27
+ cancel_event = threading.Event()
28
+ def cancel_generation():
29
+ cancel_event.set()
30
+ return "Generation cancelled."
 
 
 
 
 
 
 
 
 
 
31
 
32
+ # Streaming chat response without web search
33
+ @spaces.GPU
34
+ def chat_response(user_msg, chat_history, max_tokens, temperature, top_k, top_p, repetition_penalty):
35
+ cancel_event.clear()
36
+ history = list(chat_history or [])
37
+ history.append({"role": "user", "content": user_msg})
38
+ # Build prompt
39
+ prompt = ""
40
+ for msg in history:
41
+ prefix = "User: " if msg["role"] == "user" else "Assistant: "
42
+ prompt += prefix + msg["content"].strip() + "\n"
43
+ if not prompt.rstrip().endswith("Assistant:"):
44
+ prompt += "Assistant:"
45
+
46
+ # Set up streamer
47
+ streamer = TextIteratorStreamer(
48
+ tokenizer, skip_prompt=True, skip_special_tokens=True
49
+ )
50
+ t = threading.Thread(
51
+ target=pipe,
52
+ args=(prompt,),
53
+ kwargs={
54
+ 'max_new_tokens': max_tokens,
55
+ 'temperature': temperature,
56
+ 'top_k': top_k,
57
+ 'top_p': top_p,
58
+ 'repetition_penalty': repetition_penalty,
59
+ 'streamer': streamer,
60
+ 'return_full_text': False,
61
+ }
62
+ )
63
+ t.start()
64
 
65
+ # Stream tokens into chat history
66
  response = ""
67
+ history.append({"role": "assistant", "content": ""})
68
+ for token in streamer:
69
+ if cancel_event.is_set():
70
+ break
 
 
 
 
 
 
71
  response += token
72
+ history[-1]["content"] = response
73
+ yield history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ t.join()
76
+ gc.collect()
77
+ yield history
78
 
79
+ # Build Gradio interface
80
+ with gr.Blocks(title="MedGemma Chat") as demo:
81
+ gr.Markdown("## Chat with Google/MedGemma-27B")
82
+ chat = gr.Chatbot()
83
+ txt = gr.Textbox(placeholder="Type your message and press Enter...")
84
+ with gr.Row():
85
+ max_tok = gr.Slider(64, 4096, value=1024, step=64, label="Max Tokens")
86
+ temp = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature")
87
+ k = gr.Slider(1, 100, value=50, step=1, label="Top-K")
88
+ p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-P")
89
+ rp = gr.Slider(1.0, 2.0, value=1.2, step=0.1, label="Repetition Penalty")
90
+ cancel_btn = gr.Button("Cancel Generation")
91
+ cancel_btn.click(cancel_generation)
92
+ txt.submit(
93
+ fn=chat_response,
94
+ inputs=[txt, chat, max_tok, temp, k, p, rp],
95
+ outputs=chat
96
+ )
97
  demo.launch()