rahul7star commited on
Commit
35c9e22
·
verified ·
1 Parent(s): 74e1186

Update app_low.py

Browse files
Files changed (1) hide show
  1. app_low.py +107 -16
app_low.py CHANGED
@@ -1,18 +1,109 @@
1
- # Load model directly
 
 
 
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
 
4
- tokenizer = AutoTokenizer.from_pretrained("rubricreward/mR3-Qwen3-14B-en-prompt-en-thinking")
5
- model = AutoModelForCausalLM.from_pretrained("rubricreward/mR3-Qwen3-14B-en-prompt-en-thinking")
6
- messages = [
7
- {"role": "user", "content": "Who are you?"},
8
- ]
9
- inputs = tokenizer.apply_chat_template(
10
- messages,
11
- add_generation_prompt=True,
12
- tokenize=True,
13
- return_dict=True,
14
- return_tensors="pt",
15
- ).to(model.device)
16
-
17
- outputs = model.generate(**inputs, max_new_tokens=40)
18
- print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
+ from huggingface_hub import snapshot_download
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
 
7
+ # =========================================================
8
+ # 1️⃣ Download model from HF (once)
9
+ # =========================================================
10
+ MODEL_ID = "rubricreward/mR3-Qwen3-14B-en-prompt-en-thinking"
11
+ print(f"📦 Downloading or loading cached model: {MODEL_ID} ...")
12
+ model_path = snapshot_download(repo_id=MODEL_ID)
13
+ print(f"✅ Model path: {model_path}")
14
+
15
+ # =========================================================
16
+ # 2️⃣ Smart device setup (auto CPU/GPU/offload)
17
+ # =========================================================
18
+ if torch.cuda.is_available():
19
+ device = "cuda"
20
+ dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
21
+ print("⚙️ Using CUDA for inference.")
22
+ else:
23
+ device = "cpu"
24
+ dtype = torch.float32
25
+ print("⚙️ Using CPU — applying efficient offloading settings.")
26
+
27
+ # =========================================================
28
+ # 3️⃣ Load model and tokenizer with optimized config
29
+ # =========================================================
30
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
31
+
32
+ model = AutoModelForCausalLM.from_pretrained(
33
+ model_path,
34
+ torch_dtype=dtype,
35
+ device_map="auto" if device == "cuda" else {"": "cpu"},
36
+ low_cpu_mem_usage=True,
37
+ offload_folder="./offload" if device == "cpu" else None,
38
+ )
39
+
40
+ # =========================================================
41
+ # 4️⃣ Chat inference function
42
+ # =========================================================
43
+ def chat_with_model(user_input, chat_history):
44
+ """Run chat-style inference."""
45
+ if not user_input.strip():
46
+ return chat_history + [["", "⚠️ Please enter a message."]]
47
+
48
+ messages = [{"role": "user", "content": user_input}]
49
+ inputs = tokenizer.apply_chat_template(
50
+ messages,
51
+ add_generation_prompt=True,
52
+ tokenize=True,
53
+ return_tensors="pt",
54
+ ).to(model.device)
55
+
56
+ with torch.no_grad():
57
+ outputs = model.generate(
58
+ **inputs,
59
+ max_new_tokens=128,
60
+ temperature=0.7,
61
+ top_p=0.9,
62
+ do_sample=True,
63
+ repetition_penalty=1.1,
64
+ )
65
+
66
+ response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
67
+ chat_history = chat_history + [[user_input, response.strip()]]
68
+ return chat_history
69
+
70
+ # =========================================================
71
+ # 5️⃣ Gradio Chat UI
72
+ # =========================================================
73
+ with gr.Blocks(theme=gr.themes.Soft(), title="💬 Qwen3-14B Thinking Chat") as demo:
74
+ gr.Markdown(
75
+ """
76
+ # 🧠 mR3-Qwen3-14B Prompt-Enhanced Chat
77
+ A reasoning-ready English chat model from **RubricReward**, optimized for CPU/GPU with offloading.
78
+ ---
79
+ """
80
+ )
81
+
82
+ chatbot = gr.Chatbot(height=400, label="Chat with mR3-Qwen3-14B")
83
+ user_input = gr.Textbox(placeholder="Type your message here...", label="Your Message", lines=2)
84
+ send_button = gr.Button("🚀 Send", variant="primary")
85
+
86
+ def clear_history():
87
+ return []
88
+
89
+ clear_btn = gr.Button("🧹 Clear Chat")
90
+
91
+ send_button.click(chat_with_model, [user_input, chatbot], chatbot)
92
+ user_input.submit(chat_with_model, [user_input, chatbot], chatbot)
93
+ clear_btn.click(fn=clear_history, outputs=chatbot)
94
+
95
+ gr.Markdown(
96
+ """
97
+ ---
98
+ 💡 **Tips:**
99
+ - Ask it to explain, reason, or summarize complex ideas.
100
+ - Try: *“Explain quantum computing in simple terms.”*
101
+ - Try: *“Give me 3 creative ways to promote a science exhibition.”*
102
+ """
103
+ )
104
+
105
+ # =========================================================
106
+ # 6️⃣ Launch App
107
+ # =========================================================
108
+ if __name__ == "__main__":
109
+ demo.launch()