Spaces:
Sleeping
Sleeping
update files
Browse files- app.py +45 -224
- install_env.sh +1 -1
- retrieval_server.py +2 -2
app.py
CHANGED
|
@@ -1,14 +1,20 @@
|
|
| 1 |
-
import transformers
|
| 2 |
-
import torch
|
| 3 |
-
import requests
|
| 4 |
-
import re
|
| 5 |
import gradio as gr
|
| 6 |
-
from
|
| 7 |
|
| 8 |
import subprocess
|
| 9 |
import time
|
| 10 |
import atexit
|
|
|
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
server_process = subprocess.Popen(["bash", "retrieval_launch.sh"])
|
| 14 |
print(f"Server process started with PID: {server_process.pid}")
|
|
@@ -21,229 +27,44 @@ try:
|
|
| 21 |
print("Server process terminated.")
|
| 22 |
|
| 23 |
atexit.register(cleanup)
|
|
|
|
| 24 |
except Exception as e:
|
| 25 |
print(f"Failed to start retrieval_launch.sh: {e}")
|
| 26 |
print("WARNING: The retrieval server may not be running.")
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
# 1. DEFINE YOUR MODEL
|
| 31 |
-
model_id = "yrshi/AutoRefine-Qwen2.5-3B-Base"
|
| 32 |
-
|
| 33 |
-
# 2. !!! CRITICAL: UPDATE THIS URL !!!
|
| 34 |
-
# Your local 'http://127.0.0.1:8000/retrieve' will NOT work on Hugging Face.
|
| 35 |
-
# You must deploy your retrieval service and provide its public URL here.
|
| 36 |
-
RETRIEVER_URL = "http://127.0.0.1:8000/retrieve" # <-- UPDATE ME
|
| 37 |
-
|
| 38 |
-
# 3. MODEL & SEARCH CONSTANTS
|
| 39 |
-
curr_eos = [151645, 151643] # for Qwen2.5 series models
|
| 40 |
-
curr_search_template = '\n\n{output_text}<documents>{search_results}</documents>\n\n'
|
| 41 |
-
target_sequences = ["</search>", " </search>", "</search>\n", " </search>\n", "</search>\n\n", " </search>\n\n"]
|
| 42 |
-
|
| 43 |
-
# --- Global Model & Tokenizer Loading -------------------------------
|
| 44 |
-
# This happens once when the Space starts.
|
| 45 |
-
# Ensure your Space has a GPU assigned (e.g., T4, A10G).
|
| 46 |
-
|
| 47 |
-
print("Loading model and tokenizer...")
|
| 48 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 49 |
-
|
| 50 |
-
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
|
| 51 |
-
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 52 |
-
model_id,
|
| 53 |
-
torch_dtype=torch.bfloat16,
|
| 54 |
-
device_map="auto"
|
| 55 |
-
)
|
| 56 |
-
print("Model and tokenizer loaded successfully.")
|
| 57 |
-
|
| 58 |
-
# --- Custom Stopping Criteria Class ---------------------------------
|
| 59 |
-
|
| 60 |
-
class StopOnSequence(transformers.StoppingCriteria):
|
| 61 |
-
def __init__(self, target_sequences, tokenizer):
|
| 62 |
-
self.target_ids = [tokenizer.encode(target_sequence, add_special_tokens=False) for target_sequence in target_sequences]
|
| 63 |
-
self.target_lengths = [len(target_id) for target_id in self.target_ids]
|
| 64 |
-
self._tokenizer = tokenizer
|
| 65 |
-
|
| 66 |
-
def __call__(self, input_ids, scores, **kwargs):
|
| 67 |
-
targets = [torch.as_tensor(target_id, device=input_ids.device) for target_id in self.target_ids]
|
| 68 |
-
if input_ids.shape[1] < min(self.target_lengths):
|
| 69 |
-
return False
|
| 70 |
-
for i, target in enumerate(targets):
|
| 71 |
-
if torch.equal(input_ids[0, -self.target_lengths[i]:], target):
|
| 72 |
-
return True
|
| 73 |
-
return False
|
| 74 |
-
|
| 75 |
-
# Initialize stopping criteria globally
|
| 76 |
-
stopping_criteria = transformers.StoppingCriteriaList([StopOnSequence(target_sequences, tokenizer)])
|
| 77 |
-
|
| 78 |
-
# --- Helper Functions (Search & Parse) ------------------------------
|
| 79 |
-
|
| 80 |
-
def get_query(text):
|
| 81 |
-
pattern = re.compile(r"<search>(.*?)</search>", re.DOTALL)
|
| 82 |
-
matches = pattern.findall(text)
|
| 83 |
-
return matches[-1] if matches else None
|
| 84 |
-
|
| 85 |
-
def search(query: str):
|
| 86 |
-
"""
|
| 87 |
-
Calls your deployed retriever service.
|
| 88 |
-
"""
|
| 89 |
-
payload = {"queries": [query], "topk": 3, "return_scores": True}
|
| 90 |
-
|
| 91 |
-
if RETRIEVER_URL == "http://127.0.0.1:8000/retrieve":
|
| 92 |
-
print("WARNING: Using default local retriever URL. This will likely fail.")
|
| 93 |
-
print("Please update RETRIEVER_URL in app.py to your deployed service.")
|
| 94 |
-
|
| 95 |
try:
|
| 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 |
-
This function implements your local multi-turn search logic as a
|
| 128 |
-
streaming generator for the Gradio interface.
|
| 129 |
-
"""
|
| 130 |
-
|
| 131 |
-
question = message.strip()
|
| 132 |
-
|
| 133 |
-
# Use the system_message from the UI as the base prompt
|
| 134 |
-
# Or, if empty, use your default.
|
| 135 |
-
if not system_message:
|
| 136 |
-
system_message = """You are a helpful assistant excel at answering questions with multi-turn search engine calling. \
|
| 137 |
-
To answer questions, you must first reason through the available information using <think> and </think>. \
|
| 138 |
-
If you identify missing knowledge, you may issue a search request using <search> query </search> at any time. The retrieval system will provide you with the three most relevant documents enclosed in <documents> and </documents>. \
|
| 139 |
-
After each search, you need to summarize and refine the existing documents in <refine> and </refine>. \
|
| 140 |
-
You may send multiple search requests if needed. \
|
| 141 |
-
Once you have sufficient information, provide a concise final answer using <answer> and </answer>. For example, <answer> Donald Trump </answer>."""
|
| 142 |
-
|
| 143 |
-
prompt = f"{system_message} Question: {question}\n"
|
| 144 |
-
|
| 145 |
-
if tokenizer.chat_template:
|
| 146 |
-
# Apply chat template if it exists
|
| 147 |
-
# Note: Your logic builds the prompt manually, but this ensures
|
| 148 |
-
# correct special tokens if the model needs them.
|
| 149 |
-
chat_prompt = [{"role": "user", "content": prompt}]
|
| 150 |
-
prompt = tokenizer.apply_chat_template(chat_prompt, add_generation_prompt=True, tokenize=False)
|
| 151 |
-
|
| 152 |
-
# This string will accumulate the full agent trajectory
|
| 153 |
-
full_response_trajectory = ""
|
| 154 |
-
|
| 155 |
-
while True:
|
| 156 |
-
input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
|
| 157 |
-
attention_mask = torch.ones_like(input_ids)
|
| 158 |
-
|
| 159 |
-
# Check for context overflow
|
| 160 |
-
if input_ids.shape[1] > model.config.max_position_embeddings - max_tokens:
|
| 161 |
-
print("Context limit reached.")
|
| 162 |
-
full_response_trajectory += "\n\n[Error: Context limit reached. Aborting.]"
|
| 163 |
-
yield full_response_trajectory
|
| 164 |
-
break
|
| 165 |
-
|
| 166 |
-
# Generate text with the stopping criteria
|
| 167 |
-
outputs = model.generate(
|
| 168 |
-
input_ids,
|
| 169 |
-
attention_mask=attention_mask,
|
| 170 |
-
max_new_tokens=max_tokens,
|
| 171 |
-
stopping_criteria=stopping_criteria,
|
| 172 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 173 |
-
do_sample=True,
|
| 174 |
-
temperature=temperature,
|
| 175 |
-
top_p=top_p
|
| 176 |
-
)
|
| 177 |
-
|
| 178 |
-
# Decode the *newly* generated tokens
|
| 179 |
-
generated_token_ids = outputs[0][input_ids.shape[1]:]
|
| 180 |
-
output_text = tokenizer.decode(generated_token_ids, skip_special_tokens=True)
|
| 181 |
-
|
| 182 |
-
# Check if generation ended with an EOS token
|
| 183 |
-
if outputs[0][-1].item() in curr_eos:
|
| 184 |
-
full_response_trajectory += output_text
|
| 185 |
-
yield full_response_trajectory # Yield the final text
|
| 186 |
-
break # Exit the loop
|
| 187 |
-
|
| 188 |
-
# --- Generation stopped at </search> ---
|
| 189 |
-
|
| 190 |
-
# Get the full text (prompt + new generation) to parse the *last* query
|
| 191 |
-
full_generation_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 192 |
-
query_text = get_query(full_generation_text)
|
| 193 |
-
|
| 194 |
-
if query_text:
|
| 195 |
-
search_results = search(query_text)
|
| 196 |
-
else:
|
| 197 |
-
search_results = 'Error: Stop token found but no <search> query was parsed.'
|
| 198 |
-
|
| 199 |
-
# Construct the text to append to the prompt
|
| 200 |
-
search_text = curr_search_template.format(
|
| 201 |
-
output_text=output_text,
|
| 202 |
-
search_results=search_results
|
| 203 |
-
)
|
| 204 |
-
|
| 205 |
-
# Append to the prompt for the next loop
|
| 206 |
-
prompt += search_text
|
| 207 |
-
|
| 208 |
-
# Append to the trajectory string and yield to the UI
|
| 209 |
-
full_response_trajectory += search_text
|
| 210 |
-
yield full_response_trajectory
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
# --- Gradio UI (Example) -------------------------------------------
|
| 214 |
-
# This part is just to make the file runnable.
|
| 215 |
-
# You can customize your Gradio UI as needed.
|
| 216 |
-
|
| 217 |
-
with gr.Blocks() as demo:
|
| 218 |
-
gr.Markdown("# Multi-Turn Search Agent")
|
| 219 |
-
gr.Markdown(f"Running model: `{model_id}`")
|
| 220 |
-
|
| 221 |
-
with gr.Accordion("Prompt & Parameters"):
|
| 222 |
-
system_message = gr.Textbox(
|
| 223 |
-
label="System Message",
|
| 224 |
-
value="""You are a helpful assistant... (full prompt from code)""",
|
| 225 |
-
lines=10
|
| 226 |
-
)
|
| 227 |
-
max_tokens = gr.Slider(50, 2048, value=1024, label="Max New Tokens")
|
| 228 |
-
temperature = gr.Slider(0.1, 1.0, value=0.7, label="Temperature")
|
| 229 |
-
top_p = gr.Slider(0.1, 1.0, value=1.0, label="Top-p")
|
| 230 |
-
|
| 231 |
-
chatbot = gr.Chatbot(label="Agent Trajectory")
|
| 232 |
-
msg = gr.Textbox(label="Your Question")
|
| 233 |
-
|
| 234 |
-
def user_turn(user_message, history):
|
| 235 |
-
return "", history + [[user_message, None]]
|
| 236 |
|
| 237 |
-
|
| 238 |
-
user_turn,
|
| 239 |
-
[msg, chatbot],
|
| 240 |
-
[msg, chatbot],
|
| 241 |
-
queue=False
|
| 242 |
-
).then(
|
| 243 |
-
respond,
|
| 244 |
-
[msg, chatbot, system_message, max_tokens, temperature, top_p],
|
| 245 |
-
chatbot
|
| 246 |
-
)
|
| 247 |
|
| 248 |
-
if __name__ == "__main__":
|
| 249 |
-
demo.queue().launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from infer import run_search, question_list
|
| 3 |
|
| 4 |
import subprocess
|
| 5 |
import time
|
| 6 |
import atexit
|
| 7 |
+
from urllib.parse import urlparse
|
| 8 |
|
| 9 |
+
# ... (keep all your other imports like transformers, torch, requests, re, gr) ...
|
| 10 |
+
|
| 11 |
+
# --- NEW: Server Launch Block ---
|
| 12 |
+
# Insert this block *before* you load the model
|
| 13 |
+
# -----------------------------------------------------------------
|
| 14 |
+
print("Attempting to start retrieval server...")
|
| 15 |
+
|
| 16 |
+
# Start the server as a background process
|
| 17 |
+
# subprocess.Popen does not block, unlike os.system
|
| 18 |
try:
|
| 19 |
server_process = subprocess.Popen(["bash", "retrieval_launch.sh"])
|
| 20 |
print(f"Server process started with PID: {server_process.pid}")
|
|
|
|
| 27 |
print("Server process terminated.")
|
| 28 |
|
| 29 |
atexit.register(cleanup)
|
| 30 |
+
|
| 31 |
except Exception as e:
|
| 32 |
print(f"Failed to start retrieval_launch.sh: {e}")
|
| 33 |
print("WARNING: The retrieval server may not be running.")
|
| 34 |
|
| 35 |
+
def gradio_answer(question: str) -> str:
|
| 36 |
+
print(f"\nReceived question for Gradio: {question}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
+
# Call the core inference function, passing the pre-loaded assets
|
| 39 |
+
trajectory, answer = run_search(question)
|
| 40 |
+
answer_string = f"Final answer: {answer.strip()}"
|
| 41 |
+
answer_string += f"\n\n====== Trajectory of reasoning steps ======\n{trajectory.strip()}"
|
| 42 |
+
return answer_string
|
| 43 |
+
except Exception as e:
|
| 44 |
+
# Basic error handling for the Gradio interface
|
| 45 |
+
return f"An error occurred: {e}. Please check the console for more details."
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
iface = gr.Interface(
|
| 49 |
+
fn=gradio_answer,
|
| 50 |
+
inputs=gr.Textbox(
|
| 51 |
+
lines=3,
|
| 52 |
+
label="Enter your question",
|
| 53 |
+
placeholder="e.g., Who invented the telephone?"
|
| 54 |
+
),
|
| 55 |
+
outputs=gr.Textbox(
|
| 56 |
+
label="Answer",
|
| 57 |
+
show_copy_button=True, # Allow users to easily copy the answer
|
| 58 |
+
elem_id="answer_output" # Optional: for custom CSS/JS targeting
|
| 59 |
+
),
|
| 60 |
+
title="Demo of AutoRefine: Question Answering with Search and Refine During Thinking",
|
| 61 |
+
description=("Ask a question and this model will use a multi-turn reasoning and search mechanism to find the answer."),
|
| 62 |
+
examples=question_list, # Use the list of example questions
|
| 63 |
+
live=False, # Set to True if you want real-time updates as user types
|
| 64 |
+
allow_flagging="never", # Disable flagging functionality
|
| 65 |
+
theme=gr.themes.Soft(), # Apply a clean theme
|
| 66 |
+
cache_examples=True, # Cache the examples for faster loading
|
| 67 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
iface.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
|
|
|
|
|
install_env.sh
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main
|
| 3 |
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r
|
| 4 |
|
| 5 |
-
conda install python=3.10 -y
|
| 6 |
conda install pytorch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 pytorch-cuda=12.1 -c pytorch -c nvidia -y
|
| 7 |
pip install transformers datasets pyserini
|
| 8 |
|
|
|
|
| 2 |
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main
|
| 3 |
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r
|
| 4 |
|
| 5 |
+
# conda install python=3.10 -y
|
| 6 |
conda install pytorch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 pytorch-cuda=12.1 -c pytorch -c nvidia -y
|
| 7 |
pip install transformers datasets pyserini
|
| 8 |
|
retrieval_server.py
CHANGED
|
@@ -48,7 +48,7 @@ def load_model(model_path: str, use_fp16: bool = False):
|
|
| 48 |
model_config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 49 |
model = AutoModel.from_pretrained(model_path, trust_remote_code=True)
|
| 50 |
model.eval()
|
| 51 |
-
model
|
| 52 |
if use_fp16:
|
| 53 |
model = model.half()
|
| 54 |
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True, trust_remote_code=True)
|
|
@@ -103,7 +103,7 @@ class Encoder:
|
|
| 103 |
truncation=True,
|
| 104 |
return_tensors="pt"
|
| 105 |
)
|
| 106 |
-
inputs = {k: v
|
| 107 |
|
| 108 |
if "T5" in type(self.model).__name__:
|
| 109 |
# T5-based retrieval model
|
|
|
|
| 48 |
model_config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 49 |
model = AutoModel.from_pretrained(model_path, trust_remote_code=True)
|
| 50 |
model.eval()
|
| 51 |
+
model
|
| 52 |
if use_fp16:
|
| 53 |
model = model.half()
|
| 54 |
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True, trust_remote_code=True)
|
|
|
|
| 103 |
truncation=True,
|
| 104 |
return_tensors="pt"
|
| 105 |
)
|
| 106 |
+
inputs = {k: v for k, v in inputs.items()}
|
| 107 |
|
| 108 |
if "T5" in type(self.model).__name__:
|
| 109 |
# T5-based retrieval model
|