legolasyiu commited on
Commit
4c1a418
·
verified ·
1 Parent(s): f35ca45

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -183
app.py CHANGED
@@ -1,189 +1,21 @@
1
- # save as app.py
2
- """
3
- Gradio streaming chat where:
4
- - user messages are visible in the UI,
5
- - system messages are hidden (kept for context),
6
- - assistant output is streamed and updates in-place.
7
- - full back-and-forth memory between turns.
8
 
9
- Requirements:
10
- pip install torch transformers gradio
11
- """
12
-
13
- import threading
14
  import gradio as gr
15
- import torch
16
- from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
17
-
18
- MODEL_ID = "EpistemeAI/metatune-gpt20b-R0"
19
-
20
- print("Loading tokenizer and model (this may take a while)...")
21
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
22
-
23
- # Use auto dtype & device mapping
24
- model = AutoModelForCausalLM.from_pretrained(
25
- MODEL_ID,
26
- torch_dtype="auto",
27
- device_map="auto",
28
- )
29
- model.eval()
30
- print("Model loaded. Example param device:", next(model.parameters()).device)
31
-
32
- # Thread-safe global history
33
- GLOBAL_HISTORY = [] # list of {"role": "system"|"user"|"assistant", "content": "..."}
34
- HISTORY_LOCK = threading.Lock()
35
-
36
-
37
- def build_prompt(system_message: str, history: list, user_message: str) -> str:
38
- """
39
- Build prompt in the model's expected format. Adjust as needed.
40
- """
41
- pieces = []
42
- if system_message:
43
- pieces.append(f"<|system|>\n{system_message}\n")
44
- for turn in history:
45
- role = turn.get("role", "user")
46
- content = turn.get("content", "")
47
- pieces.append(f"<|{role}|>\n{content}\n")
48
- pieces.append(f"<|user|>\n{user_message}\n<|assistant|>\n")
49
- return "\n".join(pieces)
50
-
51
-
52
- def generate_stream(prompt: str, max_tokens: int, temperature: float, top_p: float):
53
- """
54
- Stream partial strings via TextIteratorStreamer.
55
- """
56
- inputs = tokenizer(prompt, return_tensors="pt")
57
- try:
58
- input_ids = inputs["input_ids"].to(next(model.parameters()).device)
59
- except Exception:
60
- input_ids = inputs["input_ids"]
61
-
62
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
63
-
64
- gen_kwargs = dict(
65
- input_ids=input_ids,
66
- max_new_tokens=int(max_tokens),
67
- do_sample=True,
68
- temperature=float(temperature),
69
- top_p=float(top_p),
70
- streamer=streamer,
71
- )
72
-
73
- thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
74
- thread.start()
75
-
76
- partial = ""
77
- for token_str in streamer:
78
- partial += token_str
79
- yield partial
80
-
81
-
82
- def visible_messages_from_history(real_history: list, streaming_partial: str | None):
83
- """
84
- Convert internal history into Gradio-visible messages.
85
- - Show user messages.
86
- - Show assistant messages (partial or final).
87
- - Hide system messages.
88
- """
89
- msgs = []
90
- for entry in real_history:
91
- role = entry.get("role")
92
- content = entry.get("content", "")
93
- if role == "system":
94
- continue
95
- msgs.append({"role": role, "content": content or ("thinking..." if role == "assistant" else "")})
96
-
97
- if streaming_partial is not None:
98
- if msgs and msgs[-1]["role"] == "assistant":
99
- msgs[-1]["content"] = streaming_partial
100
- else:
101
- msgs.append({"role": "assistant", "content": streaming_partial})
102
-
103
- return msgs
104
-
105
-
106
- def respond_stream(user_message, system_message, max_tokens, temperature, top_p, history_state):
107
- """
108
- Gradio streaming handler with persistent memory.
109
- """
110
- if history_state is None:
111
- history_state = []
112
-
113
- # Sync local and global histories (optional global memory)
114
- with HISTORY_LOCK:
115
- GLOBAL_HISTORY[:] = history_state
116
-
117
- # Add the new user message and placeholder assistant
118
- with HISTORY_LOCK:
119
- if system_message:
120
- GLOBAL_HISTORY.append({"role": "system", "content": system_message})
121
- GLOBAL_HISTORY.append({"role": "user", "content": user_message})
122
- GLOBAL_HISTORY.append({"role": "assistant", "content": ""})
123
- snapshot = list(GLOBAL_HISTORY)
124
-
125
- # Show initial "thinking..." state
126
- initial_display = visible_messages_from_history(snapshot, streaming_partial="thinking...")
127
- yield initial_display, snapshot
128
-
129
- # Build prompt excluding assistant placeholder
130
- with HISTORY_LOCK:
131
- prompt_history = [h for h in GLOBAL_HISTORY[:-1]]
132
- prompt = build_prompt(system_message or "", prompt_history, user_message or "")
133
-
134
- # Stream generation and update assistant output
135
- for partial in generate_stream(prompt, max_tokens, temperature, top_p):
136
- with HISTORY_LOCK:
137
- if GLOBAL_HISTORY and GLOBAL_HISTORY[-1]["role"] == "assistant":
138
- GLOBAL_HISTORY[-1]["content"] = partial
139
- snapshot = list(GLOBAL_HISTORY)
140
- display = visible_messages_from_history(snapshot, streaming_partial=partial)
141
- yield display, snapshot
142
-
143
- # Final display
144
- with HISTORY_LOCK:
145
- final_snapshot = list(GLOBAL_HISTORY)
146
- final_display = visible_messages_from_history(final_snapshot, streaming_partial=final_snapshot[-1].get("content", ""))
147
- yield final_display, final_snapshot
148
-
149
-
150
- def reset_all():
151
- with HISTORY_LOCK:
152
- GLOBAL_HISTORY.clear()
153
- return [], []
154
-
155
-
156
- # --- Gradio UI ---
157
- with gr.Blocks() as demo:
158
- gr.Markdown(f"**Model:** {MODEL_ID} — (system messages hidden; user visible)")
159
-
160
- chatbot = gr.Chatbot(elem_id="chatbot", label="Chat", type="messages", height=560)
161
- history_state = gr.State([])
162
-
163
- with gr.Row():
164
- with gr.Column(scale=4):
165
- user_input = gr.Textbox(placeholder="Type a message and press Send", label="Your message")
166
- with gr.Column(scale=2):
167
- system_input = gr.Textbox(value="You are a Vibe Coder assistant.", label="System message (hidden)")
168
- max_tokens = gr.Slider(minimum=1, maximum=4000, value=800, step=1, label="Max new tokens")
169
- temperature = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.01, label="Temperature")
170
- top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p (nucleus sampling)")
171
- send_btn = gr.Button("Send")
172
 
173
- send_btn.click(
174
- fn=respond_stream,
175
- inputs=[user_input, system_input, max_tokens, temperature, top_p, history_state],
176
- outputs=[chatbot, history_state],
177
- queue=True,
178
- )
179
 
180
- clear_btn = gr.Button("Reset conversation")
181
- clear_btn.click(fn=reset_all, inputs=None, outputs=[chatbot, history_state])
 
 
 
 
 
 
182
 
183
- gr.Markdown(
184
- "Notes: model loading uses `device_map='auto'` and `torch_dtype='auto'`. "
185
- "If running multi-worker (gunicorn) you will need an external history store (Redis/DB)."
186
- )
187
 
188
- if __name__ == "__main__":
189
- demo.launch()
 
 
 
 
 
 
 
 
1
 
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
 
 
 
 
3
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ checkpoint = "EpistemeAI/metatune-20b"
6
+ device = "cpu" # "cuda" or "cpu"
7
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
8
+ model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
 
 
9
 
10
+ def predict(message, history):
11
+ history.append({"role": "user", "content": message})
12
+ input_text = tokenizer.apply_chat_template(history, tokenize=False)
13
+ inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
14
+ outputs = model.generate(inputs, max_new_tokens=64000, temperature=0.9, top_p=0.9, do_sample=True)
15
+ decoded = tokenizer.decode(outputs[0])
16
+ response = decoded.split("<|im_start|>assistant\n")[-1].split("<|im_end|>")[0]
17
+ return response
18
 
19
+ demo = gr.ChatInterface(predict, type="messages")
 
 
 
20
 
21
+ demo.launch()