Hrushi02 commited on
Commit
646b139
·
verified ·
1 Parent(s): 8db5361

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -50
app.py CHANGED
@@ -1,19 +1,55 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
- from transformers import AutoTokenizer
4
-
5
- # Initialize client and tokenizer
6
- client = InferenceClient()
7
- tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
8
-
9
- def respond(message, history):
10
- # Build messages list from history + new message
11
- messages = []
12
- for user_msg, assistant_msg in history:
13
- if user_msg:
14
- messages.append({"role": "user", "content": user_msg})
15
- if assistant_msg:
16
- messages.append({"role": "assistant", "content": assistant_msg})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  messages.append({"role": "user", "content": message})
18
 
19
  # Apply chat template
@@ -21,44 +57,50 @@ def respond(message, history):
21
  messages, tokenize=False, add_generation_prompt=True
22
  )
23
 
24
- # Generate response (non-streaming; for streaming, use generator below)
25
- response = client.text_generation(
26
- prompt,
27
- model="HuggingFaceH4/zephyr-7b-beta",
28
- max_new_tokens=256,
29
- temperature=0.7,
30
- do_sample=True,
31
- top_k=50,
32
- top_p=0.95,
33
- repetition_penalty=1.1,
34
- return_full_text=False # Only new tokens
35
- )
36
- return response
37
-
38
- # For streaming (if your original used stream=True), replace the generation with:
39
- # def respond(message, history):
40
- # ... (same messages and prompt)
41
- # for chunk in client.text_generation(
42
- # prompt,
43
- # model="HuggingFaceH4/zephyr-7b-beta",
44
- # max_new_tokens=256,
45
- # temperature=0.7,
46
- # do_sample=True,
47
- # top_k=50,
48
- # top_p=0.95,
49
- # repetition_penalty=1.1,
50
- # return_full_text=False,
51
- # stream=True
52
- # ):
53
- # yield chunk # Yield chunks for Gradio streaming
54
-
55
- # Gradio interface with fixed chatbot format
56
  demo = gr.ChatInterface(
57
  respond,
58
- chatbot=gr.Chatbot(type="messages"), # Fixes deprecation warning
 
 
 
 
 
 
 
 
 
 
 
 
59
  title="Root Math Chatbot",
60
- description="Ask math questions about roots and equations!"
61
  )
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
1
+ ```python
2
  import gradio as gr
3
+ import os
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from peft import PeftModel
6
+ import torch
7
+
8
+ # Load Hugging Face API token securely
9
+ api_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
10
+
11
+ if not api_token:
12
+ raise ValueError("❌ ERROR: Hugging Face API token is not set. Please set it as an environment variable.")
13
+
14
+ # Define model names
15
+ base_model_name = "unsloth/qwen2.5-math-7b-bnb-4bit"
16
+ peft_model_name = "Hrushi02/Root_Math"
17
+
18
+ # Load base model with authentication
19
+ base_model = AutoModelForCausalLM.from_pretrained(
20
+ base_model_name,
21
+ torch_dtype=torch.float16,
22
+ device_map="auto",
23
+ use_auth_token=api_token # ✅ Correct
24
+ )
25
+
26
+ # Load fine-tuned model
27
+ model = PeftModel.from_pretrained(base_model, peft_model_name, token=api_token)
28
+
29
+ # Load tokenizer
30
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name, token=api_token)
31
+
32
+ # Ensure pad_token is set
33
+ if tokenizer.pad_token is None:
34
+ tokenizer.pad_token = tokenizer.eos_token
35
+
36
+ def respond(
37
+ message,
38
+ history: list[tuple[str, str]],
39
+ system_message,
40
+ max_tokens,
41
+ temperature,
42
+ top_p,
43
+ ):
44
+ # Build messages list
45
+ messages = [{"role": "system", "content": system_message}]
46
+
47
+ for val in history:
48
+ if val[0]:
49
+ messages.append({"role": "user", "content": val[0]})
50
+ if val[1]:
51
+ messages.append({"role": "assistant", "content": val[1]})
52
+
53
  messages.append({"role": "user", "content": message})
54
 
55
  # Apply chat template
 
57
  messages, tokenize=False, add_generation_prompt=True
58
  )
59
 
60
+ # Tokenize input
61
+ inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
62
+
63
+ # Generate response with streaming
64
+ with torch.no_grad():
65
+ for new_token in model.generate(
66
+ **inputs,
67
+ max_new_tokens=max_tokens,
68
+ temperature=temperature,
69
+ top_p=top_p,
70
+ do_sample=True,
71
+ pad_token_id=tokenizer.eos_token_id,
72
+ repetition_penalty=1.1,
73
+ streamer=None, # We'll handle streaming manually
74
+ ):
75
+ # Decode the new token
76
+ new_token_decoded = tokenizer.decode(new_token[-1:], skip_special_tokens=True)
77
+ yield new_token_decoded
78
+
79
+ # Note: For true token-by-token streaming in Gradio, the above yields per-token.
80
+ # If you want full sentence streaming, accumulate and yield periodically, but this matches the original's per-token yield.
81
+
82
+ """
83
+ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
84
+ """
 
 
 
 
 
 
 
85
  demo = gr.ChatInterface(
86
  respond,
87
+ additional_inputs=[
88
+ gr.Textbox(value="You are a helpful math assistant specialized in solving equations and finding roots.", label="System message"),
89
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
90
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
91
+ gr.Slider(
92
+ minimum=0.1,
93
+ maximum=1.0,
94
+ value=0.95,
95
+ step=0.05,
96
+ label="Top-p (nucleus sampling)",
97
+ ),
98
+ ],
99
+ chatbot=gr.Chatbot(type="messages"), # Modern format to avoid deprecation
100
  title="Root Math Chatbot",
101
+ description="A fine-tuned Qwen2.5-Math model for solving roots and math problems."
102
  )
103
 
104
  if __name__ == "__main__":
105
+ demo.launch()
106
+ ```