theostos commited on
Commit
0a5e5a2
·
1 Parent(s): fb3c11d

initial commit

Browse files
Files changed (3) hide show
  1. .gitignore +1 -0
  2. app.py +230 -0
  3. requirements.txt +5 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .vscode
app.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import json
3
+ import os
4
+ import textwrap
5
+ from typing import List, Dict, Any
6
+
7
+ import gradio as gr
8
+ import requests
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from transformers import AutoTokenizer, AutoModel
12
+
13
+ # -----------------------------
14
+ # Embedding utilities (from your snippet, with a couple of safety tweaks)
15
+ # -----------------------------
16
+ def last_token_pool(last_hidden_states: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
17
+ left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
18
+ if left_padding:
19
+ return last_hidden_states[:, -1]
20
+ else:
21
+ sequence_lengths = attention_mask.sum(dim=1) - 1
22
+ batch_size = last_hidden_states.shape[0]
23
+ return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
24
+
25
+ def get_detailed_instruct(task_description: str, query: str) -> str:
26
+ return f"Instruct: {task_description}\nQuery: {query}"
27
+
28
+ class Qwen3Embedding:
29
+ def __init__(self, device: str, size: str = "0.6B"):
30
+ assert size in ["0.6B", "4B", "8B"]
31
+ model_id = "Qwen/Qwen3-Embedding-" + size
32
+ self.device = device
33
+
34
+ self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
35
+ # Use bfloat16 on GPU, float32 on CPU (safer on Spaces CPU)
36
+ dtype = torch.bfloat16 if device != "cpu" else torch.float32
37
+ self.model = AutoModel.from_pretrained(model_id, trust_remote_code=True).to(device, dtype=dtype)
38
+
39
+ self.prompt_query = (
40
+ "Given a natural language query, retrieve formal Coq statements whose docstrings "
41
+ "best match the intent of the query."
42
+ )
43
+
44
+ @torch.inference_mode()
45
+ def generate(self, sentence: str, is_query: bool = False) -> torch.Tensor:
46
+ input_text = get_detailed_instruct(self.prompt_query, sentence) if is_query else sentence
47
+ batch_dict = self.tokenizer(input_text, padding=True, truncation=True, return_tensors="pt").to(self.device)
48
+ outputs = self.model(**batch_dict)
49
+ embeddings = last_token_pool(outputs.last_hidden_state, batch_dict["attention_mask"])
50
+ embeddings = F.normalize(embeddings, p=2, dim=1)
51
+ return embeddings
52
+
53
+ def name(self) -> str:
54
+ return "qwen_embedding_base"
55
+
56
+ @functools.lru_cache(maxsize=3)
57
+ def get_embedder() -> Qwen3Embedding:
58
+ return Qwen3Embedding(device="cpu", size="4B")
59
+
60
+ # -----------------------------
61
+ # Backend call
62
+ # -----------------------------
63
+ def call_retrieval_service(
64
+ server_url: str, embedding: List[float], top_k: int, timeout: int = 60
65
+ ) -> List[Dict[str, Any]]:
66
+ if server_url.endswith("/"):
67
+ server_url = server_url[:-1]
68
+ url = f"{server_url}/query"
69
+
70
+ payload = {"query": [embedding], "top_k": int(top_k)}
71
+ resp = requests.post(url, json=payload, timeout=timeout)
72
+ resp.raise_for_status()
73
+ data = resp.json()
74
+ if not isinstance(data, list):
75
+ raise ValueError("Unexpected response format: expected a list of entries.")
76
+ return data
77
+
78
+ # -----------------------------
79
+ # Formatting helpers
80
+ # -----------------------------
81
+ def _html_escape(s: str) -> str:
82
+ return (
83
+ s.replace("&", "&")
84
+ .replace("<", "&lt;")
85
+ .replace(">", "&gt;")
86
+ )
87
+
88
+ def render_results(items: List[Dict[str, Any]]) -> str:
89
+ if not items:
90
+ return "<div>No results.</div>"
91
+
92
+ rows = []
93
+ for idx, it in enumerate(items, start=1):
94
+ score = it.get("score", 0.0)
95
+ name = it.get("name", "")
96
+ kind = it.get("kind", "")
97
+ doc = it.get("docstring", "") or ""
98
+ location = it.get("location", "") or ""
99
+
100
+ # Trim long docstrings for the summary line
101
+ summary = " ".join(doc.strip().split())
102
+ if len(summary) > 240:
103
+ summary = summary[:240].rstrip() + "…"
104
+
105
+ block = f"""
106
+ <div class="result-card">
107
+ <div class="header">
108
+ <span class="rank">#{idx}</span>
109
+ <code class="name">{_html_escape(name)}</code>
110
+ <span class="meta">[{_html_escape(kind)}] · score={score:.4f}</span>
111
+ </div>
112
+ <div class="location">in {_html_escape(location)}</div>
113
+ <details class="doc">
114
+ <summary>{_html_escape(summary or "(no docstring)")}</summary>
115
+ <pre>{_html_escape(doc)}</pre>
116
+ </details>
117
+ </div>
118
+ """
119
+ rows.append(block)
120
+
121
+ style = """
122
+ <style>
123
+ .result-card {border: 1px solid rgba(0,0,0,.08); padding: 12px 14px; border-radius: 12px; margin-bottom: 12px;}
124
+ .header {display:flex; gap:10px; align-items:center; flex-wrap:wrap;}
125
+ .rank {font-weight: 700;}
126
+ .name {font-size: 0.95rem; background: rgba(0,0,0,.03); padding: 2px 6px; border-radius: 6px;}
127
+ .meta {opacity: 0.7;}
128
+ .location {font-size: 0.9rem; opacity: 0.8; margin: 4px 0 8px;}
129
+ details.doc summary {cursor: pointer; font-weight: 500; margin-bottom: 6px;}
130
+ details.doc pre {white-space: pre-wrap; background: rgba(0,0,0,.02); padding: 10px; border-radius: 8px;}
131
+ </style>
132
+ """
133
+ return style + "\n".join(rows)
134
+
135
+ # -----------------------------
136
+ # Gradio app
137
+ # -----------------------------
138
+ DEFAULT_SERVER = os.environ.get("COSIM_SERVER_URL", "https://theostos-llm4docq-cosim.hf.space")
139
+
140
+ def search(
141
+ query: str,
142
+ top_k: int,
143
+ server_url: str,
144
+ show_raw: bool,
145
+ ) -> List[Any]:
146
+ query = (query or "").strip()
147
+ if not query:
148
+ return [gr.update(value="<div>Please enter a query.</div>"), None]
149
+
150
+ try:
151
+ embedder = get_embedder()
152
+ with torch.inference_mode():
153
+ emb = embedder.generate(query, is_query=True)
154
+ # Convert to plain list[float]
155
+ emb_list = emb[0].detach().to(torch.float32).cpu().tolist()
156
+
157
+ items = call_retrieval_service(server_url, emb_list, top_k)
158
+ html = render_results(items)
159
+
160
+ if show_raw:
161
+ return [html, items]
162
+ else:
163
+ return [html, None]
164
+ except requests.exceptions.RequestException as e:
165
+ msg = f"<div style='color:#b00020'>Request error: {_html_escape(str(e))}</div>"
166
+ return [msg, None]
167
+ except RuntimeError as e:
168
+ # Often OOM or dtype issues
169
+ tip = " (Try CPU / smaller model size.)"
170
+ msg = f"<div style='color:#b00020'>Runtime error: {_html_escape(str(e))}{_html_escape(tip)}</div>"
171
+ return [msg, None]
172
+ except Exception as e:
173
+ msg = f"<div style='color:#b00020'>Unexpected error: {_html_escape(str(e))}</div>"
174
+ return [msg, None]
175
+
176
+ with gr.Blocks(title="MathComp Retrieval (Qwen3 Embedding → Cosim)", theme=gr.themes.Soft()) as demo:
177
+ gr.Markdown(
178
+ """
179
+ # 🔎 MathComp Retrieval
180
+ Embed your natural-language query with **Qwen3-Embedding** and fetch nearest MathComp items from your retrieval server.
181
+ """
182
+ )
183
+ with gr.Row():
184
+ with gr.Column(scale=3):
185
+ query = gr.Textbox(
186
+ label="Query",
187
+ placeholder="e.g., reasoning about commutative group morphisms",
188
+ lines=3,
189
+ autofocus=True,
190
+ )
191
+ with gr.Row():
192
+ top_k = gr.Slider(1, 50, value=5, step=1, label="top_k")
193
+ with gr.Accordion("Advanced", open=False):
194
+ server_url = gr.Textbox(value=DEFAULT_SERVER, label="Retrieval server URL")
195
+ show_raw = gr.Checkbox(value=False, label="Also show raw JSON response")
196
+ with gr.Row():
197
+ run_btn = gr.Button("Search", variant="primary")
198
+ clear_btn = gr.Button("Clear")
199
+
200
+ with gr.Column(scale=4):
201
+ pretty = gr.HTML(label="Results")
202
+ raw_json = gr.JSON(label="Raw JSON", visible=False)
203
+
204
+ def on_toggle_raw(show: bool):
205
+ return gr.update(visible=show)
206
+
207
+ show_raw.change(fn=on_toggle_raw, inputs=show_raw, outputs=raw_json)
208
+ run_btn.click(
209
+ fn=search,
210
+ inputs=[query, top_k, server_url, show_raw],
211
+ outputs=[pretty, raw_json],
212
+ api_name="search",
213
+ )
214
+ clear_btn.click(lambda: ("", 5, "0.6B", True, DEFAULT_SERVER, False, "<div/>", None),
215
+ inputs=None,
216
+ outputs=[query, top_k, server_url, show_raw, pretty, raw_json])
217
+
218
+ gr.Examples(
219
+ examples=[
220
+ ["polynomial division lemma for ringType"],
221
+ ["matrix rank properties over finite fields"],
222
+ ["group homomorphism kernel characterization"],
223
+ ["bigop lemmas about summation reindexing"],
224
+ ],
225
+ inputs=[query],
226
+ label="Try these",
227
+ )
228
+
229
+ if __name__ == "__main__":
230
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.38.0
2
+ transformers>=4.41.0
3
+ torch>=2.3.0
4
+ accelerate>=0.30.0
5
+ requests>=2.31.0