File size: 7,574 Bytes
d0f4aff
5968a97
2db3bb3
d0f4aff
5968a97
719a76f
cb98777
719a76f
ae0ca85
f69cdc0
 
80f8fa5
 
 
 
e7c4f38
80f8fa5
 
e7c4f38
 
1f6ff2e
80f8fa5
1f6ff2e
 
 
 
 
 
 
 
e7c4f38
 
 
1f6ff2e
 
 
 
 
 
 
80f8fa5
 
 
 
 
 
 
 
 
 
f69cdc0
dbf90db
 
 
 
 
 
719a76f
6df6769
d86f9b0
6df6769
 
 
81a16df
 
 
5d2980c
81a16df
dbf90db
6183592
 
 
e7c4f38
 
 
6183592
e7c4f38
 
 
 
 
 
d86f9b0
e7c4f38
dbf90db
 
81a16df
dbf90db
f69cdc0
d86f9b0
68ccec0
dbf90db
719a76f
e7c4f38
ecbb7be
dbf90db
719a76f
dbf90db
 
719a76f
1f6ff2e
 
5a1d495
5d2980c
80f8fa5
 
205d52f
80f8fa5
205d52f
d86f9b0
 
205d52f
 
d86f9b0
205d52f
 
 
 
 
 
 
 
 
 
 
 
d86f9b0
0e4362c
87aa0f1
559c9f6
d86f9b0
 
 
 
 
d6e3337
dbf90db
1f6ff2e
 
 
64a8918
719a76f
205d52f
 
 
559c9f6
d86f9b0
0e4362c
dbf90db
719a76f
5a1d495
1f6ff2e
 
87aa0f1
1f6ff2e
57ea763
4b15ccd
2db3bb3
b6b7c74
 
 
 
 
 
 
 
 
0ebe852
b6b7c74
 
 
 
2db3bb3
b6b7c74
 
65d5ebe
b6b7c74
 
5968a97
2db3bb3
 
 
 
 
 
 
 
 
 
 
 
 
 
5968a97
86a7aaf
5968a97
 
4b15ccd
86a7aaf
 
5968a97
 
 
86a7aaf
 
 
7ee1641
0115682
86a7aaf
 
 
d0f4aff
86a7aaf
2db3bb3
 
 
4b15ccd
86a7aaf
 
 
 
5e84c69
 
86a7aaf
 
 
 
 
 
 
 
 
 
b6b7c74
0115682
2db3bb3
0115682
2db3bb3
4b15ccd
86a7aaf
0ebe852
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import os
import torch
import time
import gradio as gr
import spaces
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
import threading

from transformers import TextIteratorStreamer
import threading

from transformers import TextIteratorStreamer
import queue

class RichTextStreamer(TextIteratorStreamer):
    def __init__(self, tokenizer, prompt_len=0, **kwargs):
        super().__init__(tokenizer, **kwargs)
        self.token_queue = queue.Queue()
        self.prompt_len = prompt_len
        self.count = 0

    def put(self, value):
        if isinstance(value, torch.Tensor):
            token_ids = value.view(-1).tolist()
        elif isinstance(value, list):
            token_ids = value
        else:
            token_ids = [value]

        for token_id in token_ids:
            self.count += 1
            if self.count <= self.prompt_len:
                continue  # skip prompt tokens
            token_str = self.tokenizer.decode([token_id], **self.decode_kwargs)
            is_special = token_id in self.tokenizer.all_special_ids
            self.token_queue.put({
                "token_id": token_id,
                "token": token_str,
                "is_special": is_special
            })

    def __iter__(self):
        while True:
            try:
                token_info = self.token_queue.get(timeout=self.timeout)
                yield token_info
            except queue.Empty:
                if self.end_of_generation.is_set():
                    break


@spaces.GPU
def chat_with_model(messages):
    global current_model, current_tokenizer
    if current_model is None or current_tokenizer is None:
        yield messages + [{"role": "assistant", "content": "⚠️ No model loaded."}]
        return

    pad_id = current_tokenizer.pad_token_id
    eos_id = current_tokenizer.eos_token_id
    if pad_id is None:
        pad_id = current_tokenizer.unk_token_id or 0

    output_text = ""
    in_think = False
    max_new_tokens = 256
    generated_tokens = 0

    prompt = format_prompt(messages)
    device = torch.device("cuda")
    current_model.to(device).half()

    # 1. Tokenize prompt
    inputs = current_tokenizer(prompt, return_tensors="pt").to(device)
    prompt_len = inputs["input_ids"].shape[-1]

    # 2. Init streamer with prompt_len
    streamer = RichTextStreamer(
        tokenizer=current_tokenizer,
        prompt_len=prompt_len,
        skip_special_tokens=False
    )

    # 3. Build generation kwargs
    generation_kwargs = dict(
        **inputs,
        max_new_tokens=max_new_tokens,
        do_sample=True,
        streamer=streamer,
        eos_token_id=eos_id,
        pad_token_id=pad_id
    )

    # 4. Launch generation in a thread
    thread = threading.Thread(target=current_model.generate, kwargs=generation_kwargs)
    thread.start()

    messages = messages.copy()
    messages.append({"role": "assistant", "content": ""})

    print(f'Step 1: {messages}')

    prompt_text = current_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=False)
    
    for token_info in streamer:
        token_str = token_info["token"]
        token_id = token_info["token_id"]
        is_special = token_info["is_special"]

        # Stop immediately at EOS
        if token_id == eos_id:
            break

        # Detect reasoning block
        if "<think>" in token_str:
            in_think = True
            token_str = token_str.replace("<think>", "")
            output_text += "*"

        if "</think>" in token_str:
            in_think = False
            token_str = token_str.replace("</think>", "")
            output_text += token_str + "*"
        else:
            output_text += token_str

        # Early stopping if user reappears
        if "\nUser" in output_text:
            output_text = output_text.split("\nUser")[0].rstrip()
            messages[-1]["content"] = output_text
            break

        generated_tokens += 1
        if generated_tokens >= max_new_tokens:
            break

        messages[-1]["content"] = output_text

        print(f'Step 2: {messages}')

        yield messages

    if in_think:
        output_text += "*"
        messages[-1]["content"] = output_text
    
    # Wait for thread to finish
    # current_model.to("cpu")
    torch.cuda.empty_cache()

    messages[-1]["content"] = output_text
    print(f'Step 3: {messages}')

    return messages



# Globals
current_model = None
current_tokenizer = None

def load_model_on_selection(model_name, progress=gr.Progress(track_tqdm=False)):
    global current_model, current_tokenizer
    token = os.getenv("HF_TOKEN")

    progress(0, desc="Loading tokenizer...")
    current_tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=token)

    progress(0.5, desc="Loading model...")
    current_model = AutoModelForCausalLM.from_pretrained(
        model_name,
        torch_dtype=torch.float16,
        device_map="cpu",  # loaded to CPU initially
        use_auth_token=token
    )

    progress(1, desc="Model ready.")
    return f"{model_name} loaded and ready!"

# Format conversation as plain text
def format_prompt(messages):
    prompt = ""
    for msg in messages:
        role = msg["role"]
        if role == "user":
            prompt += f"User: {msg['content'].strip()}\n"
        elif role == "assistant":
            prompt += f"Assistant: {msg['content'].strip()}\n"
    prompt += "Assistant:"
    return prompt

def add_user_message(user_input, history):
    return "", history + [{"role": "user", "content": user_input}]

# Curated models
model_choices = [
    "meta-llama/Llama-3.2-3B-Instruct",
    "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
    "google/gemma-7b",
    "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
]

with gr.Blocks() as demo:
    gr.Markdown("## Clinical Chatbot (Streaming)")

    default_model = gr.State(model_choices[0])

    with gr.Row():
        mode = gr.Radio(["Choose from list", "Enter custom model"], value="Choose from list", label="Model Input Mode")
        model_selector = gr.Dropdown(choices=model_choices, label="Select Predefined Model")
        model_textbox = gr.Textbox(label="Or Enter HF Model Name")

    model_status = gr.Textbox(label="Model Status", interactive=False)
    chatbot = gr.Chatbot(label="Chat", type="messages")
    msg = gr.Textbox(label="Your message", placeholder="Enter clinical input...", show_label=False)
    clear = gr.Button("Clear")

    def resolve_model_choice(mode, dropdown_value, textbox_value):
        return textbox_value.strip() if mode == "Enter custom model" else dropdown_value

    # Load on launch
    demo.load(fn=load_model_on_selection, inputs=default_model, outputs=model_status)

    # Load on user selection
    mode.select(fn=resolve_model_choice, inputs=[mode, model_selector, model_textbox], outputs=default_model).then(
        load_model_on_selection, inputs=default_model, outputs=model_status
    )
    model_selector.change(fn=resolve_model_choice, inputs=[mode, model_selector, model_textbox], outputs=default_model).then(
        load_model_on_selection, inputs=default_model, outputs=model_status
    )
    model_textbox.submit(fn=resolve_model_choice, inputs=[mode, model_selector, model_textbox], outputs=default_model).then(
        load_model_on_selection, inputs=default_model, outputs=model_status
    )

    msg.submit(add_user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
        chat_with_model, chatbot, chatbot
    )
    clear.click(lambda: [], None, chatbot, queue=False)


demo.launch()