legolasyiu commited on
Commit
6b3973e
·
verified ·
1 Parent(s): 058e0ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -35
app.py CHANGED
@@ -1,48 +1,97 @@
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  def respond(
6
  message,
7
- history: list[dict[str, str]],
8
  system_message,
9
  max_tokens,
10
  temperature,
11
  top_p,
12
- hf_token: gr.OAuthToken,
13
  ):
14
  """
15
- 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
 
16
  """
17
- client = InferenceClient(token=hf_token.token, model="EpistemeAI/VibeCoder-20B-alpha-0.001")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
 
21
- messages.extend(history)
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
24
 
25
- response = ""
 
 
 
 
 
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = 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
  chatbot = gr.ChatInterface(
47
  respond,
48
  type="messages",
@@ -50,21 +99,15 @@ chatbot = gr.ChatInterface(
50
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
  ],
61
  )
62
 
63
  with gr.Blocks() as demo:
64
  with gr.Sidebar():
 
65
  gr.LoginButton()
66
  chatbot.render()
67
 
68
-
69
  if __name__ == "__main__":
70
  demo.launch()
 
1
+ # save as app.py
2
+ import threading
3
  import gradio as gr
4
+ import torch
5
+ from transformers import (
6
+ AutoTokenizer,
7
+ AutoModelForCausalLM,
8
+ TextIteratorStreamer,
9
+ )
10
+
11
+ MODEL_ID = "EpistemeAI/VibeCoder-20B-alpha-0.001"
12
+
13
+ # --------- Model load (do this once at startup) ----------
14
+ # Adjust dtype / device_map to your environment.
15
+ # If you have limited GPU memory, consider: device_map="auto", load_in_8bit=True (requires bitsandbytes)
16
+ print("Loading tokenizer and model (this may take a while)...")
17
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=True, trust_remote_code=True)
18
+
19
+ # Recommended: try device_map="auto" with accelerate installed; fallback to cpu if not available.
20
+ try:
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ MODEL_ID,
23
+ device_map="auto",
24
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
25
+ trust_remote_code=True,
26
+ )
27
+ except Exception as e:
28
+ print("Automatic device_map load failed, falling back to cpu. Error:", e)
29
+ model = AutoModelForCausalLM.from_pretrained(
30
+ MODEL_ID,
31
+ device_map={"": "cpu"},
32
+ torch_dtype=torch.float32,
33
+ trust_remote_code=True,
34
+ )
35
 
36
+ model.eval()
37
+ print("Model loaded. Device:", next(model.parameters()).device)
38
 
39
+ # --------- Helper: build prompt ----------
40
+ def build_prompt(system_message: str, history: list[dict], user_message: str) -> str:
41
+ # Keep your conversation structure — adapt to model's preferred format if needed.
42
+ pieces = []
43
+ if system_message:
44
+ pieces.append(f"<|system|>\n{system_message}\n")
45
+ for turn in history:
46
+ role = turn.get("role", "user")
47
+ content = turn.get("content", "")
48
+ pieces.append(f"<|{role}|>\n{content}\n")
49
+ pieces.append(f"<|user|>\n{user_message}\n<|assistant|>\n")
50
+ return "\n".join(pieces)
51
+
52
+ # --------- Gradio respond function (streams tokens) ----------
53
  def respond(
54
  message,
55
+ history: list[dict],
56
  system_message,
57
  max_tokens,
58
  temperature,
59
  top_p,
60
+ hf_token=None, # kept for compatibility with UI; not used for local pipeline
61
  ):
62
  """
63
+ Streams tokens as they are generated using TextIteratorStreamer.
64
+ Gradio will accept a generator yielding partial response strings.
65
  """
66
+ prompt = build_prompt(system_message, history or [], message)
 
 
67
 
68
+ # Prepare inputs
69
+ inputs = tokenizer(prompt, return_tensors="pt")
70
+ input_ids = inputs["input_ids"].to(model.device)
71
 
72
+ # Create streamer to yield token-chunks as they are generated
73
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
74
 
75
+ gen_kwargs = dict(
76
+ input_ids=input_ids,
77
+ max_new_tokens=int(max_tokens),
78
+ do_sample=True,
79
+ temperature=float(temperature),
80
+ top_p=float(top_p),
81
+ streamer=streamer,
82
+ )
83
 
84
+ # Start generation in background thread
85
+ thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
86
+ thread.start()
 
 
 
 
 
 
 
 
87
 
88
+ partial = ""
89
+ # Iterate streamer yields token chunks (strings)
90
+ for token_str in streamer:
91
+ partial += token_str
92
+ yield partial
93
 
94
+ # --------- Build Gradio UI ----------
 
 
 
95
  chatbot = gr.ChatInterface(
96
  respond,
97
  type="messages",
 
99
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
100
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
101
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
102
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
 
 
 
 
 
 
103
  ],
104
  )
105
 
106
  with gr.Blocks() as demo:
107
  with gr.Sidebar():
108
+ gr.Markdown("Model: " + MODEL_ID)
109
  gr.LoginButton()
110
  chatbot.render()
111
 
 
112
  if __name__ == "__main__":
113
  demo.launch()