RysoAI commited on
Commit
46bee4a
·
verified ·
1 Parent(s): b5b09c0

RysoAI TinyQA-1 Moss: initial release

Browse files
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. LICENSE +202 -0
  3. NOTICE.md +20 -0
  4. README.md +195 -0
  5. SHA256SUMS +48 -0
  6. code/gse_mini/__init__.py +1 -0
  7. code/gse_mini/answer.py +263 -0
  8. code/gse_mini/dense.py +31 -0
  9. code/gse_mini/extract.py +102 -0
  10. code/gse_mini/ingest/__init__.py +1 -0
  11. code/gse_mini/ingest/text.py +45 -0
  12. code/gse_mini/ingest/zim.py +91 -0
  13. code/gse_mini/planner.py +167 -0
  14. code/gse_mini/prompt.py +60 -0
  15. code/gse_mini/reader.py +44 -0
  16. code/gse_mini/render.py +67 -0
  17. code/gse_mini/rerank.py +66 -0
  18. code/gse_mini/retrieve.py +429 -0
  19. code/gse_mini/serve.py +37 -0
  20. code/gse_mini/store.py +378 -0
  21. code/gse_mini/verify.py +65 -0
  22. code/local/bench_web.py +108 -0
  23. code/local/experiments/doors.py +268 -0
  24. code/local/experiments/sieve.py +91 -0
  25. code/local/regrade.py +55 -0
  26. code/local/webqa.py +603 -0
  27. code/local/webqa_server.py +54 -0
  28. code/local/webui/index.html +177 -0
  29. gguf/gse-planner-120m-v2-Q8_0.gguf +3 -0
  30. gguf/gse-sft-120m-Q8_0.gguf +3 -0
  31. gguf/gse-verbaliser-120m-short-Q8_0.gguf +3 -0
  32. models/gse-ranker/config.json +37 -0
  33. models/gse-ranker/model.safetensors +3 -0
  34. models/gse-ranker/ranker_meta.json +1 -0
  35. models/gse-ranker/tokenizer.json +0 -0
  36. models/gse-ranker/tokenizer_config.json +18 -0
  37. models/gse-verifier-v4-33m/config.json +32 -0
  38. models/gse-verifier-v4-33m/model.safetensors +3 -0
  39. models/gse-verifier-v4-33m/special_tokens_map.json +37 -0
  40. models/gse-verifier-v4-33m/tokenizer.json +0 -0
  41. models/gse-verifier-v4-33m/tokenizer_config.json +58 -0
  42. models/gse-verifier-v4-33m/verifier_meta.json +38 -0
  43. models/gse-verifier-v4-33m/vocab.txt +0 -0
  44. moss.sh +56 -0
  45. requirements.txt +9 -0
  46. results/freshqa_600_serper_summary.json +56 -0
  47. results/popqa_1000_serper_summary.json +116 -0
  48. results/repro.json +70 -0
  49. results/simpleqa_1000_ddgs_summary.json +91 -0
  50. results/simpleqa_1000_serper_summary.json +91 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ gguf/gse-planner-120m-v2-Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
37
+ gguf/gse-sft-120m-Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
38
+ gguf/gse-verbaliser-120m-short-Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
NOTICE.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Notices
2
+
3
+ RysoAI TinyQA-1 Moss code and the weights in `models/` and `gguf/` are released under the Apache License 2.0 (see `LICENSE`).
4
+
5
+ ## Components
6
+
7
+ | component | file | license |
8
+ |---|---|---|
9
+ | Ranker, 22M | `models/gse-ranker` | Apache-2.0; fine-tuned from `cross-encoder/ms-marco-MiniLM-L6-v2` (Apache-2.0) |
10
+ | Verifier, 33M | `models/gse-verifier-v4-33m` | Apache-2.0; fine-tuned from `cross-encoder/ms-marco-MiniLM-L12-v2` (Apache-2.0) |
11
+ | Verbaliser, glue decoder, planner, 113M each | `gguf/` | Apache-2.0 |
12
+ | Reader, 33M | not included; downloaded at run time | `deepset/minilm-uncased-squad2`, CC-BY-4.0 |
13
+ | Entailment scorer, 22M (paragraph mode only) | not included; downloaded on first use | `cross-encoder/nli-deberta-v3-xsmall`, Apache-2.0 |
14
+
15
+ ## Attributions
16
+
17
+ - Reader: deepset, *minilm-uncased-squad2*, https://huggingface.co/deepset/minilm-uncased-squad2, CC-BY-4.0.
18
+ - Cross-encoder bases: *ms-marco-MiniLM-L6-v2* and *ms-marco-MiniLM-L12-v2*, https://huggingface.co/cross-encoder, Apache-2.0.
19
+ - Tokenizer of the 113M models: derived from the SmolLM2 vocabulary (Hugging Face, Apache-2.0).
20
+ - Pretraining text of the 113M models: FineWeb-Edu (Hugging Face), ODC-By 1.0.
README.md ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ library_name: sentence-transformers
6
+ pipeline_tag: question-answering
7
+ tags:
8
+ - question-answering
9
+ - retrieval
10
+ - cross-encoder
11
+ - verification
12
+ - citations
13
+ - edge
14
+ - cpu
15
+ - offline
16
+ base_model:
17
+ - cross-encoder/ms-marco-MiniLM-L6-v2
18
+ - cross-encoder/ms-marco-MiniLM-L12-v2
19
+ model-index:
20
+ - name: RysoAI TinyQA-1 Moss
21
+ results:
22
+ - task: {type: question-answering, name: Open-book question answering}
23
+ dataset: {type: google/simpleqa-verified, name: SimpleQA Verified, split: eval}
24
+ metrics:
25
+ - {type: f1, value: 77.1, name: F-score (open-book, DuckDuckGo)}
26
+ - {type: accuracy, value: 71.3, name: Correct (open-book, DuckDuckGo)}
27
+ ---
28
+
29
+ # RysoAI TinyQA-1 Moss
30
+
31
+ **A tiny but powerful 89M-parameter question-answering model.**
32
+
33
+ Moss is a retrieval question-answering system built to be as small as possible while still answering at a high standard.
34
+ It reads search results or a local collection of documents, selects the text that states the answer, checks and verifies
35
+ it, and returns the exact quote, the short answer and its source in a readable format. Every answer carries its
36
+ verification result, so an unverified answer is always clearly marked.
37
+
38
+ ## 1. General information
39
+
40
+ Moss can be used anywhere a question needs a sourced answer. It was initially designed for two settings:
41
+
42
+ - **Minimal hardware.** Small enough for single-board computers and other constrained devices, with very little
43
+ inference cost. It can run fully offline against a local corpus, or over an intranet, where a large language model
44
+ is not practical.
45
+ - **Retrieval at scale.** At about a quarter of a second of compute per question on a laptop CPU, Moss can gather and
46
+ verify large volumes of facts cheaply. We use it to collect millions of data points of evidence for our larger
47
+ forecasting models, which we benchmark publicly on ForecastBench ([ryso.ai](https://ryso.ai)).
48
+
49
+ It also works well alongside larger models: Moss gathers and verifies information with almost no inference, and the
50
+ sourced results can be passed to a large language model to reason over.
51
+
52
+ | | |
53
+ |---|---|
54
+ | Model provider | RysoAI |
55
+ | Release date | November 2026 |
56
+ | Languages | English |
57
+ | License | Apache 2.0 |
58
+
59
+ ## 2. Getting started
60
+
61
+ ```bash
62
+ ./moss.sh setup # Python 3.11 environment with pinned dependencies
63
+ ./moss.sh start # local web interface at http://127.0.0.1:8091
64
+ ./moss.sh ask "Who designed the Missouri Centennial half dollar?"
65
+ ```
66
+
67
+ ```
68
+ The Missouri Centennial half dollar was designed by Robert Aitken, who is best known for designing the Panama Pacific Exposition fifty dollar gold commemoratives.
69
+ “The coin was designed by Robert Aitken, who is best known for designing the Panama Pacific Exposition fifty dollar gold commemoratives.” (stated by 3 sources)
70
+ https://www.your-rare-coin-collecting-guide.com/missouri-centennial.html
71
+ ```
72
+
73
+ **Local documents.** Index any folder of `.txt` or `.md` files, or a `.jsonl` file of `{"title", "text"}` records, and
74
+ ask questions with no network connection:
75
+
76
+ ```bash
77
+ ./moss.sh index ~/Documents/field-manuals
78
+ ./moss.sh start
79
+ ./moss.sh ask --local "How long should water be boiled to make it safe?"
80
+ ```
81
+
82
+ **Search.** Web search uses DuckDuckGo by default and needs no key. Add `SERPER_API_KEY=...` to a `.env` file beside
83
+ `moss.sh` to use Google results and verifier-gated retries.
84
+
85
+ **Answer line.** Install [llama.cpp](https://github.com/ggml-org/llama.cpp) (`brew install llama.cpp`) and the 113M
86
+ models write a one-sentence answer around the verified quote. Without it, a template is used. The quote is always shown.
87
+
88
+ ## 3. Model properties
89
+
90
+ **Architecture.** A pipeline of small transformer encoders, each with one job, plus optional 113M decoders for the
91
+ written answer line.
92
+
93
+ | component | role | parameters | file |
94
+ |---|---|---|---|
95
+ | Ranker | orders candidate sentences by relevance to the question | 22M | `models/gse-ranker` |
96
+ | Verifier | scores whether a sentence states the answer; this score is the confidence | 33M | `models/gse-verifier-v4-33m` |
97
+ | Reader | marks the exact answer span inside the chosen sentence | 33M | `deepset/minilm-uncased-squad2`, fetched at run time |
98
+ | Verbaliser (optional) | writes the answer line using only words already on the page | 113M | `gguf/gse-verbaliser-120m-short-Q8_0.gguf` |
99
+ | Glue decoder (optional) | fallback answer-line writer | 113M | `gguf/gse-sft-120m-Q8_0.gguf` |
100
+ | Planner (optional) | rewrites queries for retries and supplies answer frames | 113M | `gguf/gse-planner-120m-v2-Q8_0.gguf` |
101
+
102
+ **Parameters.** 89M for the core answering path (ranker, verifier, reader), 429M with all three optional decoders.
103
+
104
+ **Input.** A natural-language question in English.
105
+
106
+ **Output.** One verified sentence quoted verbatim from a source, the short answer span within it, the source link, a
107
+ verified or not-verified flag, and the number of independent sources that agree. Optionally, a one-line written answer.
108
+
109
+ **Verification.** An answer is marked verified when the verifier scores it at 1.5 or above, or when three independent
110
+ sources state the same short answer and the verifier does not score against it. Unverified results are labelled as such
111
+ and never presented as the answer.
112
+
113
+ **Hardware.** CPU only; no GPU needed. The core encoders take about 360 MB in fp32, and each optional decoder is 117 MB at
114
+ Q8. Search time dominates latency on the web; with a local corpus, a full answer takes a few hundred milliseconds.
115
+
116
+ ## 4. Training
117
+
118
+ The ranker and verifier are fine-tuned from public MS MARCO cross-encoders. The 113M decoders were pretrained from
119
+ scratch on public educational web text and then fine-tuned. Training data was drawn from publicly available sources and
120
+ synthetically generated, then filtered and deduplicated.
121
+
122
+ No benchmark questions were used in training. The verifier's training questions also exclude every subject that appears
123
+ in the benchmarks, and websites that host the benchmarks are excluded as sources at answer time.
124
+
125
+ ## 5. Evaluations
126
+
127
+ All results use the official SimpleQA grader prompt with `gpt-4.1-2025-04-14` on the full benchmark sets.
128
+
129
+ **Moss is evaluated open-book.** It answers from retrieved text, exactly as it runs in use. The frontier models it is
130
+ compared with below are evaluated **closed-book**, answering from memory alone. The comparison shows what a very small
131
+ retrieval system can reach against much larger models; it is not a like-for-like test of the same setting.
132
+
133
+ ### SimpleQA Verified (1,000 questions)
134
+
135
+ | system | setting | parameters | score |
136
+ |---|---|---|---|
137
+ | Gemini 3.1 Pro Preview | closed-book | undisclosed | 77.5 |
138
+ | **RysoAI TinyQA-1 Moss** (F-score) | **open-book, DuckDuckGo** | **89M** | **77.1** |
139
+ | GPT-6 Astra | closed-book | undisclosed | 75.8 |
140
+ | Gemini 4 Argon | closed-book | undisclosed | 75.6 |
141
+ | Gemini 3.8 Flash | closed-book | undisclosed | 74.6 |
142
+ | **RysoAI TinyQA-1 Moss** (F-score) | **open-book, Google** | **89M** | **74.0** |
143
+ | GPT-6.1 Sol | closed-book | undisclosed | 73.8 |
144
+ | Gemini 3 Pro Preview | closed-book | undisclosed | 72.1 |
145
+ | GPT-5.6 Sol | closed-book | undisclosed | 69.2 |
146
+ | Claude Opus 5 | closed-book | undisclosed | 63.3 |
147
+ | Claude Opus 4.6 | closed-book | undisclosed | 45.2 |
148
+
149
+ Closed-book scores are from the public [SimpleQA Verified leaderboard](https://www.kaggle.com/benchmarks/deepmind/simpleqa-verified)
150
+ (snapshot of 19 November 2026). The leaderboard reports a single score; the benchmark paper's headline metric is F-score.
151
+
152
+ ### Detailed results
153
+
154
+ | benchmark | search | correct | incorrect | not attempted | precision when answering | F-score |
155
+ |---|---|---|---|---|---|---|
156
+ | SimpleQA Verified | DuckDuckGo | 71.3 | 13.7 | 15.0 | 83.9 | 77.1 |
157
+ | SimpleQA Verified, verified answers only | DuckDuckGo | 60.9 | 6.2 | 32.9 | **90.8** | 72.9 |
158
+ | SimpleQA Verified | Google | 69.6 | 18.6 | 11.8 | 78.9 | 74.0 |
159
+ | SimpleQA Verified, verified answers only | Google | 59.2 | 7.5 | 33.3 | 88.8 | 71.0 |
160
+ | PopQA, 1,000 least-popular subjects | Google | 47.4 | 48.5 | 4.1 | 49.4 | 48.4 |
161
+ | PopQA, verified answers only | Google | 42.1 | 23.6 | 34.3 | 64.1 | 50.8 |
162
+ | FreshQA, 600 | Google | 39.5 | 52.3 | 8.2 | 43.0 | 41.2 |
163
+ | FreshQA, verified answers only | Google | 30.8 | 20.2 | 49.0 | 60.5 | 40.8 |
164
+
165
+ "Verified answers only" counts every answer Moss does not verify as not attempted. That is how Moss behaves when told to
166
+ answer only when sure. The graded answer is the short answer followed by the quoted sentence, as Moss displays it. FreshQA
167
+ gold answers date from August 2025, so its fast-changing questions are partly out of date against the live web.
168
+
169
+ Summaries of every graded run are in `results/`.
170
+
171
+ ## 6. Limitations
172
+
173
+ - Moss answers questions whose answer is stated in a single sentence of the retrieved text. Questions that need
174
+ arithmetic, comparison or combining facts from several sources are outside its scope.
175
+ - Its accuracy follows the quality of what it retrieves. A verified quote reflects what the source says.
176
+ - Results above are for web search, where engines return passages already focused on the question. Local collections
177
+ are searched with a built-in keyword index.
178
+ - English only.
179
+
180
+ ## 7. License
181
+
182
+ Code and weights in this repository are released under the Apache 2.0 license. The reader model,
183
+ [deepset/minilm-uncased-squad2](https://huggingface.co/deepset/minilm-uncased-squad2), is licensed CC-BY-4.0 and is
184
+ downloaded from its own repository at run time. See `NOTICE.md` for full attributions.
185
+
186
+ ## Citation
187
+
188
+ ```bibtex
189
+ @misc{ryso_tinyqa1_moss_2026,
190
+ title = {RysoAI TinyQA-1 Moss},
191
+ author = {{RysoAI}},
192
+ year = {2026},
193
+ url = {https://ryso.ai}
194
+ }
195
+ ```
SHA256SUMS ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./LICENSE
2
+ d3ef4e0e429b8ac9a768d42f260d0efdf4cf1c7685c83932f598f07e7418de27 ./NOTICE.md
3
+ 764449a72b93e4968777363e5f41489e1b7bab2a7febeac57870af9023c01549 ./README.md
4
+ 24803f77e64d9450d9fb9908e93b729a4e0b3846271c7b3b0a003eb14ad20663 ./code/gse_mini/__init__.py
5
+ fa7fd1f30076205c9ed9d6cc959a6e0b661d1bd8f8f85876663d027fa78cb6c5 ./code/gse_mini/answer.py
6
+ 3acb6af87f7357c6d606cbcefeca6d84f125270e274aa994ccbb22eeaee2342f ./code/gse_mini/dense.py
7
+ cdfb9d36527e22b26cab315099f1a165d4fd5a4951f60ff532e5f6bb1dd894e8 ./code/gse_mini/extract.py
8
+ 6118a6216d198f232854b83df4843c0c4e4ade395e8da4b39bef3825a139423e ./code/gse_mini/ingest/__init__.py
9
+ 1c5047e2e8fb27b56b0090113065a1ff688feb345cd9a15a83ff841146b12974 ./code/gse_mini/ingest/text.py
10
+ 9027cd3a14c7826d5524b52e9154a94f54e3d66de110672676f0f20dc9408299 ./code/gse_mini/ingest/zim.py
11
+ 98d61f2c50bdda6b6d9b4b3a46332a8ee1587b847568488a4f798e6e62435c39 ./code/gse_mini/planner.py
12
+ b735dd50e07f0af716d085a7c954be62311cbc2201e0162d0b5f7301cbe4021c ./code/gse_mini/prompt.py
13
+ 5c590fd9c2d2cedb2766d318dfe825ec9b56c9c342627600196b556986e12552 ./code/gse_mini/reader.py
14
+ 7a67c8139087be6c556821bba86d151ac98f674e3cf0a0ff0302c3e9d78c5875 ./code/gse_mini/render.py
15
+ 296dc8c42f030ae43a93db1eef18ab05c4982ba478192b7c6147278fa8ca1b91 ./code/gse_mini/rerank.py
16
+ 1e7dcffcb6d0bff159f4b1921b33c2206d7482601e3eece534699c441edd8946 ./code/gse_mini/retrieve.py
17
+ 5094cce7f46298daadc32e0658305309a523534ba71e6aafb957f3f0d7f450cf ./code/gse_mini/serve.py
18
+ 623dee5b1fa5ce91b6ad33d2b7a1773fec08fed1079b22b54c7a03872e7e2752 ./code/gse_mini/store.py
19
+ f07558ebcc0f3b1a55fe82810cb651b6ef3dd93043160a377a18984b8bc3bcec ./code/gse_mini/verify.py
20
+ a29678791b6b45f2a0fb6c81bb185cfa17292de1c434360b936bb76ad5e8d194 ./code/local/bench_web.py
21
+ 40645317b8164be7cfde131a578cf52dfb7e449106417d77aae23bc5f19dfc2e ./code/local/experiments/doors.py
22
+ c831fcf7c72aeb837a2d8d0a5958a2068c115b76c973a0876e12eee70ba9bb07 ./code/local/experiments/sieve.py
23
+ ad1fd84941ed0f772077a450e548741da4837449c3000fd48d8fcdaab93582cd ./code/local/regrade.py
24
+ 7e2de6af191529298c3907703e36176f9773c65559a0ecbc5a81d5baf5ce0857 ./code/local/webqa.py
25
+ 1e202a8f9750e3387eaf2524e0cd78081fdd97cdbcd5cdf882d68625c209470a ./code/local/webqa_server.py
26
+ 6c78d4fc99b0788470f4f9d56c6eedb16a69ce393eeb525b5b04050328fda8a6 ./code/local/webui/index.html
27
+ 92d4c498657415ea67883dba13d3221123b16fd330930dc1989c94339a87fcb7 ./gguf/gse-planner-120m-v2-Q8_0.gguf
28
+ cb0196c2904ad648d3397397b6515767c10d13a48764de8b93804a2cbf54b688 ./gguf/gse-sft-120m-Q8_0.gguf
29
+ e7665ef5997222de701c43360dbd89ca3f62af100cf95badfb56c2ed691347b1 ./gguf/gse-verbaliser-120m-short-Q8_0.gguf
30
+ 1890f7157c851bfea48ea028bb61d035a3f0909373a74795bc71b1e720ceccc6 ./models/gse-ranker/config.json
31
+ 7dde2650d4e130fa5681e2537fc1875a83971f4f28a346b7ceb26ae1a8758f30 ./models/gse-ranker/model.safetensors
32
+ 9d4edd1d931b6d3e8b59a561202f08aa068dacfaf9340236f3c5a3c6f1c28220 ./models/gse-ranker/ranker_meta.json
33
+ 851ca67100d372ca3ae031a6abd168f53489eebfd7d89523f35c5c9b4d372c3c ./models/gse-ranker/tokenizer.json
34
+ 649e41f8cf1cb1b67acc193795ccaef07bcaa3c4e0fc7d286ba8255fab79cffa ./models/gse-ranker/tokenizer_config.json
35
+ e4288df3d671124dd6d41ee93e147b4fb268cdd2b72df1a6e369239488edd2ec ./models/gse-verifier-v4-33m/config.json
36
+ 14f34669c51af8f27ea206b29d5bb0de45e2b69030db0927bb41e8f9cb632b2d ./models/gse-verifier-v4-33m/model.safetensors
37
+ 5d5b662e421ea9fac075174bb0688ee0d9431699900b90662acd44b2a350503a ./models/gse-verifier-v4-33m/special_tokens_map.json
38
+ 851ca67100d372ca3ae031a6abd168f53489eebfd7d89523f35c5c9b4d372c3c ./models/gse-verifier-v4-33m/tokenizer.json
39
+ 7b082b48a08a0b5c5939d99472e33addce3d96202155e33f7928cecd171186a0 ./models/gse-verifier-v4-33m/tokenizer_config.json
40
+ 060042f8f498f6039fc05a5771607a91d9d959dc7874f1a37cec806fb4ea21be ./models/gse-verifier-v4-33m/verifier_meta.json
41
+ 07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3 ./models/gse-verifier-v4-33m/vocab.txt
42
+ 8270be2810f799adf33b96642d58240ea086d10174e383461b3f71bec239fef8 ./moss.sh
43
+ d02efcc9918800b351ab5a719ebe0d045688c24e5ffa2ff2731c8ce8f1ab63ce ./requirements.txt
44
+ 16095ae79e1a75787c2e673a9c4f39a76a77aba0eb7af9faad3252a7aefb8f8f ./results/freshqa_600_serper_summary.json
45
+ 74a4fefd1e361e24f32c84e1f47e9ba429b18248b42402fa39e6f16647655ba7 ./results/popqa_1000_serper_summary.json
46
+ 4221c9e3e20152b5a7b978ba8b3f7db9ed8e59122eec01ef371fd8f235872654 ./results/repro.json
47
+ 1ca547aeff5e8188e40dc7051064968bc2f411d8361427be2a43cd02afbd50a9 ./results/simpleqa_1000_ddgs_summary.json
48
+ 9675ed2d23bd2a48e19635f2cbb82a1faaa36a3de6e244a7960682187f815139 ./results/simpleqa_1000_serper_summary.json
code/gse_mini/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """GSE-mini: quote-first retrieval harness. Corpus-agnostic; see GSE-DESIGN.md §14."""
code/gse_mini/answer.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end GSE-mini runtime: question -> retrieve -> constrained generation (llama.cpp server) -> verify -> render.
2
+
3
+ python -m gse_mini.answer --store /root/data/store.sqlite --server http://127.0.0.1:8080 "Who was the fourth king of Thailand?"
4
+ Start the server first, e.g.:
5
+ /root/llama.cpp/build/bin/llama-server -m /root/models/gguf/gse-sft-120m-Q8_0.gguf -c 2048 --port 8080 -ngl 99
6
+ """
7
+ from __future__ import annotations
8
+ import argparse, json, os, re, sys, time, urllib.request
9
+ from .store import Store
10
+ from .retrieve import retrieve
11
+ from .prompt import build_prompt, gbnf, parse_answer, EOS_ANSWER
12
+ from .verify import check
13
+ from .render import render
14
+
15
+ def generate(server: str, prompt: str, grammar: str, max_tokens: int = 80) -> str:
16
+ body = json.dumps({"prompt": prompt, "n_predict": max_tokens, "temperature": 0.0, "grammar": grammar,
17
+ "stop": [EOS_ANSWER], "cache_prompt": True}).encode()
18
+ req = urllib.request.Request(f"{server}/completion", data=body, headers={"Content-Type": "application/json"})
19
+ for attempt in range(2):
20
+ try:
21
+ with urllib.request.urlopen(req, timeout=60) as r:
22
+ return json.loads(r.read())["content"]
23
+ except Exception:
24
+ if attempt == 1:
25
+ return "" # decoder unavailable or slow: treated as an abstention; the rankers/reader still decide
26
+ time.sleep(1.0)
27
+
28
+ TAU_HI = float(os.environ.get("GSE_TAU_HI", "2.0")) # ranker top score above which E1 is trusted (grammar restricts refs to E1)
29
+ TAU_LO = float(os.environ.get("GSE_TAU_LO", "-6.0")) # ranker top score below which we abstain without calling the decoder
30
+ MARGIN = float(os.environ.get("GSE_MARGIN", "4.0")) # top-minus-second gap that also earns trust (answerable p25 = 5.2, unanswerable p90 = 3.7)
31
+ TAU2 = float(os.environ.get("GSE_TAU2", "5.0")) # second ranker's score the agreed-on top sentence must reach to be called verified
32
+ VERIFY = os.environ.get("GSE_VERIFY", "agree") # "agree": two-ranker agreement; "v2": the answer-bearing ranker picks and verifies (§15.9 step 2)
33
+ TAU_V = float(os.environ.get("GSE_TAU_V", "0.0")) # v2 logit the cited sentence must reach to be called verified (calibrated on synthetic data only)
34
+ TAU_V_LO = float(os.environ.get("GSE_TAU_V_LO", "-3.0")) # v2 logit below which the candidate is not even shown as a best match
35
+
36
+ def _fold(x: str) -> str:
37
+ import unicodedata
38
+ return "".join(c for c in unicodedata.normalize("NFKD", x.lower()) if not unicodedata.combining(c))
39
+
40
+ _NAME = re.compile(r"\b[A-Z][\w'’-]+(?:\s+[A-Z][\w'’-]+)*")
41
+ _YESNO = re.compile(r"^(?:did|does|do|is|are|was|were|has|have|had|can|could|will|would|should|shall)\b", re.I)
42
+ _NEG = re.compile(r"\b(?:not|never|no|none|neither|nor|without|cannot)\b|n't\b", re.I)
43
+ SHORT_ON_BEST = os.environ.get("GSE_SHORT_ON_BEST") == "1" # default: a bold short answer only on verified answers; a best match shows the passage
44
+ _NUMBER = re.compile(r"\d[\d,.]*")
45
+
46
+ def _answer_content(e, question: str) -> set:
47
+ """Entities and numbers a sentence (plus its bridges) contributes beyond the question's own words."""
48
+ import unicodedata
49
+ fold = lambda x: "".join(c for c in unicodedata.normalize("NFKD", x.lower()) if not unicodedata.combining(c))
50
+ qtoks = set(re.findall(r"[a-z0-9]+", fold(question)))
51
+ text = e.text + " " + e.hop_text()
52
+ out = set()
53
+ for m in _NAME.findall(text):
54
+ toks = [t for t in re.findall(r"[a-z0-9]+", fold(m)) if t not in qtoks and len(t) > 2]
55
+ if toks:
56
+ out.add(" ".join(toks))
57
+ for n in _NUMBER.findall(text):
58
+ n = n.strip(".,")
59
+ if n and n not in qtoks and len(n) >= 2:
60
+ out.add(n)
61
+ return out
62
+
63
+ def answer(store: Store, server: str, question: str, n_sentences: int = 16) -> dict:
64
+ """Tiered answer (design §3.1): ranker confidence decides how much freedom the decoder gets."""
65
+ t0 = time.time()
66
+ from .planner import plan as make_plan, PLANNER, PLANNER_KIND
67
+ from .retrieve import retrieve_planned
68
+ p = make_plan(question) if PLANNER else None
69
+ # the 8B teacher's answerability call is reliable; a 113M planner's is not (22% of real factual questions marked
70
+ # unanswerable by planner v2), so for the own planner it is advisory only and retrieval + verification decide
71
+ trust_answerable = PLANNER_KIND != "own" or os.environ.get("GSE_TRUST_ANSWERABLE") == "1"
72
+ if p and "error" not in p and p.get("answerable") is False and trust_answerable:
73
+ reason = (p.get("reason") or "not a factual question").strip()
74
+ return {"text": f"Not something the library can answer ({reason}).", "ok": True, "abstained": True, "tier": 3, "planner": p,
75
+ "ms_retrieve": round(1000*(time.time()-t0)), "ms_generate": 0}
76
+ if p and "error" not in p:
77
+ ev, info = retrieve_planned(store, question, p, n_sentences=n_sentences)
78
+ else:
79
+ ev, info = retrieve(store, question, n_sentences=n_sentences)
80
+ if p: info["planner_error"] = p["error"]
81
+ t1 = time.time()
82
+ if not ev:
83
+ return {"text": "I could not find anything relevant in the library.", "ok": False, "abstained": True, "tier": 3, "ms_retrieve": round(1000*(t1-t0)), "ms_generate": 0}
84
+ top = ev[0].score if ev[0].score is not None else 0.0
85
+ ranked = all(e.score is not None for e in ev) and top > -90 # scores are ranker logits when the reranker ran
86
+ from .reader import reads_as_answer, READER
87
+ from .verify import coverage
88
+ def _excerpt(e): # the reader must know what article a sentence comes from: "he served as..." is about the article's subject
89
+ return f"{e.title}: {e.text}" + "".join(f" | {bt}: {bx}" for _, bt, bx in e.bridges)
90
+ def _reader_pick(cands):
91
+ """First candidate the reader confirms that also covers the question's hard constraints; None if none."""
92
+ for e in cands:
93
+ r_ = reads_as_answer(question, _excerpt(e))
94
+ if r_ is None:
95
+ return None
96
+ if r_ and not coverage(question, e, store, synonyms=info.get("plan", ([], {}))[1], required=info.get("required"), hard=info.get("hard")):
97
+ return e
98
+ return None
99
+ read = None
100
+ from .extract import extract as _extract
101
+ from .reader import yes_no as _yes_no
102
+ def _short(cands, atype):
103
+ """Short answer for entity/date/number questions: a copied span; yes/no questions: the reader's verdict."""
104
+ if atype == "yes_no":
105
+ yn = _yes_no(question, _excerpt(cands[0])) if READER and cands else None
106
+ if yn in ("yes", "no"):
107
+ return {"answer": yn.capitalize(), "kind": "yes_no"}
108
+ # no reader on the small stack: a verified sentence that states the fact without negation answers "Yes";
109
+ # polarity is never guessed from a negated or unverified sentence
110
+ if cands and getattr(_short, "verified", False) and not _NEG.search(cands[0].text):
111
+ return {"answer": "Yes", "kind": "yes_no"}
112
+ return None
113
+ if atype in ("definition", "howto"):
114
+ return None
115
+ # the short answer must come from what is actually cited (first candidate(s)); other top candidates only
116
+ # contribute VOTES, never the displayed span
117
+ n_cited = max(1, getattr(_short, "n_cited", 1))
118
+ r_ = _extract(question, [(_excerpt(e), e.tag) for e in cands[:n_cited]], answer_type=atype)
119
+ if r_ and r_["answer"].lower() not in ("he", "she", "it", "they", "him", "her", "them"):
120
+ others = _extract(question, [(_excerpt(e), e.tag) for e in cands[n_cited:n_cited + 3]], answer_type=atype) if len(cands) > n_cited else None
121
+ from .extract import normalize as _norm
122
+ votes = r_["votes"] + (1 if others and _norm(others["answer"]) == _norm(r_["answer"]) else 0)
123
+ return {"answer": r_["answer"], "score": r_["score"], "votes": votes, "kind": "span"}
124
+ # no span, or a pronoun: an encyclopedia sentence is about its article's subject ("he served as the 45th
125
+ # president" in the article "Donald Trump"); for entity-typed questions the article title is the answer
126
+ from .extract import type_ok
127
+ if atype in ("person", "place", "organization") and cands:
128
+ # meta-articles are about their subject: "Outline of Mars" / "List of X" / "History of X" -> X
129
+ title = re.sub(r"\s*\(.*?\)\s*$", "", cands[0].title)
130
+ title = re.sub(r"^(?:Outline|List|History|Timeline|Geography|Economy|Politics|Demographics|Culture) of (?:the )?", "", title)
131
+ if type_ok(title, atype) and title.lower() not in question.lower():
132
+ return {"answer": title, "kind": "title"}
133
+ return None
134
+ atype = (info.get("planner") or {}).get("answer_type") if isinstance(info.get("planner"), dict) else None
135
+ if _YESNO.match(question.strip()):
136
+ atype = "yes_no" # "Did Nazi Germany ever host the Olympics?" is yes/no whatever a small planner typed it as
137
+ if ranked and top < TAU_LO:
138
+ e_ok = _reader_pick(ev[:3]) if READER else None
139
+ if e_ok is None:
140
+ return {"text": render([], ev, True), "ok": True, "abstained": True, "tier": 3, "top_score": round(top, 2),
141
+ "anchors": info["anchors"], "planner": info.get("planner"), "evidence_texts": [e.text for e in ev], "cited_texts": [], "evidence_ids": [e.sent_id for e in ev], "cited_ids": [], "pool_sids": info.get("pool_sids", []),
142
+ "ms_retrieve": round(1000*(t1-t0)), "ms_generate": 0}
143
+ # the rankers gave up but the reader confirms a covering candidate: cite it as reader-verified
144
+ parts, abst, tier, read, raw, v = [("ref", e_ok.tag)], False, 1, True, "", {"ok": True, "problems": [], "refs": [e_ok.tag]}
145
+ second = margin = -99.0; s2 = None; agree = False; score2 = None; uncovered = []
146
+ t2 = time.time()
147
+ by_tag = {e.tag: e for e in ev}
148
+ label = "Answer (reader-verified):\n"
149
+ _short.n_cited = 1
150
+ sa = _short([e_ok] + [e for e in ev[:3] if e is not e_ok], atype)
151
+ return {"text": label + render(parts, ev, abst, short=sa["answer"] if sa else None), "short_answer": sa, "raw": raw, "ok": True, "problems": [], "abstained": False, "tier": 1,
152
+ "top_score": round(top, 2), "margin": None, "score2": None, "agree": None, "uncovered": [], "bridged": info.get("bridged", 0),
153
+ "planner": info.get("planner"), "reader": True, "evidence_texts": [e.text for e in ev],
154
+ "cited_texts": [e_ok.text + (" " + e_ok.hop_text() if e_ok.bridges else "")], "evidence_ids": [e.sent_id for e in ev], "cited_ids": [e_ok.sent_id], "pool_sids": info.get("pool_sids", []), "anchors": info["anchors"],
155
+ "ms_retrieve": round(1000*(t1-t0)), "ms_generate": round(1000*(t2-t1))}
156
+ second = ev[1].score if len(ev) > 1 and ev[1].score is not None else -99.0
157
+ margin = top - second
158
+ # trust = two independent rankers agree on the top sentence and the second one is confident; a single model's
159
+ # absolute score is not comparable across question styles, agreement between two models transfers much better
160
+ from .rerank import second_opinion
161
+ s2 = second_opinion(question, ev, top=8) if ranked else None
162
+ best2 = max(range(len(s2)), key=lambda i: s2[i]) if s2 else None
163
+ # agreement is corroboration of the ANSWER, not the exact sentence: the second ranker's favourite is the same
164
+ # sentence, a sentence from the same article, or a sentence naming the same answer content (an entity or a
165
+ # number beyond the question's own words: "Alexander Fleming" in two different articles)
166
+ agree = best2 is not None and (best2 == 0 or (best2 <= 2 and ev[best2].doc_id == ev[0].doc_id)
167
+ or bool(_answer_content(ev[0], question) & _answer_content(ev[best2], question)))
168
+ score2 = s2[0] if s2 else None
169
+ # question terms the top sentence (plus its article lead and any bridge) does not account for: a sentence that is
170
+ # merely *about* the entity ("...plays for Al-Hilal") must not be called a verified answer to "which Midlands club..."
171
+ from .verify import coverage
172
+ uncovered = coverage(question, ev[0], store, synonyms=info.get("plan", ([], {}))[1], required=info.get("required"), hard=info.get("hard")) if ranked else []
173
+ trusted = ranked and not uncovered and ((agree and score2 >= TAU2) or (s2 is None and (top >= TAU_HI or margin >= MARGIN)))
174
+ weak_v2 = None
175
+ if VERIFY == "v2" and s2:
176
+ # Answer-bearing verification: ranker-v2 was trained on judge labels ("does this sentence state the answer?"), so its
177
+ # favourite among the relevance ranker's top 8 becomes the citation, and its logit is the verification. Question-word
178
+ # coverage is no longer the gate (that is what cited the wrong sentence on 28% of real questions); only the planner's
179
+ # hard constraint words must still be covered, so "fifth king" cannot be answered with the fourth.
180
+ words_q = re.findall(r"[A-Za-z0-9][\w'’-]*", question)
181
+ caps_q = {_fold(w) for w in words_q[1:] if w[:1].isupper()}
182
+ from .retrieve import term_weight
183
+ def entity_missing(e_):
184
+ unc = coverage(question, e_, store, synonyms=info.get("plan", ([], {}))[1], required=info.get("required"), hard=info.get("hard"))
185
+ return unc, [t for t in unc if t in caps_q or t in (info.get("hard") or []) or term_weight(store, t) >= 1.0]
186
+ cov = [entity_missing(e_) for e_ in ev[:len(s2)]]
187
+ # "Who starred in Moneyball and Superbad?": a Superbad cast sentence can out-score the Jonah Hill sentence on
188
+ # answer-bearing alone; the pick must also cover the question's entities (itself, its lead, or a hop)
189
+ about = [i_ for i_ in range(len(s2)) if not cov[i_][1] and s2[i_] >= TAU_V_LO]
190
+ pick = max(about, key=lambda i_: s2[i_]) if about else best2
191
+ if pick != 0:
192
+ ev.insert(0, ev.pop(pick)); s2.insert(0, s2.pop(pick)); cov.insert(0, cov.pop(pick))
193
+ for i_, e_ in enumerate(ev):
194
+ e_.tag = f"E{i_+1}"
195
+ score2 = s2[0]; agree = True
196
+ uncovered = cov[0][0]
197
+ hard_missing = [t for t in uncovered if t in (info.get("hard") or [])]
198
+ trusted = ranked and score2 >= TAU_V and not hard_missing
199
+ weak_v2 = score2 < TAU_V_LO
200
+ allowed = [1] if trusted else None
201
+ raw = generate(server, build_prompt(ev, question), gbnf(len(ev), allowed=allowed))
202
+ t2 = time.time()
203
+ parts, abst = parse_answer(raw)
204
+ tier = 1 if allowed else 2
205
+ if allowed and (abst or not any(k == "ref" for k, _ in parts)):
206
+ parts, abst = [("ref", "E1")], False # ranker is confident: quote E1 even if the decoder gave up
207
+ v = check(parts, ev, question) if not abst else {"ok": True, "problems": [], "refs": []}
208
+ if not abst and not v["ok"]:
209
+ if allowed:
210
+ parts, v = [("ref", "E1")], {"ok": True, "problems": v["problems"], "refs": ["E1"]} # drop bad glue, keep the trusted quote
211
+ else:
212
+ abst, parts = True, [] # fail closed: show evidence instead of a bad answer
213
+ weak = bool(uncovered) and (score2 is None or score2 < 3.0) # misses question terms AND fails to convince the second ranker
214
+ if weak_v2 is not None:
215
+ weak = weak_v2
216
+ if abst and ranked and top >= TAU_LO and not weak:
217
+ # middle band: the decoder gave up (or was rejected) but the ranker has a candidate; show it, clearly unverified
218
+ parts, abst, tier = [("ref", "E1")], False, 2
219
+ elif abst and weak:
220
+ tier = 3
221
+ # the reader: an independent model reads the top candidates and says whether each states the answer.
222
+ # It can confirm an unverified best match (or rescue an abstention) and it must agree before the rankers'
223
+ # "verified" stands; a candidate the reader confirms is cited, with its hops.
224
+ if READER and ev:
225
+ if tier == 1:
226
+ read = reads_as_answer(question, _excerpt(ev[0]))
227
+ if read is False:
228
+ tier = 2 # rankers agreed, reader disagrees: show, but unverified
229
+ else:
230
+ e_ok = _reader_pick(ev[:3])
231
+ if e_ok is not None:
232
+ parts, abst, tier, read = [("ref", e_ok.tag)], False, 1, True
233
+ if tier == 2 and not abst and uncovered:
234
+ # "Which player played for both Wolves and Al Hilal?" answered with a sentence that never mentions Al Hilal, or
235
+ # "CEO of WhatsApp" with a sentence about another company: a proper noun, a rare word or a planner entity of the
236
+ # question that the cited text does not cover means the passage is about something else. Closest passages, no bold.
237
+ words = re.findall(r"[A-Za-z0-9][\w'’-]*", question)
238
+ caps = {_fold(w) for w in words[1:] if w[:1].isupper()}
239
+ from .retrieve import term_weight
240
+ entity_like = [t for t in uncovered if t in caps or t in (info.get("hard") or []) or term_weight(store, t) >= 1.0]
241
+ if entity_like:
242
+ abst, parts, tier = True, [], 3
243
+ uncovered = entity_like
244
+ by_tag = {e.tag: e for e in ev}
245
+ label = "" if abst else (("Answer (reader-verified):\n" if read else "Answer (ranker-verified):\n") if tier == 1 else "Best match (unverified):\n")
246
+ sa = None
247
+ _short.verified = tier == 1
248
+ if not abst and (tier == 1 or SHORT_ON_BEST):
249
+ cited = [by_tag[r] for k_, r in parts if k_ == "ref" and r in by_tag]
250
+ _short.n_cited = max(1, len(cited))
251
+ sa = _short(cited + [e for e in ev[:3] if e not in cited], atype)
252
+ return {"text": label + render(parts, ev, abst, short=sa["answer"] if sa else None), "short_answer": sa, "raw": raw, "ok": v["ok"], "problems": v["problems"], "abstained": abst, "tier": tier,
253
+ "top_score": round(top, 2), "margin": round(margin, 2), "score2": None if score2 is None else round(score2, 2), "agree": agree,
254
+ "uncovered": uncovered, "bridged": info.get("bridged", 0), "planner": info.get("planner"), "planner_error": info.get("planner_error"), "reader": read,
255
+ "evidence_texts": [e.text + (" " + e.hop_text() if e.bridges else "") for e in ev], "cited_texts": [by_tag[r].text + (" " + by_tag[r].hop_text() if by_tag[r].bridges else "") for r in ([val for k_, val in parts if k_ == "ref"] if not abst else []) if r in by_tag], "evidence_ids": [e.sent_id for e in ev], "cited_ids": [by_tag[r].sent_id for r in ([val for k_, val in parts if k_ == "ref"] if not abst else []) if r in by_tag], "pool_sids": info.get("pool_sids", []), "anchors": info["anchors"], "ms_retrieve": round(1000*(t1-t0)), "ms_generate": round(1000*(t2-t1))}
256
+
257
+ if __name__ == "__main__":
258
+ ap = argparse.ArgumentParser(); ap.add_argument("--store", required=True); ap.add_argument("--server", default="http://127.0.0.1:8080")
259
+ ap.add_argument("question", nargs="+"); a = ap.parse_args()
260
+ st = Store(a.store)
261
+ for q in a.question:
262
+ r = answer(st, a.server, q)
263
+ print(f"\nQ: {q}\n{r['text']}\n [{r['ms_retrieve']} ms retrieve, {r['ms_generate']} ms generate, raw={r.get('raw','')!r}, problems={r.get('problems')}]")
code/gse_mini/dense.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dense passage search (usearch HNSW over bge-small embeddings). Optional: silently off if the index is missing."""
2
+ from __future__ import annotations
3
+ import os
4
+ import numpy as np
5
+ VEC_DIR = os.environ.get("GSE_VEC", "/root/data/vec")
6
+ _IDX = _MODEL = None
7
+ _OFF = os.environ.get("GSE_DENSE", "1") == "0"
8
+
9
+ def get():
10
+ global _IDX, _MODEL, _OFF
11
+ if _OFF:
12
+ return None
13
+ if _IDX is None:
14
+ try:
15
+ from usearch.index import Index
16
+ from sentence_transformers import SentenceTransformer
17
+ _IDX = Index.restore(f"{VEC_DIR}/passages.usearch", view=True)
18
+ _MODEL = SentenceTransformer("BAAI/bge-small-en-v1.5", device=os.environ.get("GSE_DENSE_DEVICE", "cpu"))
19
+ _MODEL.max_seq_length = 64
20
+ except Exception:
21
+ _OFF = True; return None
22
+ return _IDX
23
+
24
+ def search(question: str, k: int = 40) -> list[tuple[int, float]]:
25
+ """Top-k passage ids with cosine similarity. bge recommends a query instruction for short queries."""
26
+ idx = get()
27
+ if idx is None:
28
+ return []
29
+ q = _MODEL.encode(["Represent this sentence for searching relevant passages: " + question], normalize_embeddings=True)[0].astype(np.float16)
30
+ m = idx.search(q, k)
31
+ return [(int(key), float(1.0 - d)) for key, d in zip(m.keys, m.distances)]
code/gse_mini/extract.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Short-answer extraction (design §6, M2's reader role): a 33M SQuAD2 model marks the answer SPAN inside the cited
2
+ sentence (with its article title and hops), so the short answer is copied text, never generated. The span is checked
3
+ against the planner's answer type, and agreement across the top candidates (DrQA-style voting) adds confidence."""
4
+ from __future__ import annotations
5
+ import os, re
6
+ MODEL = os.environ.get("GSE_READER_SPAN", "deepset/minilm-uncased-squad2")
7
+ _QA = None
8
+ _OFF = os.environ.get("GSE_EXTRACT", "1") == "0"
9
+
10
+ class _SpanModel:
11
+ """Manual SQuAD2 span head (the transformers pipeline was removed in v5): start/end logits, no-answer via [CLS]."""
12
+ def __init__(self, name):
13
+ import torch
14
+ from transformers import AutoTokenizer, AutoModelForQuestionAnswering
15
+ torch.set_num_threads(int(os.environ.get("GSE_EXTRACT_THREADS", "4")))
16
+ self.tok = AutoTokenizer.from_pretrained(name); self.model = AutoModelForQuestionAnswering.from_pretrained(name).eval()
17
+ def __call__(self, question, context, max_answer_tokens=24):
18
+ import torch
19
+ enc = self.tok(question, context, truncation="only_second", max_length=384, return_offsets_mapping=True, return_tensors="pt")
20
+ offsets = enc.pop("offset_mapping")[0].tolist(); seq_ids = enc.sequence_ids(0)
21
+ with torch.no_grad():
22
+ out = self.model(**enc)
23
+ start, end = out.start_logits[0], out.end_logits[0]
24
+ null = float(start[0] + end[0])
25
+ ctx_idx = [i for i, sid in enumerate(seq_ids) if sid == 1]
26
+ if not ctx_idx:
27
+ return {"answer": "", "score": 0.0}
28
+ best, best_s = None, -1e9
29
+ s_top = sorted(ctx_idx, key=lambda i: -float(start[i]))[:20]
30
+ e_top = sorted(ctx_idx, key=lambda i: -float(end[i]))[:20]
31
+ for i in s_top:
32
+ for j in e_top:
33
+ if j < i or j - i + 1 > max_answer_tokens:
34
+ continue
35
+ sc = float(start[i] + end[j])
36
+ if sc > best_s:
37
+ best_s, best = sc, (i, j)
38
+ if best is None or best_s <= null:
39
+ return {"answer": "", "score": 0.0, "null_margin": null - best_s if best else None}
40
+ a, b = offsets[best[0]][0], offsets[best[1]][1]
41
+ span = context[a:b]
42
+ # confidence: softmax-style gap between the span and the no-answer option, squashed to (0, 1)
43
+ import math
44
+ conf = 1.0 / (1.0 + math.exp(-(best_s - null) / 2.0))
45
+ return {"answer": span, "score": conf}
46
+
47
+ def get():
48
+ global _QA, _OFF
49
+ if _OFF:
50
+ return None
51
+ if _QA is None:
52
+ try:
53
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
54
+ _QA = _SpanModel(MODEL)
55
+ except Exception:
56
+ _OFF = True; return None
57
+ return _QA
58
+
59
+ _DATE = re.compile(r"\b(?:\d{1,2}\s+)?(?:january|february|march|april|may|june|july|august|september|october|november|december)\b.*?\d{4}|\b(?:1[0-9]{3}|20[0-9]{2})\b", re.I)
60
+ _NUM = re.compile(r"\d[\d,.]*")
61
+ _NAME = re.compile(r"^[A-Z][\w'’.-]*(?:\s+(?:of|the|de|da|di|von|van|and|&)\s+)?(?:\s*[A-Z][\w'’.-]*){0,5}$")
62
+
63
+ def type_ok(span: str, answer_type: str | None) -> bool:
64
+ s = span.strip()
65
+ if not s or len(s) > 80:
66
+ return False
67
+ if answer_type == "date":
68
+ return bool(_DATE.search(s))
69
+ if answer_type == "number":
70
+ return bool(_NUM.search(s))
71
+ if answer_type in ("person", "place", "organization"):
72
+ return bool(_NAME.match(s)) or (s[:1].isupper() and len(s.split()) <= 6)
73
+ return True
74
+
75
+ def normalize(s: str) -> str:
76
+ return re.sub(r"[^a-z0-9 ]", "", s.lower()).strip()
77
+
78
+ def extract(question: str, candidates: list[tuple[str, str]], answer_type: str | None = None, min_score: float = 0.15) -> dict | None:
79
+ """candidates: [(context_text, tag), ...] in rank order. Returns {"answer", "score", "tag", "votes"} or None.
80
+ The context must carry the article title ("Donald Trump: ...he served as the 45th president...") so that a
81
+ pronoun sentence can yield the subject's name as the span."""
82
+ qa = get()
83
+ if qa is None or not candidates:
84
+ return None
85
+ best, votes = None, {}
86
+ for ctx, tag in candidates[:4]:
87
+ try:
88
+ r = qa(question, ctx[:2000])
89
+ except Exception:
90
+ continue
91
+ span = (r.get("answer") or "").strip(" .,;:\"'“”")
92
+ score = float(r.get("score") or 0.0)
93
+ if not span or score < min_score or not type_ok(span, answer_type):
94
+ continue
95
+ key = normalize(span)
96
+ votes[key] = votes.get(key, 0) + 1
97
+ if best is None or score > best["score"]:
98
+ best = {"answer": span, "score": round(score, 3), "tag": tag}
99
+ if best is None:
100
+ return None
101
+ best["votes"] = votes.get(normalize(best["answer"]), 1)
102
+ return best
code/gse_mini/ingest/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Source adapters. Each yields doc records: {"kb","title","path","sections":[(name,text)],"aliases":[...]}."""
code/gse_mini/ingest/text.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plain-text / markdown / JSONL adapters, so GSE slots onto any text you give it.
2
+
3
+ - A directory of .txt/.md files: one doc per file; markdown headings become sections.
4
+ - A .jsonl file: one doc per line with {"title","text"} and optional "aliases", "path", "sections":[[name,text],...].
5
+ """
6
+ from __future__ import annotations
7
+ import json, os, re
8
+ from typing import Iterator
9
+
10
+ _H = re.compile(r"^(#{1,3})\s+(.*)$", re.M)
11
+
12
+ def md_sections(text: str) -> list[tuple[str, str]]:
13
+ parts = _H.split(text)
14
+ if len(parts) == 1:
15
+ return [("lead", text)]
16
+ out = []
17
+ lead = parts[0].strip()
18
+ if lead:
19
+ out.append(("lead", lead))
20
+ for i in range(1, len(parts), 3):
21
+ name, body = parts[i + 1].strip(), parts[i + 2].strip()
22
+ if body:
23
+ out.append((name[:80], body))
24
+ return out
25
+
26
+ def iter_dir(path: str, kb: str) -> Iterator[dict]:
27
+ for root, _, files in os.walk(path):
28
+ for f in sorted(files):
29
+ if not f.lower().endswith((".txt", ".md")):
30
+ continue
31
+ p = os.path.join(root, f)
32
+ text = open(p, encoding="utf-8", errors="ignore").read()
33
+ m = re.match(r"^#\s+(.+)$", text, re.M)
34
+ title = m.group(1).strip() if m else os.path.splitext(f)[0].replace("_", " ")
35
+ yield {"kb": kb, "title": title, "path": os.path.relpath(p, path), "sections": md_sections(text), "aliases": []}
36
+
37
+ def iter_jsonl(path: str, kb: str) -> Iterator[dict]:
38
+ with open(path, encoding="utf-8") as fh:
39
+ for n, line in enumerate(fh):
40
+ if not line.strip():
41
+ continue
42
+ d = json.loads(line)
43
+ secs = d.get("sections") or md_sections(d.get("text", ""))
44
+ yield {"kb": d.get("kb", kb), "title": d["title"], "path": d.get("path", f"{n}"),
45
+ "sections": [tuple(s) for s in secs], "aliases": d.get("aliases", [])}
code/gse_mini/ingest/zim.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kiwix ZIM adapter (Wikipedia, iFixit, Appropedia, zimit crawls...). Uses python-libzim + lxml.
2
+
3
+ Parallel over entry-id ranges: each worker opens the archive itself and returns parsed docs
4
+ and (alias, target_path) redirects; the parent process writes to the store.
5
+ """
6
+ from __future__ import annotations
7
+ import re
8
+ from lxml import html as lxml_html
9
+
10
+ SKIP_CLASSES = {"reference", "mw-editsection", "hatnote", "navbox", "toc", "noprint", "metadata",
11
+ "ambox", "infobox", "sidebar", "mw-empty-elt", "reflist", "thumb", "gallery", "mbox-small", "vertical-navbox"}
12
+ HEADINGS = {"h2", "h3"}
13
+
14
+ def _skip(el) -> bool:
15
+ cls = el.get("class") or ""
16
+ return any(c in SKIP_CLASSES for c in cls.split())
17
+
18
+ def html_to_sections(raw: bytes) -> list[tuple[str, str]]:
19
+ """Walk the body in document order: paragraphs + list items grouped under h2/h3 headings."""
20
+ try:
21
+ root = lxml_html.fromstring(raw)
22
+ except Exception:
23
+ return []
24
+ body = root.find("body")
25
+ if body is None:
26
+ body = root
27
+ for bad in body.xpath(".//script|.//style|.//sup|.//table|.//figure|.//nav|.//aside"):
28
+ bad.drop_tree()
29
+ sections: list[tuple[str, list[str]]] = [("lead", [])]
30
+ for el in body.iter():
31
+ tag = el.tag if isinstance(el.tag, str) else ""
32
+ if tag in HEADINGS:
33
+ name = " ".join(el.text_content().split())[:80]
34
+ if name:
35
+ sections.append((name, []))
36
+ elif tag in ("p", "li", "dd"):
37
+ if any(_skip(a) for a in el.iterancestors()) or _skip(el):
38
+ continue
39
+ txt = " ".join(el.text_content().split())
40
+ if len(txt) >= 20:
41
+ sections[-1][1].append(txt)
42
+ out = []
43
+ for name, paras in sections:
44
+ if name.lower() in {"references", "external links", "see also", "notes", "further reading", "bibliography", "sources", "footnotes"}:
45
+ continue
46
+ if paras:
47
+ out.append((name, " ".join(paras)))
48
+ return out
49
+
50
+ def _open(path):
51
+ from libzim.reader import Archive
52
+ return Archive(path)
53
+
54
+ def _entry_by_id(archive, i):
55
+ f = getattr(archive, "get_entry_by_id", None) or getattr(archive, "_get_entry_by_id")
56
+ return f(i)
57
+
58
+ ALLOWED = None # optional frozenset of entry paths to keep (set in the parent before forking workers)
59
+
60
+ def parse_range(args):
61
+ """Worker: (zim_path, kb, start, end) -> (docs, redirects, n_seen)"""
62
+ zim_path, kb, start, end = args
63
+ archive = _open(zim_path)
64
+ docs, redirects = [], []
65
+ for i in range(start, min(end, archive.all_entry_count)):
66
+ try:
67
+ e = _entry_by_id(archive, i)
68
+ except Exception:
69
+ continue
70
+ try:
71
+ if e.is_redirect:
72
+ tgt = e.get_redirect_entry()
73
+ redirects.append((e.title, tgt.path))
74
+ continue
75
+ if ALLOWED is not None and e.path not in ALLOWED:
76
+ continue
77
+ item = e.get_item()
78
+ if not item.mimetype.startswith("text/html"):
79
+ continue
80
+ title = e.title or e.path.rsplit("/", 1)[-1]
81
+ if ":" in title.split(" ")[0] and title.split(":")[0] in ("Category", "File", "Template", "Wikipedia", "Help", "Portal", "Special", "Talk", "User"):
82
+ continue
83
+ sections = html_to_sections(bytes(item.content))
84
+ if sections:
85
+ docs.append({"kb": kb, "title": title, "path": e.path, "sections": sections, "aliases": []})
86
+ except Exception:
87
+ continue
88
+ return docs, redirects, min(end, archive.all_entry_count) - start
89
+
90
+ def entry_count(zim_path: str) -> int:
91
+ return _open(zim_path).all_entry_count
code/gse_mini/planner.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The question-understanding layer (design §6, M1): a language model turns the question into a RETRIEVAL PLAN.
2
+
3
+ The plan is generic. Nothing here knows about Thailand, football or years; the model does: it writes the answer
4
+ *as the corpus would phrase it* (a hypothetical sentence), names the entities to anchor on, the constraints the
5
+ answer must satisfy, and the hops if more than one article is needed. The harness executes it.
6
+
7
+ Served by llama-server (OpenAI-compatible chat endpoint, JSON-schema constrained). Prototype with the 8B teacher;
8
+ the production planner is our own small model trained on the teacher's plans (SFT, then RL with retrieval recall).
9
+ """
10
+ from __future__ import annotations
11
+ import collections, json, os, re, time, unicodedata, urllib.request
12
+
13
+ PLANNER = os.environ.get("GSE_PLANNER", "") # e.g. http://127.0.0.1:8092 ; empty = planner off
14
+ PLANNER_KIND = os.environ.get("GSE_PLANNER_KIND", "chat") # "chat": instruct model via /v1/chat/completions; "own": our planner via raw /completion
15
+
16
+ SCHEMA = {
17
+ "type": "object",
18
+ "properties": {
19
+ "entities": {"type": "array", "items": {"type": "string"}, "maxItems": 4},
20
+ "answer_type": {"type": "string", "enum": ["person", "place", "organization", "date", "number", "yes_no", "definition", "howto", "other"]},
21
+ "hypothetical": {"type": "string"},
22
+ "search_terms": {"type": "array", "items": {"type": "string"}, "maxItems": 8},
23
+ "constraints": {"type": "array", "maxItems": 4, "items": {"type": "object", "properties": {
24
+ "must": {"type": "string"}, "forms": {"type": "array", "items": {"type": "string"}, "maxItems": 4}}, "required": ["must", "forms"]}},
25
+ "hops": {"type": "array", "items": {"type": "string"}, "maxItems": 3},
26
+ "answerable": {"type": "boolean"},
27
+ "reason": {"type": "string"},
28
+ },
29
+ "required": ["entities", "answer_type", "hypothetical", "search_terms", "constraints", "hops", "answerable", "reason"],
30
+ }
31
+
32
+ SYSTEM = """You turn a user's question into a retrieval plan for an offline encyclopedia (Wikipedia lead sections plus repair and appropriate-technology manuals). Output JSON only.
33
+ - entities: the specific things to look up, written as encyclopedia article titles (expand abbreviations: "UK" -> "United Kingdom"; "the fourth king of Thailand" -> "Thailand", "Chakri dynasty").
34
+ - answer_type: what kind of thing the answer is.
35
+ - hypothetical: ONE sentence, in the encyclopedia's own wording, that would answer the question. Put ____ where the unknown answer goes. Use the corpus's conventions (regnal numbers like "Rama IV", "Prime Minister of the United Kingdom", "from 1997 to 2007", "all-time record goalscorer").
36
+ - search_terms: 3-8 terms in corpus wording that the answer sentence would contain, including synonyms/expansions (monarch/king, Siam/Thailand, goalscorer/scorer).
37
+ - constraints: the conditions in the question that the answer sentence (or a linked sentence) must satisfy. Each has "must": the words of the question that express it (copy them from the question: "largest population", "Midlands", "1999") and "forms": other wordings the encyclopedia might use for the same condition ("most populous", "West Midlands", "1997 to 2007").
38
+ - hops: if the answer needs more than one article, list the sub-questions in order; otherwise [].
39
+ - answerable: false if no encyclopedia could answer it: a matter of opinion or taste, a prediction about the future, something personal or private to the asker, gibberish, or a request for advice rather than a fact. true otherwise. reason: a few words ("opinion", "future event", "personal", "nonsense", or "" when answerable)."""
40
+
41
+ def _clean(p: dict) -> dict:
42
+ p["entities"] = [str(e).strip() for e in (p.get("entities") or []) if e and str(e).strip()]
43
+ p["search_terms"] = list(dict.fromkeys(str(t).strip() for t in (p.get("search_terms") or []) if t and str(t).strip()))
44
+ p["hops"] = list(dict.fromkeys(str(h).strip() for h in (p.get("hops") or []) if h and str(h).strip()))
45
+ p.setdefault("hops", []); p.setdefault("constraints", []); p.setdefault("answerable", True); p.setdefault("reason", "")
46
+ return p
47
+
48
+ # the schema our own planner was trained on (constraints as strings; no answerability fields yet)
49
+ SCHEMA_OWN = {
50
+ "type": "object",
51
+ "properties": {
52
+ "entities": {"type": "array", "items": {"type": "string"}, "maxItems": 4},
53
+ "answer_type": {"type": "string", "enum": ["person", "place", "organization", "date", "number", "yes_no", "definition", "howto", "other"]},
54
+ "hypothetical": {"type": "string"},
55
+ "search_terms": {"type": "array", "items": {"type": "string"}, "maxItems": 8},
56
+ "constraints": {"type": "array", "items": {"type": "string"}, "maxItems": 4},
57
+ "hops": {"type": "array", "items": {"type": "string"}, "maxItems": 3},
58
+ },
59
+ "required": ["entities", "answer_type", "hypothetical", "search_terms", "constraints", "hops"],
60
+ }
61
+
62
+ def _post(url: str, body: dict, timeout: float) -> dict:
63
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
64
+ with urllib.request.urlopen(req, timeout=timeout) as r:
65
+ return json.loads(r.read())
66
+
67
+ # Second attempt when greedy decoding loops ("You You You ...", seen on 12% of real search-style questions, design §15.9):
68
+ # sample with a mild repetition penalty instead of returning no plan at all.
69
+ RESAMPLE = {"temperature": 0.6, "top_p": 0.9, "repeat_penalty": 1.15, "repeat_last_n": 64, "seed": 7}
70
+
71
+ def plan_own(question: str, server: str, timeout: float = 30.0) -> dict | None:
72
+ """Our own planner (a plain decoder trained on teacher plans): raw completion under the schema it was trained on.
73
+ It has no answerability judgement yet (that comes with the next training round), so answerable defaults to True."""
74
+ schema = SCHEMA if os.environ.get("GSE_PLANNER_SCHEMA", "own") == "full" else SCHEMA_OWN # v2 planners are trained on the full schema
75
+ base = {"prompt": f"<|question|> {question.strip()}\n<|plan|>", "n_predict": 320, "temperature": 0.0,
76
+ "stop": ["<|end|>"], "json_schema": schema, "cache_prompt": False}
77
+ t0 = time.time(); err = "no attempt"
78
+ for attempt, extra in enumerate(({}, RESAMPLE)):
79
+ try:
80
+ d = _post(f"{server}/completion", {**base, **extra}, timeout)
81
+ if d.get("stop_type") == "limit" and attempt == 0:
82
+ err = "greedy decoding hit n_predict"; continue
83
+ p = json.loads(d["content"])
84
+ except Exception as ex:
85
+ err = str(ex)[:120]; continue
86
+ p["ms"] = round(1000 * (time.time() - t0)); p["resampled"] = attempt > 0
87
+ return _clean(p)
88
+ return {"error": err, "ms": round(1000 * (time.time() - t0))}
89
+
90
+ # ---- grounding gate (design §15.9) -------------------------------------------------------------------------------
91
+ # A 113M planner hallucinates under distribution shift (real search-style questions): "arsenal premier league" -> "United States
92
+ # Army". The harness therefore keeps only planner claims that are anchored in the question's own words, drops degenerate strings,
93
+ # and treats a plan with nothing anchored as "no plan" so retrieval falls back to the heuristic pool. Same spirit as the
94
+ # content-free glue check for the decoder: the small model may organise the lookup, never invent its subject.
95
+ _WORD = re.compile(r"[a-z0-9]+")
96
+
97
+ def _fold(text: str) -> str:
98
+ return "".join(c for c in unicodedata.normalize("NFKD", text.lower()) if not unicodedata.combining(c))
99
+
100
+ def _content(text: str) -> list[str]:
101
+ from .store import Store
102
+ return [t for t in _WORD.findall(_fold(text)) if t not in Store.QWORDS and len(t) > 1]
103
+
104
+ def _anchored(phrase: str, qtoks: list[str]) -> bool:
105
+ """A phrase is anchored if one of its content tokens occurs in the question (4-char stem prefix tolerates inflection)."""
106
+ for t in _content(phrase):
107
+ k = t[:4]
108
+ if any((q.startswith(k) and len(t) > 4) or q == t for q in qtoks):
109
+ return True
110
+ return False
111
+
112
+ def _degenerate(text: str, max_words: int) -> bool:
113
+ """Too long, a content word repeated 3+ times, or any word repeated 4+ times ("You You You You")."""
114
+ toks, alltoks = _content(text), _WORD.findall(text.lower())
115
+ rep = lambda ts, k: bool(ts) and collections.Counter(ts).most_common(1)[0][1] >= k
116
+ return len(alltoks) > max_words or rep(toks, 3) or rep(alltoks, 4)
117
+
118
+ def ground_plan(p: dict | None, question: str) -> dict | None:
119
+ if not p or "error" in p:
120
+ return p
121
+ qt = _content(question)
122
+ ents = list(dict.fromkeys(e for e in p.get("entities") or [] if not _degenerate(e, 8) and _anchored(e, qt)))
123
+ p["dropped"] = len(p.get("entities") or []) - len(ents); p["entities"] = ents
124
+ p["search_terms"] = [t for t in p.get("search_terms") or [] if not _degenerate(t, 8)]
125
+ hyp = p.get("hypothetical") or ""
126
+ p["hypothetical"] = "" if _degenerate(hyp, 40) or not _anchored(hyp, qt) else hyp
127
+ # a hop question legitimately names the bridge entity (which is not in the question), so it may anchor in the surviving plan too
128
+ pool = qt + [t for s in p["entities"] + p["search_terms"] + [p["hypothetical"]] for t in _content(s)]
129
+ p["hops"] = [h for h in p.get("hops") or [] if isinstance(h, str) and not _degenerate(h, 30) and _anchored(h, pool)]
130
+ cons = []
131
+ for c in p.get("constraints") or []:
132
+ must = c.get("must") if isinstance(c, dict) else c
133
+ if not isinstance(must, str) or _degenerate(must, 12) or not _anchored(must, qt):
134
+ continue
135
+ mt = _content(must)
136
+ if len(mt) > 3 or (qt and len(set(mt) & set(qt)) > max(2, len(set(qt)) // 2)):
137
+ continue # "who votes in the speaker of the house" restates the question: every word would become a hard requirement
138
+ cons.append(c)
139
+ p["constraints"] = cons
140
+ if not p["entities"] and not p["hypothetical"]:
141
+ return {"error": "plan not anchored in the question", "ms": p.get("ms", 0)}
142
+ return p
143
+
144
+
145
+ def plan(question: str, server: str | None = None, timeout: float = 30.0, kind: str | None = None) -> dict | None:
146
+ server = server or PLANNER
147
+ if not server:
148
+ return None
149
+ if (kind or PLANNER_KIND) == "own":
150
+ return ground_plan(plan_own(question, server, timeout), question)
151
+ body = {
152
+ "messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question.strip() + " /no_think"}],
153
+ "temperature": 0.0, "max_tokens": 400,
154
+ "response_format": {"type": "json_schema", "json_schema": {"name": "plan", "schema": SCHEMA}},
155
+ }
156
+ req = urllib.request.Request(f"{server}/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
157
+ t0 = time.time()
158
+ try:
159
+ with urllib.request.urlopen(req, timeout=timeout) as r:
160
+ out = json.loads(r.read())
161
+ text = out["choices"][0]["message"]["content"]
162
+ text = text.split("</think>")[-1].strip()
163
+ p = json.loads(text)
164
+ except Exception as ex: # planner down or malformed: the harness falls back to heuristic retrieval
165
+ return {"error": str(ex)[:120], "ms": round(1000 * (time.time() - t0))}
166
+ p["ms"] = round(1000 * (time.time() - t0))
167
+ return ground_plan(_clean(p), question)
code/gse_mini/prompt.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompt format, special tokens and the decode grammar for the stitched-answer task.
2
+
3
+ The model sees numbered evidence sentences and the question, and may only emit glue text and
4
+ reference tokens <q E1> ... <q E16>, or <abstain>. Each reference is ONE token in the trained
5
+ tokenizer, so a quote costs one decode step and the grammar is trivial.
6
+ """
7
+ from __future__ import annotations
8
+ import re
9
+ from .retrieve import Evidence
10
+
11
+ MAX_EVIDENCE = 16
12
+ REF_TOKENS = [f"<q E{i}>" for i in range(1, MAX_EVIDENCE + 1)]
13
+ ABSTAIN = "<abstain>"
14
+ BOS_EVIDENCE, BOS_QUESTION, BOS_ANSWER, EOS_ANSWER = "<|evidence|>", "<|question|>", "<|answer|>", "<|end|>"
15
+ SPECIAL_TOKENS = REF_TOKENS + [ABSTAIN, BOS_EVIDENCE, BOS_QUESTION, BOS_ANSWER, EOS_ANSWER]
16
+
17
+ def evidence_block(ev: list[Evidence]) -> str:
18
+ lines = []
19
+ for e in ev:
20
+ sec = "" if e.section == "lead" else f" › {e.section}"
21
+ line = f"[{e.tag}] ({e.title}{sec}) {e.text}"
22
+ for _, bt, bx in e.bridges:
23
+ line += f" ⟶ ({bt}) {bx}"
24
+ lines.append(line)
25
+ return "\n".join(lines)
26
+
27
+ def build_prompt(ev: list[Evidence], question: str) -> str:
28
+ return f"{BOS_EVIDENCE}\n{evidence_block(ev)}\n{BOS_QUESTION} {question.strip()}\n{BOS_ANSWER}"
29
+
30
+ def gbnf(n_evidence: int, max_glue_tokens: int = 40, allowed: list[int] | None = None) -> str:
31
+ """Grammar for llama.cpp: refs limited to the evidence that exists (or to `allowed` ids when the ranker is
32
+ confident, so the decoder only writes framing); glue between refs is short."""
33
+ ids = allowed or list(range(1, n_evidence + 1))
34
+ refs = " | ".join(f'"<q E{i}>"' for i in ids)
35
+ return f'''root ::= "{ABSTAIN}" | answer
36
+ answer ::= segment+ glue?
37
+ segment ::= glue? ref
38
+ ref ::= {refs}
39
+ glue ::= [^<]{{1,{max_glue_tokens * 5}}}
40
+ '''
41
+
42
+ REF_RE = re.compile(r"<q E(\d+)>")
43
+
44
+ def parse_answer(text: str) -> tuple[list[tuple[str, str]], bool]:
45
+ """Returns ([("glue", str) | ("ref", "E3"), ...], abstained)."""
46
+ text = text.split(EOS_ANSWER)[0].strip()
47
+ if text.startswith(ABSTAIN):
48
+ return [], True
49
+ parts: list[tuple[str, str]] = []
50
+ pos = 0
51
+ for m in REF_RE.finditer(text):
52
+ glue = text[pos:m.start()]
53
+ if glue.strip():
54
+ parts.append(("glue", glue))
55
+ parts.append(("ref", f"E{m.group(1)}"))
56
+ pos = m.end()
57
+ tail = text[pos:]
58
+ if tail.strip():
59
+ parts.append(("glue", tail))
60
+ return parts, False
code/gse_mini/reader.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The reader (design §6, M2's second role): does this sentence answer the question? A third, independent signal next
2
+ to the two rankers. On the box it is the 8B instruct model behind llama-server; on a Pi it will be a small model
3
+ distilled from it (see vast/remote/15_judge_pairs.py). Off when GSE_READER is empty."""
4
+ from __future__ import annotations
5
+ import json, os, time, urllib.request
6
+
7
+ READER = os.environ.get("GSE_READER", "")
8
+ SYS = ("You judge whether a quoted encyclopedia excerpt states the answer to a question. The excerpt may include a linked "
9
+ "sentence from another article. A year inside a stated range counts. Reply with exactly one word: yes or no. /no_think")
10
+
11
+ def reads_as_answer(question: str, text: str, server: str | None = None, timeout: float = 20.0) -> bool | None:
12
+ server = server or READER
13
+ if not server:
14
+ return None
15
+ body = {"messages": [{"role": "system", "content": SYS},
16
+ {"role": "user", "content": f"Question: {question}\n\nExcerpt:\n{text[:1200]}\n\nDoes the excerpt state the answer? yes or no."}],
17
+ "temperature": 0.0, "max_tokens": 4}
18
+ req = urllib.request.Request(f"{server}/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
19
+ try:
20
+ with urllib.request.urlopen(req, timeout=timeout) as r:
21
+ out = json.loads(r.read())["choices"][0]["message"]["content"].strip().lower()
22
+ return out.startswith("yes")
23
+ except Exception:
24
+ return None
25
+
26
+
27
+ YN_SYS = ("You answer a yes/no question using ONLY a quoted encyclopedia excerpt (which may include a linked sentence). "
28
+ "If the excerpt supports yes, reply yes; if it supports no, reply no; if it does not settle it, reply unknown. One word. /no_think")
29
+
30
+ def yes_no(question: str, text: str, server: str | None = None, timeout: float = 20.0) -> str | None:
31
+ """For yes/no questions: 'yes' | 'no' | 'unknown' from the excerpt, or None if the reader is unavailable."""
32
+ server = server or READER
33
+ if not server:
34
+ return None
35
+ body = {"messages": [{"role": "system", "content": YN_SYS},
36
+ {"role": "user", "content": f"Question: {question}\n\nExcerpt:\n{text[:1200]}\n\nAnswer: yes, no or unknown."}],
37
+ "temperature": 0.0, "max_tokens": 4}
38
+ req = urllib.request.Request(f"{server}/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
39
+ try:
40
+ with urllib.request.urlopen(req, timeout=timeout) as r:
41
+ out = json.loads(r.read())["choices"][0]["message"]["content"].strip().lower()
42
+ return "yes" if out.startswith("yes") else "no" if out.startswith("no") else "unknown"
43
+ except Exception:
44
+ return None
code/gse_mini/render.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Expand references to verbatim sentences, shown as cited excerpts (not spliced into the model's sentence)."""
2
+ from __future__ import annotations
3
+ import re
4
+ from .retrieve import Evidence
5
+
6
+ # discourse openers that make a lifted sentence read as a fragment; elided as "[…]" (standard quotation practice)
7
+ _OPENERS = ("because of this, ", "however, ", "thus, ", "therefore, ", "in addition, ", "for example, ", "as a result, ",
8
+ "also, ", "moreover, ", "furthermore, ", "in contrast, ", "nevertheless, ", "consequently, ", "additionally, ",
9
+ "for instance, ", "on the other hand, ", "in other words, ", "that said, ", "meanwhile, ", "similarly, ", "finally, ")
10
+
11
+ def tidy_quote(text: str) -> str:
12
+ low = text.lower()
13
+ for o in _OPENERS:
14
+ if low.startswith(o):
15
+ return "[…] " + text[len(o):]
16
+ return text
17
+
18
+ def source_label(e: Evidence) -> str:
19
+ return e.title if e.section == "lead" else f"{e.title} › {e.section}"
20
+
21
+ def render(parts, ev: list[Evidence], abstained: bool, short: str | None = None) -> str:
22
+ by_tag = {e.tag: e for e in ev}
23
+ if abstained:
24
+ closest = "\n".join(f" › “{tidy_quote(e.text)}” — {source_label(e)}" for e in ev[:3])
25
+ return "No direct answer found in the library. Closest passages:\n" + closest
26
+ glue: list[str] = []
27
+ quotes: list[tuple[str, str]] = []
28
+ frame: list[str] = [] # glue with the first quote's position marked, to be completed with the short answer
29
+ for kind, val in parts:
30
+ if kind == "glue":
31
+ g = val.strip()
32
+ if g:
33
+ glue.append(g); frame.append(g)
34
+ else:
35
+ e = by_tag.get(val)
36
+ if e is not None and all(q[0] != e.text for q in quotes):
37
+ quotes.append((e.text, source_label(e)))
38
+ for hop, (_, bt, bx) in enumerate(e.bridges, 1):
39
+ quotes.append((bx, f"{bt} (linked, hop {hop})"))
40
+ if "\x00" not in frame:
41
+ frame.append("\x00")
42
+ head = " ".join(glue).strip()
43
+ head = re.sub(r"\s+([,.;:])", r"\1", head)
44
+ lines = []
45
+ # Composition, not generation: the model wrote a content-free frame ("The CEO of OpenAI is <quote>."); the short answer is
46
+ # a span copied from that quote. Filling the frame with the span gives a readable sentence whose every content word
47
+ # came from the question or the cited text; the full quote still follows as the citation.
48
+ filled = None
49
+ if short and "\x00" in frame:
50
+ i = frame.index("\x00")
51
+ before = " ".join(frame[:i]).strip(); after = " ".join(frame[i+1:]).strip()
52
+ if before and re.fullmatch(r"[.,;:!?]*", after):
53
+ filled = f"{before} **{short}**{after or '.'}"
54
+ if filled:
55
+ lines.append(filled)
56
+ else:
57
+ if short:
58
+ lines.append(f"**{short}**") # the short answer: a span copied from the quoted text or its article title
59
+ if head and re.search(r"\b(?:is|are|was|were|in|of|by|for|at|to|called|named|from|on)[.:]?$", head):
60
+ head = "" # a frame that dangles without its quote ("The CEO of WhatsApp is.") is dropped
61
+ if head and not head.endswith((":", ".", "!", "?")):
62
+ head += ":"
63
+ if head:
64
+ lines.append(head)
65
+ for text, src in quotes:
66
+ lines.append(f" › “{tidy_quote(text)}” — {src}")
67
+ return "\n".join(lines)
code/gse_mini/rerank.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional cross-encoder reranking of the evidence block (design §6: M2 ranker). 22M-parameter MiniLM; ~30 ms for 16 pairs on CPU.
2
+ Loads only from the local HF cache (never downloads inside worker processes); silently disabled if unavailable or GSE_RERANK=0."""
3
+ from __future__ import annotations
4
+ import os
5
+ MODEL = os.environ.get("GSE_RANKER", "cross-encoder/ms-marco-MiniLM-L-6-v2") # a local dir (trained ranker) or a hub id
6
+ MODEL2 = os.environ.get("GSE_RANKER2", "cross-encoder/ms-marco-MiniLM-L-6-v2") # independent second opinion for the trust decision
7
+ _CE = None
8
+ _CE2 = None
9
+ _DISABLED = os.environ.get("GSE_RERANK", "1") == "0"
10
+
11
+ def get():
12
+ global _CE, _DISABLED
13
+ if _DISABLED:
14
+ return None
15
+ if _CE is None:
16
+ try:
17
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
18
+ import torch
19
+ from sentence_transformers import CrossEncoder
20
+ device = os.environ.get("GSE_RERANK_DEVICE", "cpu") # cpu by default: Pi parity, and safe in forked workers
21
+ if device == "cpu":
22
+ torch.set_num_threads(int(os.environ.get("GSE_RERANK_THREADS", "4")))
23
+ _CE = CrossEncoder(MODEL, max_length=256, device=device, local_files_only=not os.path.isdir(MODEL))
24
+ except Exception:
25
+ _DISABLED = True
26
+ return None
27
+ return _CE
28
+
29
+ def _load(name):
30
+ import torch
31
+ from sentence_transformers import CrossEncoder
32
+ device = os.environ.get("GSE_RERANK_DEVICE", "cpu")
33
+ return CrossEncoder(name, max_length=256, device=device, local_files_only=not os.path.isdir(name))
34
+
35
+ def second_opinion(question: str, ev: list, top: int = 8) -> list[float] | None:
36
+ """Scores from the second ranker for the first `top` candidates (None if unavailable or same model as the first)."""
37
+ global _CE2
38
+ if _DISABLED or MODEL2 == MODEL or not ev:
39
+ return None
40
+ if _CE2 is None:
41
+ try:
42
+ _CE2 = _load(MODEL2)
43
+ except Exception:
44
+ return None
45
+ sub = ev[:top]
46
+ return [float(x) for x in _CE2.predict([(question, e.rank_text()) for e in sub], batch_size=32, show_progress_bar=False)]
47
+
48
+ def rerank(question: str, ev: list, keep: int | None = None, hints: list[str] | None = None) -> list:
49
+ """Reorder Evidence by cross-encoder relevance, keep the top `keep`, re-tag E1..En.
50
+ `hints` (the retriever's expansions: siam, monarch, 5th, satellites...) are appended to the query so the
51
+ ranker can match sentences phrased with an alias or synonym. Keeps the list if the model is unavailable."""
52
+ ce = get()
53
+ if ce is None or len(ev) < 2:
54
+ return ev[:keep] if keep else ev
55
+ q = question if not hints else f"{question} ({', '.join(dict.fromkeys(hints))})"
56
+ pairs = [(q, e.rank_text()) for e in ev]
57
+ scores = ce.predict(pairs, batch_size=64, show_progress_bar=False)
58
+ order = sorted(range(len(ev)), key=lambda i: -float(scores[i]))
59
+ if keep:
60
+ order = order[:keep]
61
+ out = []
62
+ for rank, i in enumerate(order):
63
+ e = ev[i]
64
+ e.tag = f"E{rank+1}"; e.score = float(scores[i])
65
+ out.append(e)
66
+ return out
code/gse_mini/retrieve.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Entity-anchored BM25 retrieval -> numbered evidence block (E1..En) of sentences."""
2
+ from __future__ import annotations
3
+ import os, re
4
+ from dataclasses import dataclass, field
5
+ from .store import Store, norm_alias
6
+
7
+ @dataclass
8
+ class Evidence:
9
+ tag: str # "E1"
10
+ sent_id: int
11
+ doc_id: int
12
+ title: str
13
+ section: str
14
+ text: str
15
+ passage_id: int
16
+ score: float
17
+ bridge_sent_id: int | None = None # first hop (kept for compatibility); all hops live in `bridges`
18
+ bridge_title: str | None = None
19
+ bridge_text: str | None = None
20
+ bridges: list = field(default_factory=list) # [(sent_id, title, text), ...] in hop order
21
+
22
+ def add_hop(self, sent_id: int, title: str, text: str):
23
+ self.bridges.append((sent_id, title, text))
24
+ if self.bridge_text is None:
25
+ self.bridge_sent_id, self.bridge_title, self.bridge_text = sent_id, title, text
26
+
27
+ def hop_text(self) -> str:
28
+ return " ".join(f"{t}. {x}" for _, t, x in self.bridges)
29
+
30
+ def rank_text(self) -> str:
31
+ return f"{self.title}. {self.text}" + (" " + self.hop_text() if self.bridges else "")
32
+
33
+ ORDINALS = {"first": ("1st", "i"), "second": ("2nd", "ii"), "third": ("3rd", "iii"), "fourth": ("4th", "iv"), "fifth": ("5th", "v"),
34
+ "sixth": ("6th", "vi"), "seventh": ("7th", "vii"), "eighth": ("8th", "viii"), "ninth": ("9th", "ix"), "tenth": ("10th", "x"),
35
+ "eleventh": ("11th", "xi"), "twelfth": ("12th", "xii")}
36
+ DIGITS = {"1": ("first", "i"), "2": ("second", "ii"), "3": ("third", "iii"), "4": ("fourth", "iv"), "5": ("fifth", "v"),
37
+ "6": ("sixth", "vi"), "7": ("seventh", "vii"), "8": ("eighth", "viii"), "9": ("ninth", "ix"), "10": ("tenth", "x")}
38
+ NOUN_SYN = {"king": ("monarch", "ruler"), "queen": ("monarch",), "capital": ("capital city",), "wrote": ("author", "written"),
39
+ "scorer": ("goalscorer", "goals", "scored"), "goals": ("goalscorer", "scorer"), "most": ("record", "highest"),
40
+ "side": ("allied", "allies", "axis"), "war": ("wartime",), "ww2": ("ii",), "wwii": ("ii",), "ww1": ("i",), "wwi": ("i",),
41
+ "invented": ("inventor", "invention"), "discovered": ("discovery", "discoverer"), "painted": ("painter", "painting"),
42
+ "founded": ("founder", "established"), "died": ("death",), "born": ("birth",), "tall": ("height", "elevation"),
43
+ "population": ("inhabitants",), "longest": ("length",), "largest": ("biggest",), "moons": ("satellites", "moon")}
44
+
45
+ def _edit_close(a: str, b: str, k: int = 2) -> bool:
46
+ """True if a is within k edits of b (cheap bounded Levenshtein), i.e. a typo redirect rather than a real alias."""
47
+ if abs(len(a) - len(b)) > k:
48
+ return False
49
+ prev = list(range(len(b) + 1))
50
+ for i, ca in enumerate(a, 1):
51
+ cur = [i]
52
+ for j, cb in enumerate(b, 1):
53
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
54
+ prev = cur
55
+ return prev[-1] <= k
56
+
57
+ def _terms(store: Store, question: str) -> list[str]:
58
+ return [t for t in re.findall(r"[a-z0-9]+", question.lower()) if t not in store.QWORDS]
59
+
60
+ def _overlap(terms: set[str], text: str) -> int:
61
+ low = text.lower()
62
+ return sum(1 for t in terms if t in low)
63
+
64
+ _CAP = re.compile(r"\b[A-Z][\w'’.-]*(?:\s+(?:of|the|de|da|di|von|van|and)?\s*[A-Z][\w'’.-]*){0,3}")
65
+
66
+ def _fold(text: str) -> str:
67
+ """Lowercase, diacritics stripped (Rúben -> ruben), so coverage is spelling-insensitive."""
68
+ import unicodedata
69
+ return "".join(c for c in unicodedata.normalize("NFKD", text.lower()) if not unicodedata.combining(c))
70
+
71
+ _RANGE = re.compile(r"(?<!\d)(1[0-9]{3}|20[0-9]{2})\s*(?:–|-|—|to|until|till|and)\s*(1[0-9]{3}|20[0-9]{2}|present|now|date)(?!\d)")
72
+ _SINCE = re.compile(r"\b(?:since|from)\s+(1[0-9]{3}|20[0-9]{2})\b(?!\s*(?:–|-|—|to|until))")
73
+
74
+ def _year_covered(text: str, year: int) -> bool:
75
+ """A year is covered by a sentence that states it, or a range containing it ("from 1997 to 2007", "1997–2007",
76
+ "between 1997 and 2007", "since 1997")."""
77
+ for a, b in _RANGE.findall(text):
78
+ hi = 2100 if b in ("present", "now", "date") else int(b)
79
+ if int(a) <= year <= hi:
80
+ return True
81
+ for a in _SINCE.findall(text):
82
+ if int(a) <= year:
83
+ return True
84
+ return False
85
+
86
+ def _covers(text: str, term: str) -> bool:
87
+ low = _fold(text)
88
+ if len(term) <= 3: # short forms ("iv", "ii", "v") must match whole words
89
+ return re.search(rf"(?<![a-z0-9]){re.escape(term)}(?![a-z0-9])", low) is not None
90
+ if term.isdigit() and len(term) == 4 and 1000 <= int(term) <= 2100:
91
+ return re.search(rf"(?<!\d){term}(?!\d)", low) is not None or _year_covered(low, int(term))
92
+ return term in low or (len(term) > 4 and term[:-1] in low)
93
+
94
+ def term_weight(store: Store, t: str) -> float:
95
+ """How much a question term constrains the answer: rare words (midlands) weigh 1, common verbs (play) little."""
96
+ d = store.df(t)
97
+ return 1.0 if d == 0 or d < 50_000 else (0.5 if d < 500_000 else 0.15)
98
+
99
+ def _missing(e, terms: list[str]) -> list[str]:
100
+ hay = f"{e.title} {e.text}"
101
+ return [t for t in terms if not _covers(hay, t)]
102
+
103
+ def _link_docs(store: Store, text: str, cache: dict, exclude: set, limit: int = 6) -> list[int]:
104
+ """Docs for the entities named in a sentence (capitalised mentions resolved through the alias table)."""
105
+ out = []
106
+ for m in _CAP.findall(text)[:limit]:
107
+ key = norm_alias(m)
108
+ if not key or key in store.QWORDS:
109
+ continue
110
+ if key not in cache:
111
+ rows = store.con.execute("SELECT a.doc_id FROM alias a JOIN doc d ON d.id=a.doc_id WHERE a.alias=? ORDER BY d.n_alias DESC LIMIT 1", (key,)).fetchall()
112
+ cache[key] = rows[0][0] if rows else None
113
+ d = cache[key]
114
+ if d is not None and d not in exclude and d not in out:
115
+ out.append(d)
116
+ return out
117
+
118
+ def bridge(store: Store, question: str, ev: list, terms_all: set[str], anchor_ids: list[int], max_links: int = 40,
119
+ weights: dict | None = None, max_hops: int = 3) -> int:
120
+ """Multi-hop link over the alias graph, judged PER CANDIDATE and greedy by rarity-weighted coverage:
121
+ hop 1: entities named in the candidate -> their lead sentences -> attach the one covering the most missing weight;
122
+ hop 2..n: entities named in the attached sentence -> ... until every term is covered or max_hops is reached.
123
+ "He joined Wolverhampton Wanderers" -> (Wolves) "...clubs from the West Midlands" -> (Wolverhampton) "...city in ... England"."""
124
+ qterms = [t for t in terms_all if t not in store.QWORDS and len(t) > 3]
125
+ if not qterms or not ev:
126
+ return 0
127
+ weights = weights or {t: term_weight(store, t) for t in qterms}
128
+ n_bridged, cache = 0, {}
129
+ for e in ev[:32]:
130
+ if e.bridges:
131
+ continue
132
+ missing = _missing(e, qterms)
133
+ if not missing or len(missing) > max(2, len(qterms) - 1):
134
+ continue
135
+ frontier_text, visited = e.text, {e.doc_id}
136
+ for hop in range(max_hops):
137
+ best = None
138
+ for d in _link_docs(store, frontier_text, cache, visited):
139
+ for row in store.lead_sentences(d, n=8):
140
+ hit = sum(weights.get(t, 1.0) for t in missing if _covers(row[4], t))
141
+ if hit >= 0.5 and (best is None or hit > best[0]):
142
+ best = (hit, row, d)
143
+ if best is None:
144
+ # no lead covers a missing term directly: step through the most popular linked entity and look again
145
+ links = _link_docs(store, frontier_text, cache, visited, limit=4)
146
+ if not links or hop == max_hops - 1:
147
+ break
148
+ d = links[0]; visited.add(d)
149
+ lead = store.lead_sentences(d, n=1)
150
+ if not lead:
151
+ break
152
+ frontier_text = lead[0][4]
153
+ continue
154
+ hit, row, d = best
155
+ e.add_hop(row[0], row[5], row[4]); visited.add(d)
156
+ missing = [t for t in missing if not _covers(row[4], t)]
157
+ frontier_text = row[4]
158
+ if not missing:
159
+ break
160
+ if e.bridges:
161
+ n_bridged += 1
162
+ if len(cache) >= max_links:
163
+ break
164
+ return n_bridged
165
+
166
+ def _plan(store: Store, question: str, anchors) -> tuple[list[str], dict[str, list[str]]]:
167
+ """Query terms are the question's content tokens (never required phrases). Synonyms OR-ed with a token:
168
+ ordinal forms, a few question-noun variants, and other single-word names of the entity the token names
169
+ (thailand -> siam) taken from the alias table of popular docs."""
170
+ toks = [t for t in re.findall(r"[a-z0-9]+", question.lower()) if t not in store.QWORDS]
171
+ years = [t for t in toks if t.isdigit() and len(t) == 4 and 1000 <= int(t) <= 2100]
172
+ if years and len(toks) > len(years) + 1:
173
+ toks = [t for t in toks if t not in years] # keep the year out of the AND query; coverage handles ranges
174
+ syn: dict[str, list[str]] = {}
175
+ for t in dict.fromkeys(toks):
176
+ alts: list[str] = []
177
+ if t in ORDINALS:
178
+ alts += list(ORDINALS[t])
179
+ if t in DIGITS:
180
+ alts += list(DIGITS[t])
181
+ if t in NOUN_SYN:
182
+ alts += list(NOUN_SYN[t])
183
+ if t not in store.QWORDS and len(t) >= 2 and store.df(t) <= 100000: # entity-like tokens only, not "point"/"prime"
184
+ rows = store.con.execute("SELECT a.doc_id, d.n_alias FROM alias a JOIN doc d ON d.id=a.doc_id WHERE a.alias=? ORDER BY d.n_alias DESC LIMIT 1", (t,)).fetchall()
185
+ # short tokens ("uk") only expand when they are the name of a very popular entity
186
+ if rows and (rows[0][1] >= 5 if len(t) >= 4 else rows[0][1] >= 20):
187
+ for a in store.doc_aliases(rows[0][0], exclude=t, limit=20):
188
+ # skip near-misspellings (typo redirects) and anything already present; phrases ("united kingdom") are fine
189
+ if a == t or len(a) < 3 or a in alts or _edit_close(a, t) or len(a.split()) > 3:
190
+ continue
191
+ alts.append(a)
192
+ if len(alts) >= 5:
193
+ break
194
+ if alts:
195
+ syn[t] = alts[:5]
196
+ return list(dict.fromkeys(toks)), syn
197
+
198
+ def retrieve(store: Store, question: str, n_sentences: int = 12, n_passages: int = 40, per_passage: int = 2, leads: int = 1, pool: int = 48, _pool_only: bool = False) -> tuple[list[Evidence], dict]:
199
+ """1) anchors: alias hits ranked by popularity (top 3 docs); 2) first lead sentence of the top anchored docs;
200
+ 3) BM25 restricted to anchored docs (scored in Python) merged with global BM25;
201
+ 4) from each ranked passage take only its best-overlapping sentence(s), so the block spans many passages."""
202
+ anchors = store.anchors(question, top=3)
203
+ anchor_ids = [d for d, _, _ in anchors]
204
+ terms = set(_terms(store, question))
205
+ ev: list[Evidence] = []
206
+ seen_sent: set[int] = set()
207
+ from .rerank import get as _ranker
208
+ cap = pool if _ranker() is not None else n_sentences # with a ranker: gather a larger pool, let it pick the best n
209
+ def add(row, pid, score):
210
+ sid, doc_id, section, idx, text, title = row
211
+ if sid in seen_sent or len(ev) >= cap:
212
+ return
213
+ seen_sent.add(sid)
214
+ ev.append(Evidence(tag=f"E{len(ev)+1}", sent_id=sid, doc_id=doc_id, title=title, section=section, text=text, passage_id=pid, score=score))
215
+ # anchored docs are short (lead sections): include the start of the lead of the top doc (4) and the second (2), but only
216
+ # for anchors with some popularity (>= 2 names pointing at them), so a one-redirect film title cannot take the slots.
217
+ # The answering sentence often shares no words with the question ("It is a tree endemic to Peninsular Malaysia.").
218
+ for i, (d, _, pop) in enumerate(anchors[:2]):
219
+ if pop < 2 and len(anchors) > 1:
220
+ continue
221
+ if store.is_disambiguation(d):
222
+ picked = store.disambiguate(d, question)
223
+ if picked:
224
+ d = picked
225
+ for row in store.lead_sentences(d, n=4 if i == 0 else 2):
226
+ add(row, -1, -100.0)
227
+ ranked: list[tuple[int, float]] = []
228
+ seen_p = set()
229
+ # sentence overlap uses the question terms plus their synonyms (ordinal forms, siam, monarch, ...)
230
+ terms_plan, syn = _plan(store, question, anchors)
231
+ terms_all = set(terms) | {a for alts in syn.values() for a in alts}
232
+ if anchor_ids:
233
+ scored = []
234
+ for d in anchor_ids:
235
+ for pid, text in store.doc_passages(d):
236
+ hit = _overlap(terms_all, text)
237
+ if hit:
238
+ scored.append((pid, -30.0 - 30.0 * hit / max(1, len(terms_all)))) # competitive with global bm25 scores
239
+ scored.sort(key=lambda x: x[1])
240
+ for pid, sc in scored[:8]:
241
+ if pid not in seen_p:
242
+ seen_p.add(pid); ranked.append((pid, sc))
243
+ for pid, sc in store.bm25(question, limit=n_passages, terms=terms_plan, synonyms=syn):
244
+ if pid not in seen_p:
245
+ seen_p.add(pid); ranked.append((pid, sc))
246
+ # dense candidates (semantic match: "top scorer of all time" ~ "all-time record goalscorer"); the ranker arbitrates
247
+ from .dense import search as dense_search
248
+ for rank_i, (pid, sim) in enumerate(dense_search(question, k=n_passages)):
249
+ if pid not in seen_p:
250
+ seen_p.add(pid); ranked.append((pid, -40.0 * sim - 5.0 + 0.5 * rank_i)) # map cosine ~0.6-0.9 onto the bm25 score range
251
+ ranked.sort(key=lambda x: x[1])
252
+ # pass 1: best sentence(s) of each passage; pass 2: remaining sentences of the top passages if room is left
253
+ leftovers = []
254
+ for pid, score in ranked:
255
+ if len(ev) >= cap:
256
+ break
257
+ rows = store.passage_sentences(pid)
258
+ rows_scored = sorted(rows, key=lambda r: -_overlap(terms_all, r[4]))
259
+ k = per_passage + 1 if (rows and rows[0][1] in anchor_ids) else per_passage # anchored docs: one extra sentence
260
+ for row in rows_scored[:k]:
261
+ add(row, pid, score)
262
+ leftovers.extend((row, pid, score) for row in rows_scored[k:])
263
+ for row, pid, score in leftovers:
264
+ if len(ev) >= cap:
265
+ break
266
+ add(row, pid, score)
267
+ qterms0 = [t for t in terms if t not in store.QWORDS and len(t) > 3]
268
+ weights = {t: term_weight(store, t) for t in qterms0}
269
+ if _pool_only:
270
+ return ev, {"anchors": {d: a for d, a, _ in anchors}, "anchor_pop": {d: n for d, _, n in anchors}, "plan": (terms_plan, syn),
271
+ "terms": terms, "qterms0": qterms0, "weights": weights, "anchor_ids": anchor_ids}
272
+ n_bridged = bridge(store, question, ev, set(terms), anchor_ids, weights=weights) # question terms only, not their synonyms
273
+ from .rerank import rerank
274
+ hints = [a for alts in syn.values() for a in alts if " " not in a][:8]
275
+ pool_sids = [e.sent_id for e in ev]
276
+ ev = rerank(question, ev, keep=None, hints=hints) # rank the whole pool; truncate only after the coverage sort
277
+ # coverage-aware ordering: a candidate that accounts for every question term (itself or via its bridge) outranks one
278
+ # that is merely about the entity; ties keep the ranker's order. Synonym-covered terms count as covered.
279
+ qterms = qterms0
280
+ mode = os.environ.get("GSE_COV_SORT", "rare") # off | rare (only rare-term misses demote) | all
281
+ def missing_weight(e):
282
+ hay = f"{e.title} {e.text} {e.hop_text()}"
283
+ miss = [t for t in qterms if not (_covers(hay, t) or any(_covers(hay, a) for a in syn.get(t, [])))]
284
+ if mode == "rare":
285
+ miss = [t for t in miss if weights[t] >= 1.0]
286
+ return round(sum(weights[t] for t in miss), 2)
287
+ # coverage promotes fully-covering candidates to the front, but only within the ranker's top band: coverage is a
288
+ # verification signal, the ranker is the retrieval signal, and a gold sentence that paraphrases the question
289
+ # must not be pushed out of the block by a constraint word it happens not to contain
290
+ band = ev[:n_sentences + 8]
291
+ if mode != "off":
292
+ band.sort(key=missing_weight)
293
+ cov = [(e.tag, missing_weight(e), len(e.bridges), e.title) for e in band]
294
+ ev = band[:n_sentences]
295
+ for i, e in enumerate(ev):
296
+ e.tag = f"E{i+1}"
297
+ info = {"anchors": {d: a for d, a, _ in anchors}, "anchor_pop": {d: n for d, _, n in anchors}, "n_passages": len(ranked), "plan": (terms_plan, syn), "bridged": n_bridged, "coverage": cov, "weights": weights, "pool_sids": pool_sids}
298
+ return ev, info
299
+
300
+
301
+ def retrieve_planned(store: Store, question: str, p: dict, n_sentences: int = 16, pool: int = 48) -> tuple[list[Evidence], dict]:
302
+ """Execute a retrieval plan (see planner.py). Generic: entities -> anchors; the hypothetical answer sentence and
303
+ search terms -> lexical + dense candidates; hops -> extra candidate queries; constraints -> what must be covered
304
+ (by the sentence itself, its article lead, or a bridge). The rankers then see the question AND the hypothetical."""
305
+ from .rerank import rerank, get as _ranker
306
+ from .dense import search as dense_search
307
+ ents = p.get("entities") or []
308
+ anchors = []
309
+ for ent in ents[:4]:
310
+ d = store.resolve_entity(ent, context=question)
311
+ if d and d not in anchors:
312
+ anchors.append(d)
313
+ hyp = (p.get("hypothetical") or "").replace("____", " ").strip()
314
+ inferred: list[int] = []
315
+ if not anchors and hyp:
316
+ # describe-then-name (design §15.9 step 4): the question describes its subject instead of naming it ("the dwarf in
317
+ # game of thrones"), so no alias resolves. The articles the hypothetical answer sentence lands in become the anchors,
318
+ # and their leads and passages are searched exactly as a named entity's would be. Generic: no entity lists involved.
319
+ votes: dict[int, float] = {}
320
+ for i, (pid, sim) in enumerate(dense_search(hyp, k=12)):
321
+ row = store.con.execute("SELECT doc_id FROM passage WHERE id=?", (pid,)).fetchone()
322
+ if row:
323
+ votes[row[0]] = votes.get(row[0], 0.0) + (12 - i) * max(sim, 0.0)
324
+ inferred = [d for d, _ in sorted(votes.items(), key=lambda x: -x[1])[:2]]
325
+ anchors = list(inferred)
326
+ pop = dict(store.con.execute(f"SELECT id, n_alias FROM doc WHERE id IN ({','.join('?'*len(anchors))})", anchors).fetchall()) if anchors else {}
327
+ anchors.sort(key=lambda d: -pop.get(d, 0))
328
+ terms_plan = [t.lower() for t in (p.get("search_terms") or [])]
329
+ # what must be covered for an answer to count as verified: the planner's constraint and entity words, but only
330
+ # those traceable to the user's own question. The model may expand ("Rama IV", "1997 to 2007") for SEARCH, but it
331
+ # also invents constraints; verification stays grounded in what the user actually asked.
332
+ q_words = set(re.findall(r"[a-z0-9]+", _fold(question)))
333
+ cons, forms_by_word = [], {}
334
+ for c in (p.get("constraints") or []):
335
+ if isinstance(c, dict):
336
+ must = str(c.get("must") or ""); forms = [str(f) for f in (c.get("forms") or []) if f]
337
+ else:
338
+ must, forms = str(c), []
339
+ words = [w for w in re.findall(r"[a-z0-9]+", _fold(must)) if w not in store.QWORDS and len(w) > 2 and w in q_words]
340
+ cons += words
341
+ for w in words: # the model's alternative wordings count as covering the question's word
342
+ forms_by_word.setdefault(w, []).extend(_fold(f) for f in forms)
343
+ cons_words = cons
344
+ ent_words = [w for e in ents for w in re.findall(r"[a-z0-9]+", _fold(e)) if w not in store.QWORDS and len(w) > 2 and w in q_words]
345
+ required = list(dict.fromkeys(cons_words + ent_words))
346
+ ev: list[Evidence] = []; seen: set[int] = set()
347
+ cap = pool if _ranker() is not None else n_sentences
348
+ def add(row, pid, score):
349
+ sid, doc_id, section, idx, text, title = row
350
+ if sid in seen or len(ev) >= cap:
351
+ return
352
+ seen.add(sid); ev.append(Evidence(tag=f"E{len(ev)+1}", sent_id=sid, doc_id=doc_id, title=title, section=section, text=text, passage_id=pid, score=score))
353
+ for i, d in enumerate(anchors[:2]):
354
+ for row in store.lead_sentences(d, n=4 if i == 0 else 2):
355
+ add(row, -1, -100.0)
356
+ ranked: list[tuple[int, float]] = []; seen_p = set()
357
+ def take(pairs, bonus=0.0):
358
+ for pid, sc in pairs:
359
+ if pid not in seen_p:
360
+ seen_p.add(pid); ranked.append((pid, sc + bonus))
361
+ # anchored docs' own passages scored by overlap with search terms + constraint words
362
+ overlap_terms = set(terms_plan + required)
363
+ for d in anchors[:3]:
364
+ scored = []
365
+ for pid, text in store.doc_passages(d):
366
+ hit = sum(1 for t in overlap_terms if t and t in text.lower())
367
+ if hit:
368
+ scored.append((pid, -30.0 - 30.0 * hit / max(1, len(overlap_terms))))
369
+ take(sorted(scored, key=lambda x: x[1])[:8])
370
+ # lexical: the plan's own search terms (already in corpus wording), then the raw question
371
+ if terms_plan:
372
+ take(store.bm25(question, limit=30, terms=terms_plan))
373
+ take(store.bm25(question, limit=20))
374
+ # dense: the hypothetical answer sentence is the strongest query we have; the question and each hop add recall
375
+ if hyp:
376
+ take([(pid, -40.0 * sim - 8.0 + 0.5 * i) for i, (pid, sim) in enumerate(dense_search(hyp, k=40))])
377
+ take([(pid, -40.0 * sim - 5.0 + 0.5 * i) for i, (pid, sim) in enumerate(dense_search(question, k=20))])
378
+ for hq in (p.get("hops") or [])[:3]:
379
+ take([(pid, -40.0 * sim - 4.0 + 0.5 * i) for i, (pid, sim) in enumerate(dense_search(hq, k=10))])
380
+ ranked.sort(key=lambda x: x[1])
381
+ leftovers = []
382
+ for pid, score in ranked:
383
+ if len(ev) >= cap:
384
+ break
385
+ rows = store.passage_sentences(pid)
386
+ rows_scored = sorted(rows, key=lambda r: -_overlap(overlap_terms, r[4]))
387
+ k = 3 if (rows and rows[0][1] in anchors) else 2
388
+ for row in rows_scored[:k]:
389
+ add(row, pid, score)
390
+ leftovers.extend((row, pid, score) for row in rows_scored[k:])
391
+ for row, pid, score in leftovers:
392
+ if len(ev) >= cap:
393
+ break
394
+ add(row, pid, score)
395
+ # UNION with the heuristic candidates: the plan adds recall (hypothetical sentence, hops, entity anchors), it must
396
+ # never remove what plain anchoring and keyword search would have found. The ranker, not the generator, decides.
397
+ h_ev, h_info = retrieve(store, question, n_sentences=n_sentences, pool=pool, _pool_only=True)
398
+ for e in h_ev:
399
+ if e.sent_id not in seen and len(ev) < 2 * pool:
400
+ seen.add(e.sent_id); e.tag = f"E{len(ev)+1}"; ev.append(e)
401
+ for d in h_info.get("anchor_ids", []):
402
+ if d not in anchors:
403
+ anchors.append(d)
404
+ syn_h = dict(h_info.get("plan", ([], {}))[1])
405
+ for w, fs in forms_by_word.items():
406
+ syn_h[w] = list(dict.fromkeys(syn_h.get(w, []) + fs))
407
+ # hops/constraints that a candidate lacks: bridge through the entities it names (same mechanism, plan-driven terms)
408
+ req_all = list(dict.fromkeys(required + [t for t in h_info.get("qterms0", []) if t not in required]))
409
+ # a word the planner marked as a constraint is a hard requirement whatever its corpus frequency ("all time", "most"):
410
+ # the model judged it to matter; rarity weighting only applies to the remaining question words
411
+ weights = {t: (1.0 if t in cons_words else term_weight(store, t)) for t in req_all}
412
+ # the hypothetical was for RETRIEVAL; the rankers judge the plain question they were trained on.
413
+ # Rank first, bridge the ranked top band (the pool is large after the union), then rank again with hops attached.
414
+ pool_sids = [e.sent_id for e in ev]
415
+ ev = rerank(question, ev, keep=None, hints=terms_plan[:8])
416
+ n_bridged = bridge(store, question, ev[:32], set(req_all), anchors, weights=weights) if req_all else 0
417
+ if n_bridged:
418
+ ev = rerank(question, ev, keep=None, hints=terms_plan[:8])
419
+ def missing_weight(e):
420
+ hay = f"{e.title} {e.text} {e.hop_text()}"
421
+ return round(sum(weights[t] for t in req_all if weights[t] >= 1.0 and not (_covers(hay, t) or any(_covers(hay, a) for a in syn_h.get(t, [])))), 2)
422
+ band = ev[:n_sentences + 8]
423
+ band.sort(key=missing_weight)
424
+ ev = band[:n_sentences]
425
+ for i, e in enumerate(ev):
426
+ e.tag = f"E{i+1}"
427
+ info = {"anchors": {d: store.doc(d)[2] for d in anchors[:3]}, "anchor_pop": pop, "n_passages": len(ranked),
428
+ "plan": (terms_plan, syn_h), "bridged": n_bridged, "required": req_all, "hard": cons_words, "planner": p, "pool_sids": pool_sids, "inferred_anchors": inferred}
429
+ return ev, info
code/gse_mini/serve.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persistent GSE-mini service: holds the store and ranker in memory, calls llama-server for generation.
2
+
3
+ GSE_RANKER=/root/models/gse-ranker python -m gse_mini.serve --store /root/data/store.sqlite --port 8090
4
+ curl -s 'localhost:8090/ask?q=who+discovered+penicillin'
5
+ """
6
+ from __future__ import annotations
7
+ import argparse, json, time
8
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
9
+ from urllib.parse import urlparse, parse_qs
10
+ from .store import Store
11
+ from .answer import answer
12
+ from .rerank import get as get_ranker
13
+
14
+ def main():
15
+ ap = argparse.ArgumentParser(); ap.add_argument("--store", required=True); ap.add_argument("--port", type=int, default=8090)
16
+ ap.add_argument("--llama", default="http://127.0.0.1:8089"); a = ap.parse_args()
17
+ store = Store(a.store); ranker = get_ranker()
18
+ print(f"[serve] store ready; ranker={'on' if ranker else 'off'}; llama={a.llama}", flush=True)
19
+
20
+ class H(BaseHTTPRequestHandler):
21
+ def log_message(self, *args): pass
22
+ def do_GET(self):
23
+ u = urlparse(self.path); qs = parse_qs(u.query)
24
+ if u.path == "/health":
25
+ body = {"ok": True, "ranker": ranker is not None}
26
+ elif u.path == "/ask" and qs.get("q"):
27
+ t = time.time(); r = answer(store, a.llama, qs["q"][0], n_sentences=16); r["ms_total"] = round(1000 * (time.time() - t))
28
+ body = r
29
+ else:
30
+ self.send_response(404); self.end_headers(); return
31
+ data = json.dumps(body, ensure_ascii=False).encode()
32
+ self.send_response(200); self.send_header("Content-Type", "application/json; charset=utf-8"); self.send_header("Content-Length", str(len(data))); self.end_headers()
33
+ self.wfile.write(data)
34
+ ThreadingHTTPServer(("0.0.0.0", a.port), H).serve_forever()
35
+
36
+ if __name__ == "__main__":
37
+ main()
code/gse_mini/store.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLite sentence/passage store with FTS5 BM25 and an alias table.
2
+
3
+ Corpus-agnostic: every source adapter yields the same `doc` records
4
+ {"kb": str, "title": str, "path": str, "sections": [(section_name, text), ...], "aliases": [str, ...]}
5
+ and the store turns them into sentences (the quotable units), passages (the BM25 units) and aliases.
6
+ """
7
+ from __future__ import annotations
8
+ import re, sqlite3, time
9
+ from typing import Iterable
10
+
11
+ SCHEMA = """
12
+ PRAGMA journal_mode=WAL;
13
+ PRAGMA synchronous=OFF;
14
+ CREATE TABLE IF NOT EXISTS doc(id INTEGER PRIMARY KEY, kb TEXT, title TEXT, path TEXT, n_alias INT DEFAULT 0, n_sent INT DEFAULT 0);
15
+ CREATE TABLE IF NOT EXISTS sent(id INTEGER PRIMARY KEY, doc_id INT, section TEXT, idx INT, text TEXT);
16
+ CREATE TABLE IF NOT EXISTS passage(id INTEGER PRIMARY KEY, doc_id INT, section TEXT, sent_from INT, sent_to INT);
17
+ CREATE VIRTUAL TABLE IF NOT EXISTS passage_fts USING fts5(text, tokenize='porter unicode61');
18
+ CREATE TABLE IF NOT EXISTS alias(alias TEXT, doc_id INT, kind TEXT);
19
+ CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
20
+ """
21
+ INDEXES = """
22
+ CREATE INDEX IF NOT EXISTS alias_idx ON alias(alias);
23
+ CREATE UNIQUE INDEX IF NOT EXISTS doc_path ON doc(kb, path);
24
+ CREATE INDEX IF NOT EXISTS sent_doc ON sent(doc_id, idx);
25
+ CREATE INDEX IF NOT EXISTS passage_doc ON passage(doc_id);
26
+ """
27
+
28
+ _WS = re.compile(r"\s+")
29
+ try:
30
+ from blingfire import text_to_sentences as _bf
31
+ def split_sentences(text: str) -> list[str]:
32
+ return [s for s in _bf(text).split("\n") if s.strip()]
33
+ except Exception: # pragma: no cover
34
+ _SENT = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9\"'(\[])")
35
+ def split_sentences(text: str) -> list[str]:
36
+ return [s for s in _SENT.split(text) if s.strip()]
37
+
38
+ def norm_alias(s: str) -> str:
39
+ s = s.lower().replace("_", " ")
40
+ s = re.sub(r"[^\w\s'-]", " ", s)
41
+ return _WS.sub(" ", s).strip()
42
+
43
+ def clean_sentence(s: str) -> str:
44
+ s = _WS.sub(" ", s).strip()
45
+ s = re.sub(r"\[\d+\]|\[citation needed\]|\[[a-z]\]", "", s) # leftover reference marks
46
+ return s.strip()
47
+
48
+
49
+ class StoreWriter:
50
+ """Streams docs into the store. Not thread-safe; feed it from one process."""
51
+ def __init__(self, path: str, passage_words: int = 60, passage_sents: int = 3):
52
+ self.con = sqlite3.connect(path)
53
+ self.con.executescript(SCHEMA)
54
+ self.cur = self.con.cursor()
55
+ self.passage_words, self.passage_sents = passage_words, passage_sents
56
+ self.n_docs = self.n_sents = self.n_pass = 0
57
+ self._pending_redirects: list[tuple[str, str, str]] = [] # (kb, alias, target_path)
58
+
59
+ def add_doc(self, d: dict) -> int | None:
60
+ sents_rows, pass_rows, title = [], [], d["title"]
61
+ for section, text in d["sections"]:
62
+ sents = [clean_sentence(s) for s in split_sentences(text)]
63
+ sents = [s for s in sents if 3 <= len(s.split()) <= 120]
64
+ if not sents:
65
+ continue
66
+ sents_rows.append((section, sents))
67
+ if not sents_rows:
68
+ return None
69
+ self.cur.execute("INSERT INTO doc(kb,title,path) VALUES (?,?,?)", (d["kb"], title, d["path"]))
70
+ doc_id = self.cur.lastrowid
71
+ idx = 0
72
+ for section, sents in sents_rows:
73
+ first_id = None; ids = []
74
+ for s in sents:
75
+ self.cur.execute("INSERT INTO sent(doc_id,section,idx,text) VALUES (?,?,?,?)", (doc_id, section, idx, s))
76
+ ids.append(self.cur.lastrowid); idx += 1
77
+ # group into passages
78
+ buf, buf_ids, words = [], [], 0
79
+ def flush():
80
+ nonlocal buf, buf_ids, words
81
+ if not buf: return
82
+ self.cur.execute("INSERT INTO passage(doc_id,section,sent_from,sent_to) VALUES (?,?,?,?)",
83
+ (doc_id, section, buf_ids[0], buf_ids[-1]))
84
+ pid = self.cur.lastrowid
85
+ self.cur.execute("INSERT INTO passage_fts(rowid,text) VALUES (?,?)",
86
+ (pid, f"{title}. {section}. " + " ".join(buf) if section != "lead" else f"{title}. " + " ".join(buf)))
87
+ self.n_pass += 1
88
+ buf, buf_ids, words = [], [], 0
89
+ for s, sid in zip(sents, ids):
90
+ buf.append(s); buf_ids.append(sid); words += len(s.split())
91
+ if words >= self.passage_words or len(buf) >= self.passage_sents:
92
+ flush()
93
+ flush()
94
+ self.n_sents += idx
95
+ alias_rows = {(norm_alias(title), "title")}
96
+ for a in d.get("aliases", []):
97
+ na = norm_alias(a)
98
+ if na and na != norm_alias(title):
99
+ alias_rows.add((na, "alias"))
100
+ self.cur.executemany("INSERT INTO alias(alias,doc_id,kind) VALUES (?,?,?)", [(a, doc_id, k) for a, k in alias_rows])
101
+ self.n_docs += 1
102
+ if self.n_docs % 2000 == 0:
103
+ self.con.commit()
104
+ return doc_id
105
+
106
+ def add_redirect(self, kb: str, alias: str, target_path: str):
107
+ self._pending_redirects.append((kb, alias, target_path))
108
+
109
+ def finalize(self, meta: dict | None = None):
110
+ self.con.commit()
111
+ self.con.executescript(INDEXES)
112
+ if self._pending_redirects:
113
+ self.cur.execute("CREATE TEMP TABLE rd(kb TEXT, alias TEXT, path TEXT)")
114
+ self.cur.executemany("INSERT INTO rd VALUES (?,?,?)", [(k, norm_alias(a), p) for k, a, p in self._pending_redirects])
115
+ self.cur.execute("INSERT INTO alias(alias,doc_id,kind) SELECT rd.alias, doc.id, 'redirect' FROM rd JOIN doc ON doc.kb=rd.kb AND doc.path=rd.path WHERE rd.alias != ''")
116
+ self.cur.execute("DROP TABLE rd")
117
+ self._pending_redirects.clear()
118
+ self.cur.execute("CREATE INDEX IF NOT EXISTS alias_doc ON alias(doc_id)")
119
+ self.cur.execute("UPDATE doc SET n_alias = (SELECT COUNT(*) FROM alias a WHERE a.doc_id = doc.id) WHERE n_alias = 0")
120
+ self.cur.execute("UPDATE doc SET n_sent = (SELECT COUNT(*) FROM sent s WHERE s.doc_id = doc.id) WHERE n_sent = 0")
121
+ self.cur.execute("INSERT INTO passage_fts(passage_fts) VALUES('optimize')")
122
+ for k, v in (meta or {}).items():
123
+ self.cur.execute("INSERT OR REPLACE INTO meta VALUES (?,?)", (k, str(v)))
124
+ self.cur.execute("INSERT OR REPLACE INTO meta VALUES ('built_at', ?)", (time.strftime("%Y-%m-%d %H:%M:%S"),))
125
+ self.con.commit()
126
+ self.con.execute("PRAGMA optimize")
127
+ self.con.close()
128
+
129
+
130
+ class Store:
131
+ """Read-only access used by retrieval, training data generation and the runtime."""
132
+ STOP = set("a an the of in on at to for by with and or is are was were be been being who what when where which how why did does do that this these those it its as from into than then there their his her he she they them".split())
133
+ QWORDS = STOP | set("many much can could should would will i you my me your have has had not no about tell explain give list name wont dont cant whats isnt doesnt didnt im ive".split())
134
+ # common English words that are also article titles; as single-token anchors they hijack retrieval ("build", "check", "water")
135
+ COMMON = set("""build check water sunlight design purify come down turn make use get run work time way day year people man woman
136
+ world life hand part child eye place week case point government company number group problem fact money lot right study book job
137
+ word business issue side kind head house service friend father power hour game line end member law car city community name
138
+ president team minute idea kid body information back parent face others level office door health person art war history party
139
+ result change morning reason research girl guy moment air teacher force education foot boy age policy process music market sense
140
+ nation plan college interest death experience effect class control care field development role effort rate heart drug show leader
141
+ light voice wife police mind price report decision son view relationship road arm difference value building action model season
142
+ society tax director position player record paper space ground form event official matter center couple site project activity
143
+ star table need court oil situation cost industry figure street image phone data picture practice piece land product doctor wall
144
+ patient worker news test movie north love support technology step baby computer type attention film tree source direction
145
+ language period energy season bed order fire stove battery screen phone tyre tire bike toilet cooker river mountain element""".split())
146
+
147
+ def __init__(self, path: str):
148
+ self.con = sqlite3.connect(f"file:{path}?mode=ro", uri=True, check_same_thread=False)
149
+ self.con.execute("PRAGMA cache_size=-262144") # 256 MB page cache
150
+ self.con.execute("PRAGMA mmap_size=4294967296")
151
+
152
+ def doc(self, doc_id: int):
153
+ return self.con.execute("SELECT id,kb,title,path FROM doc WHERE id=?", (doc_id,)).fetchone()
154
+
155
+ def sentence(self, sid: int):
156
+ return self.con.execute("SELECT s.id,s.doc_id,s.section,s.idx,s.text,d.title FROM sent s JOIN doc d ON d.id=s.doc_id WHERE s.id=?", (sid,)).fetchone()
157
+
158
+ def passage_sentences(self, pid: int):
159
+ return self.con.execute(
160
+ "SELECT s.id,s.doc_id,s.section,s.idx,s.text,d.title FROM passage p JOIN sent s ON s.id BETWEEN p.sent_from AND p.sent_to "
161
+ "JOIN doc d ON d.id=s.doc_id WHERE p.id=? ORDER BY s.id", (pid,)).fetchall()
162
+
163
+ def alias_docs(self, question: str, max_ngram: int = 4) -> dict[int, str]:
164
+ """Exact alias hits over the question's word n-grams. Returns {doc_id: alias}. Longest matches win.
165
+ Generic phrases are skipped: n-grams made only of question/stop words, or starting with one ("who was", "how do i")."""
166
+ words = norm_alias(question).split()
167
+ hits: dict[int, str] = {}
168
+ self._kind: dict[int, str] = {}
169
+ taken = [False] * len(words)
170
+ for n in range(min(max_ngram, len(words)), 0, -1):
171
+ for i in range(0, len(words) - n + 1):
172
+ if any(taken[i:i + n]):
173
+ continue
174
+ toks = words[i:i + n]; g = " ".join(toks)
175
+ if all(t in self.QWORDS for t in toks) or (n > 1 and toks[0] in self.QWORDS and toks[0] not in ("the", "a", "an")):
176
+ continue
177
+ if n == 1 and (g in self.QWORDS or len(g) < 3):
178
+ continue
179
+ rows = self.con.execute("SELECT doc_id, kind FROM alias WHERE alias=? LIMIT 5", (g,)).fetchall()
180
+ if rows:
181
+ for d, kind in rows:
182
+ if d not in hits or (kind == "title" and self._kind.get(d) != "title"):
183
+ hits[d] = g; self._kind[d] = kind
184
+ for j in range(i, i + n): taken[j] = True
185
+ return hits
186
+
187
+ def anchors(self, question: str, top: int = 3) -> list[tuple[int, str, int]]:
188
+ """Alias hits ranked by the doc's alias count (titles + redirects pointing at it: a popularity proxy)."""
189
+ hits = self.alias_docs(question)
190
+ if not hits:
191
+ return []
192
+ caps = {w.lower() for w in re.findall(r"\b[A-Z][\w'-]+", question)}
193
+ ids = list(hits)
194
+ rows = self.con.execute(f"SELECT id, n_alias FROM doc WHERE id IN ({','.join('?'*len(ids))})", ids).fetchall()
195
+ pop = {d: n for d, n in rows}
196
+ def keep(d, alias):
197
+ """Junk anchors are common English words that happen to be titles ("second", "naturally", "the head").
198
+ Keep: capitalised proper nouns; single tokens with df <= 50k; phrases with a rare token, or that are an
199
+ article's exact title with some popularity, or fully capitalised in the question."""
200
+ toks = [t for t in alias.split() if t not in ("the", "a", "an")]
201
+ if not toks or any(t in self.COMMON for t in toks if len(toks) == 1):
202
+ return False
203
+ if len(toks) == 1:
204
+ t = toks[0]
205
+ # a lowercase single word anchors only when it is rare, or moderately rare AND the article it names is a
206
+ # notable entity (several redirects point at it): "kentucky" yes, "lose" / "drove" / "scout" no
207
+ return t in caps or self.df(t) <= 5000 or (self.df(t) <= 50000 and pop.get(d, 0) >= 3)
208
+ if min((self.df(t) or 1) for t in toks) <= 100000:
209
+ return True
210
+ if self._kind.get(d) == "title" and pop.get(d, 0) >= 2:
211
+ return True
212
+ return all(t in caps or t.isdigit() for t in toks)
213
+ hits = {d: a for d, a in hits.items() if keep(d, a)}
214
+ if not hits:
215
+ return []
216
+ ranked = sorted(hits, key=lambda d: (-(pop.get(d, 0)), d))
217
+ return [(d, hits[d], pop.get(d, 0)) for d in ranked[:top]]
218
+
219
+ def doc_aliases(self, doc_id: int, exclude: str = "", limit: int = 6) -> list[str]:
220
+ """Other short names of a doc (title, redirects, aliases): "siam", "kingdom of thailand" for Thailand."""
221
+ rows = self.con.execute("SELECT alias, kind FROM alias WHERE doc_id=? LIMIT 200", (doc_id,)).fetchall()
222
+ ex = set(exclude.split())
223
+ out = []
224
+ for a, kind in sorted(rows, key=lambda r: (r[1] != "title", len(r[0]))):
225
+ toks = a.split()
226
+ if a == exclude or not toks or len(toks) > 3 or set(toks) <= ex or any(t in self.QWORDS and t not in ("of", "the") for t in toks):
227
+ continue
228
+ if any(len(t) < 3 for t in toks) and kind != "title":
229
+ continue
230
+ out.append(a)
231
+ if len(out) >= limit:
232
+ break
233
+ return out
234
+
235
+ def doc_passages(self, doc_id: int):
236
+ """All passages of a doc with their text (docs are short: lead sections in the mini corpus)."""
237
+ return self.con.execute(
238
+ "SELECT p.id, f.text FROM passage p JOIN passage_fts f ON f.rowid = p.id WHERE p.doc_id=? ORDER BY p.id", (doc_id,)).fetchall()
239
+
240
+ def is_disambiguation(self, doc_id: int) -> bool:
241
+ row = self.doc(doc_id)
242
+ if row and "(disambiguation)" in (row[2] or "").lower():
243
+ return True
244
+ lead = self.lead_sentences(doc_id, n=1)
245
+ return bool(lead) and ("may refer to" in lead[0][4].lower() or "may also refer to" in lead[0][4].lower())
246
+
247
+ def disambiguate(self, doc_id: int, context: str) -> int | None:
248
+ """A disambiguation page lists the candidate articles; pick the one whose lead best covers the question's words
249
+ (generic: "Hugo Bueno" + "club ... play" -> the footballer, not the disambiguation page itself)."""
250
+ from .retrieve import _CAP, _fold
251
+ ctx = {t for t in re.findall(r"[a-z0-9]+", _fold(context)) if t not in self.QWORDS and len(t) > 2}
252
+ text = " ".join(r[4] for r in self.lead_sentences(doc_id, n=12))
253
+ best, seen = None, set()
254
+ for m in _CAP.findall(text)[:30]:
255
+ key = norm_alias(m)
256
+ if not key or key in seen or key in self.QWORDS:
257
+ continue
258
+ seen.add(key)
259
+ rows = self.con.execute("SELECT a.doc_id FROM alias a JOIN doc d ON d.id=a.doc_id WHERE a.alias=? AND a.doc_id!=? ORDER BY d.n_alias DESC LIMIT 1", (key, doc_id)).fetchall()
260
+ if not rows or self.is_disambiguation(rows[0][0]):
261
+ continue
262
+ lead = " ".join(r[4] for r in self.lead_sentences(rows[0][0], n=3)).lower()
263
+ score = sum(1 for t in ctx if t in lead)
264
+ if best is None or score > best[0]:
265
+ best = (score, rows[0][0])
266
+ return best[1] if best and best[0] > 0 else None
267
+
268
+ def resolve_entity(self, name: str, context: str = "") -> int | None:
269
+ """Doc id for an entity name from the planner ("United Kingdom", "Rúben Neves"): exact alias, then the
270
+ longest alias-matching n-gram inside the name, most popular doc wins; disambiguation pages are resolved
271
+ through the question's context."""
272
+ key = norm_alias(name)
273
+ if not key:
274
+ return None
275
+ rows = self.con.execute("SELECT a.doc_id FROM alias a JOIN doc d ON d.id=a.doc_id WHERE a.alias=? ORDER BY d.n_alias DESC LIMIT 3", (key,)).fetchall()
276
+ cands = [r[0] for r in rows]
277
+ if not cands:
278
+ hits = self.alias_docs(name)
279
+ if not hits:
280
+ return None
281
+ ids = list(hits)
282
+ pop = dict(self.con.execute(f"SELECT id, n_alias FROM doc WHERE id IN ({','.join('?'*len(ids))})", ids).fetchall())
283
+ cands = [max(ids, key=lambda d: (len(hits[d].split()), pop.get(d, 0)))]
284
+ d = cands[0]
285
+ if self.is_disambiguation(d):
286
+ picked = self.disambiguate(d, context or name)
287
+ if picked:
288
+ return picked
289
+ for alt in cands[1:]:
290
+ if not self.is_disambiguation(alt):
291
+ return alt
292
+ return d
293
+
294
+ def lead_sentences(self, doc_id: int, n: int = 2):
295
+ return self.con.execute(
296
+ "SELECT s.id,s.doc_id,s.section,s.idx,s.text,d.title FROM sent s JOIN doc d ON d.id=s.doc_id "
297
+ "WHERE s.doc_id=? AND s.section='lead' ORDER BY s.idx LIMIT ?", (doc_id, n)).fetchall()
298
+
299
+ _stemmer = None
300
+ def df(self, term: str) -> int:
301
+ """Document frequency of a (porter-stemmed) term from the FTS5 vocab table; 0 if unknown."""
302
+ if Store._stemmer is None:
303
+ try:
304
+ import Stemmer; Store._stemmer = Stemmer.Stemmer("porter")
305
+ except Exception:
306
+ Store._stemmer = False
307
+ t = Store._stemmer.stemWord(term) if Store._stemmer else term
308
+ try:
309
+ row = self.con.execute("SELECT doc FROM passage_vocab WHERE term=?", (t,)).fetchone()
310
+ except Exception:
311
+ return 0
312
+ return row[0] if row else 0
313
+
314
+ def fts_query(self, question: str) -> tuple[str, str]:
315
+ toks = [t for t in re.findall(r"[a-z0-9]+", question.lower()) if t not in self.STOP]
316
+ toks = toks[:12]
317
+ q_and = " AND ".join(f'"{t}"' for t in toks)
318
+ q_or = " OR ".join(f'"{t}"' for t in toks)
319
+ return q_and, q_or
320
+
321
+ def bm25(self, question: str, limit: int = 20, doc_ids: Iterable[int] | None = None, min_hits: int = 5,
322
+ terms: list[str] | None = None, synonyms: dict[str, list[str]] | None = None) -> list[tuple[int, float]]:
323
+ """Top passages (id, score; lower is better in FTS5 bm25), optionally restricted to doc ids.
324
+ `terms` may contain multi-word phrases; `synonyms` maps a term to alternatives OR-ed with it
325
+ (aliases of an anchored entity, ordinal forms). IDF-aware plan: rarest terms are required, common ones float."""
326
+ clean = lambda x: re.sub(r'["\x00-\x1f]', " ", str(x)).strip() # a stray quote in a planner term breaks the MATCH expression
327
+ if terms is None:
328
+ toks = [t for t in re.findall(r"[a-z0-9]+", question.lower()) if t not in self.QWORDS][:12]
329
+ else:
330
+ toks = [clean(t) for t in terms if clean(t)][:12]
331
+ toks = list(dict.fromkeys(toks))
332
+ if not toks:
333
+ return []
334
+ synonyms = synonyms or {}
335
+ def tdf(t): # df of a phrase = its rarest token
336
+ return min((self.df(x) or 0) for x in t.split()) if " " in t else self.df(t)
337
+ rare = sorted(toks, key=tdf)
338
+ def one(t):
339
+ alts = [a for a in dict.fromkeys(clean(x) for x in [t] + list(synonyms.get(t, []))) if a]
340
+ if not alts:
341
+ return None
342
+ return f'"{alts[0]}"' if len(alts) == 1 else "(" + " OR ".join(f'"{a}"' for a in alts) + ")"
343
+ q = lambda ts, op: f" {op} ".join(x for x in (one(t) for t in ts) if x)
344
+ queries = []
345
+ if len(toks) <= 6:
346
+ queries.append(q(toks, "AND"))
347
+ core = rare[:3]
348
+ queries.append(q(core, "AND"))
349
+ if len(core) >= 2:
350
+ queries.append(q(core[:2], "AND"))
351
+ usable = [t for t in core if 0 < tdf(t) <= 300000 or tdf(t) == 0][:3]
352
+ if usable:
353
+ queries.append(q(usable, "OR"))
354
+ queries = list(dict.fromkeys(queries))
355
+ if doc_ids:
356
+ queries.append(q(toks, "OR"))
357
+ out: list[tuple[int, float]] = []
358
+ seen = set()
359
+ for q in queries:
360
+ if len(out) >= min_hits:
361
+ break
362
+ if doc_ids:
363
+ ids = list(doc_ids)
364
+ sql = (f"SELECT f.rowid, bm25(passage_fts) AS s FROM passage_fts f JOIN passage p ON p.id=f.rowid "
365
+ f"WHERE passage_fts MATCH ? AND p.doc_id IN ({','.join('?'*len(ids))}) ORDER BY s LIMIT ?")
366
+ rows = self.con.execute(sql, (q, *ids, limit)).fetchall()
367
+ else:
368
+ rows = self.con.execute("SELECT rowid, bm25(passage_fts) AS s FROM passage_fts WHERE passage_fts MATCH ? ORDER BY s LIMIT ?", (q, limit)).fetchall()
369
+ for pid, s in rows:
370
+ if pid not in seen:
371
+ seen.add(pid); out.append((pid, s))
372
+ if len(out) >= limit:
373
+ break
374
+ return out[:limit]
375
+
376
+ def stats(self) -> dict:
377
+ g = lambda t: self.con.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
378
+ return {"docs": g("doc"), "sentences": g("sent"), "passages": g("passage"), "aliases": g("alias")}
code/gse_mini/verify.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic checks on a parsed answer. Cheap string tests, no model."""
2
+ from __future__ import annotations
3
+ import re
4
+ from .retrieve import Evidence
5
+
6
+ NUM_RE = re.compile(r"\d[\d,.\-/]*")
7
+ _GLUE_STOP = set("a an the of in on at to for by with and or is are was were be been being it its as from into than then there their his her he she they them that this these those which who what when where how why did does do".split())
8
+ CAP_RE = re.compile(r"\b(?:[A-Z][\w'-]+)(?:\s+[A-Z][\w'-]+)*")
9
+
10
+ def _norm(s: str) -> str:
11
+ return re.sub(r"[^\w\s]", " ", s.lower())
12
+
13
+ def coverage(question: str, e: Evidence, store=None, synonyms: dict | None = None, required: list[str] | None = None, hard: list[str] | None = None) -> list[str]:
14
+ """Question content terms the cited sentence does not account for (itself, its title, its bridge, its article's
15
+ first lead sentences, or a synonym/alias form). Very common terms (df > 500k, e.g. "play") are soft and ignored.
16
+ A 'verified' answer must leave this list empty."""
17
+ from .store import Store
18
+ from .retrieve import _covers, term_weight
19
+ qw = Store.QWORDS
20
+ terms = required if required is not None else [t for t in re.findall(r"[a-z0-9]+", question.lower()) if t not in qw and len(t) > 3]
21
+ hay = " ".join([e.text, e.title] + [f"{t} {x}" for _, t, x in getattr(e, "bridges", [])])
22
+ if store is not None:
23
+ hay += " " + " ".join(r[4] for r in store.lead_sentences(e.doc_id, n=4))
24
+ synonyms = synonyms or {}
25
+ out = []
26
+ for t in dict.fromkeys(terms):
27
+ if store is not None and t not in (hard or []) and term_weight(store, t) < 0.5:
28
+ continue
29
+ if _covers(hay, t) or any(_covers(hay, a) for a in synonyms.get(t, [])):
30
+ continue
31
+ out.append(t)
32
+ return out
33
+
34
+ def check(parts, ev: list[Evidence], question: str) -> dict:
35
+ """Returns {"ok": bool, "problems": [...], "refs": [...], "glue_tokens": int}"""
36
+ by_tag = {e.tag: e for e in ev}
37
+ problems, refs = [], []
38
+ for kind, val in parts:
39
+ if kind == "ref":
40
+ if val not in by_tag:
41
+ problems.append(f"invalid ref {val}")
42
+ else:
43
+ refs.append(val)
44
+ if not refs:
45
+ problems.append("no references")
46
+ # content-free glue: every number and capitalised name in the glue must come from the QUESTION. Names from the
47
+ # cited sentence are not allowed either: "The longest river in Africa is the Niger <q E11>" asserts a fact the quote
48
+ # may not support; the model's job is to frame the question and point, never to state.
49
+ allowed = _norm(question)
50
+ allowed_tokens = set(allowed.split())
51
+ glue_text = " ".join(val for kind, val in parts if kind == "glue")
52
+ # circular or padded framing ("the discovery of penicillin was instrumental in the discovery of penicillin"): a content
53
+ # word may appear at most once in the glue, and the glue stays short
54
+ gw = [w for w in re.findall(r"[a-z0-9]+", glue_text.lower()) if w not in _GLUE_STOP]
55
+ if len(gw) != len(set(gw)) or len(glue_text.split()) > 18:
56
+ problems.append("glue repeats content words or is too long")
57
+ for num in NUM_RE.findall(glue_text):
58
+ n = re.sub(r"[^\w]", "", num)
59
+ if n and n not in re.sub(r"[^\w\s]", "", allowed).split():
60
+ problems.append(f"number '{num}' not in question")
61
+ for name in CAP_RE.findall(glue_text):
62
+ toks = _norm(name).split()
63
+ if toks and toks[0] not in {"the", "a", "an", "i"} and any(t not in allowed_tokens for t in toks):
64
+ problems.append(f"name '{name}' not in question")
65
+ return {"ok": not problems, "problems": problems, "refs": refs, "glue_tokens": len(glue_text.split())}
code/local/bench_web.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Public benchmarks through the tiny-model web scaffold, graded the SimpleQA way (CORRECT / INCORRECT / NOT_ATTEMPTED by an LLM
3
+ judge) so the numbers are comparable to published frontier scores.
4
+ Benchmarks: simpleqa (google/simpleqa-verified, 1,000), popqa (akariasai/PopQA: 1,000 sampled from the 4,000 least popular
5
+ subjects, the paper's long tail), freshqa (bojanbabic/freshqa_08272025: 600, gold as of Aug 2025; fast-changing reported apart).
6
+ Judge: a local llama-server (Qwen3-4B-Instruct Q4) on :8097 with the SimpleQA grader rules. Two attempt policies are reported:
7
+ 'verified-only' (unverified best matches count as NOT_ATTEMPTED, the abstention the design is for) and 'all'.
8
+ .venv-local/bin/python local/bench_web.py --bench simpleqa --n 1000 --threads 8"""
9
+ import argparse, collections, json, os, random, re, sys, time, urllib.request
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
12
+ import webqa
13
+
14
+ def load(bench, n, seed):
15
+ from datasets import load_dataset
16
+ random.seed(seed); rows = []
17
+ if bench == "simpleqa":
18
+ for r in load_dataset("google/simpleqa-verified")["eval"]:
19
+ rows.append({"q": r["problem"], "answers": [r["answer"]], "group": r["topic"], "type": r["answer_type"]})
20
+ elif bench == "popqa":
21
+ d = sorted(load_dataset("akariasai/PopQA")["test"], key=lambda r: int(r["s_pop"]))[:4000]
22
+ for r in d:
23
+ rows.append({"q": r["question"], "answers": json.loads(r["possible_answers"]), "group": r["prop"], "type": "entity"})
24
+ elif bench == "freshqa":
25
+ ds = load_dataset("bojanbabic/freshqa_08272025")
26
+ for sp in ("test", "dev"):
27
+ for r in ds[sp]:
28
+ ans = [r[f"answer_{i}"] for i in range(10) if r.get(f"answer_{i}") and r[f"answer_{i}"] != "None"]
29
+ rows.append({"q": r["question"], "answers": ans, "group": r["fact_type"], "type": "false_premise" if str(r["false_premise"]) == "True" else r["num_hops"]})
30
+ else:
31
+ raise SystemExit("unknown bench")
32
+ random.shuffle(rows); return rows[:n]
33
+
34
+ GRADER = '\nYour job is to look at a question, a gold target, and a predicted answer, and then assign a grade of either ["CORRECT", "INCORRECT", "NOT_ATTEMPTED"].\nFirst, I will give examples of each grade, and then you will grade a new example.\n\n\nThe following are examples of CORRECT predicted answers.\n```\nQuestion: What are the names of Barack Obama\'s children?\nGold target: Malia Obama and Sasha Obama\nPredicted answer 1: sasha and malia obama\nPredicted answer 2: most people would say Malia and Sasha, but I\'m not sure and would have to double check\nPredicted answer 3: Barack Obama has two daughters. Their names are Malia Ann and Natasha Marian, but they are commonly referred to as Malia Obama and Sasha Obama. Malia was born on July 4, 1998, and Sasha was born on June 10, 2001.\n```\nThese predicted answers are all CORRECT because:\n - They fully contain the important information in the gold target.\n - They do not contain any information that contradicts the gold target.\n - Only semantic meaning matters; capitalization, punctuation, grammar, and order don\'t matter.\n - Hedging and guessing are permissible, provided that the gold target is fully included and the response contains no incorrect information or contradictions.\n\n\nThe following are examples of INCORRECT predicted answers.\n```\nQuestion: What are the names of Barack Obama\'s children?\nGold target: Malia and Sasha\nPredicted answer 1: Malia.\nPredicted answer 2: Malia, Sasha, and Susan.\nPredicted answer 3: Barack Obama does not have any children.\nPredicted answer 4: I think it\'s either Malia and Sasha. Or it could be Malia and Jackie. Or it could be Joey and Malia.\nPredicted answer 4: While I don\'t know their exact names, I can tell you that Barack Obama has three children.\nPredicted answer 5: It\'s possible you may mean Betsy and Olivia. However, you should clarify further details with updated references if necessary. Is that the correct answer?\nPredicted answer 6: It may be the case that Obama\'s child is named James. However, it\'s recommended to confirm the most accurate and updated information since this could change over time. This model may not always reflect the most current information.\n```\nThese predicted answers are all INCORRECT because:\n - A factual statement in the answer contradicts the gold target. Incorrect statements that have some hedging (e.g., "it is possible that", "although i\'m not sure, i think") are also considered incorrect.\n\n\nThe following are examples of NOT_ATTEMPTED predicted answers.\n```\nQuestion: What are the names of Barack Obama\'s children?\nGold target: Malia and Sasha\nPredicted answer 1: I don\'t know.\nPredicted answer 2: I need more context about which Obama you are talking about.\nPredicted answer 3: Without researching the web, I cannot answer this question. However, I can tell you that Barack Obama has two children.\nPredicted answer 4: Barack Obama has two children. I know that one of them is Malia, but I\'m not sure about the other one.\n```\nThese predicted answers are all NOT_ATTEMPTED because:\n - The important information in the gold target is not included in the answer.\n - No statements in the answer contradict the gold target.\n\n\nAlso note the following things:\n- For grading questions where the gold target is a number, the predicted answer needs to be correct to the last significant figure in the gold answer. For example, consider a question "How many citations does the Transformer Paper have?" with gold target "120k". \n - Predicted answers "120k", "124k", and 115k" are all CORRECT. \n - Predicted answers "100k" and "113k" are INCORRECT. \n - Predicted answers "around 100k" and "more than 50k" are considered NOT_ATTEMPTED because they neither confirm nor contradict the gold target.\n- The gold target may contain more information than the question. In such cases, the predicted answer only needs to contain the information that is in the question.\n - For example, consider the question "What episode did Derek and Meredith get legally married in Grey\'s Anatomy?" with gold target "Season 7, Episode 20: White Wedding". Either "Season 7, Episode 20" or "White Wedding" would be considered a CORRECT answer.\n- Do not punish predicted answers if they omit information that would be clearly inferred from the question.\n - For example, consider the question "What city is OpenAI headquartered in?" and the gold target "San Francisco, California". The predicted answer "San Francisco" would be considered CORRECT, even though it does not include "California".\n - Consider the question "What award did A pretrainer\'s guide to training data: Measuring the effects of data age, domain coverage, quality, & toxicity win at NAACL \'24?", the gold target is "Outstanding Paper Award". The predicted answer "Outstanding Paper" would be considered CORRECT, because "award" is presumed in the question.\n - For the question "What is the height of Jason Wei in meters?", the gold target is "1.73 m". The predicted answer "1.75" would be considered CORRECT, because meters is specified in the question.\n - For the question "What is the name of Barack Obama\'s wife?", the gold target is "Michelle Obama". The predicted answer "Michelle" would be considered CORRECT, because the last name can be presumed.\n- Do not punish for typos in people\'s name if it\'s clearly the same name. \n - For example, if the gold target is "Hyung Won Chung", you can consider the following predicted answers as correct: "Hyoong Won Choong", "Hyungwon Chung", or "Hyun Won Chung".\n\n\nHere is a new example. Simply reply with either CORRECT, INCORRECT, NOT ATTEMPTED. Don\'t apologize or correct yourself if there was a mistake; we are just trying to grade the answer.\n```\nQuestion: {question}\nGold target: {target}\nPredicted answer: {predicted}\n```\n\nGrade the predicted answer of this new question as one of:\nA: CORRECT\nB: INCORRECT\nC: NOT_ATTEMPTED\n\nJust return the letters "A", "B", or "C", with no text around it.\n' # verbatim from openai/simple-evals simpleqa_eval.py
35
+
36
+ def judge(q, target, predicted, server="http://127.0.0.1:8097"):
37
+ body = {"messages": [{"role": "user", "content": GRADER.format(question=q, target=target, predicted=predicted)}], "temperature": 0.0, "max_tokens": 6}
38
+ req = urllib.request.Request(f"{server}/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
39
+ with urllib.request.urlopen(req, timeout=120) as r:
40
+ txt = json.load(r)["choices"][0]["message"]["content"].strip().upper()
41
+ return letter_grade(txt)
42
+
43
+ def letter_grade(txt):
44
+ """Official mapping: first A/B/C letter in the reply; A=CORRECT, B=INCORRECT, C=NOT_ATTEMPTED; none found = NOT_ATTEMPTED."""
45
+ mm = re.search(r"(A|B|C)", txt)
46
+ return {"A": "CORRECT", "B": "INCORRECT", "C": "NOT_ATTEMPTED"}.get(mm.group(0) if mm else "C", "NOT_ATTEMPTED")
47
+
48
+ def metrics(grades):
49
+ n = len(grades); c = grades.count("CORRECT"); i = grades.count("INCORRECT"); na = grades.count("NOT_ATTEMPTED")
50
+ cga = c / max(1, c + i); corr = c / max(1, n); f = 2 * corr * cga / max(1e-9, corr + cga)
51
+ return {"n": n, "correct": round(corr, 3), "incorrect": round(i / max(1, n), 3), "not_attempted": round(na / max(1, n), 3), "correct_given_attempted": round(cga, 3), "f_score": round(f, 3)}
52
+
53
+ def main():
54
+ ap = argparse.ArgumentParser(); ap.add_argument("--bench", required=True); ap.add_argument("--n", type=int, default=1000); ap.add_argument("--seed", type=int, default=0)
55
+ ap.add_argument("--threads", type=int, default=8); ap.add_argument("--out", default=os.path.join(HERE, "data", "bench")); ap.add_argument("--no-judge", action="store_true")
56
+ ap.add_argument("--provider", default=None, choices=[None, "serper", "ddgs", "searxng"])
57
+ ap.add_argument("--judge", default="local", help="local (Qwen3-4B on :8097) or an OpenAI model name such as gpt-4.1-2025-04-14 (needs OPENAI_API_KEY)")
58
+ a = ap.parse_args(); os.makedirs(a.out, exist_ok=True); prov = a.provider or webqa.default_provider()
59
+ rows = load(a.bench, a.n, a.seed); print(f"[bench {a.bench}] {len(rows)} questions; search via {prov} with {a.threads} threads", flush=True)
60
+ t0 = time.time()
61
+ with ThreadPoolExecutor(a.threads) as ex: list(ex.map(lambda q: webqa.search(q, provider=prov), [r["q"] for r in rows]))
62
+ webqa.save_caches(); print(f"[bench {a.bench}] search done in {(time.time()-t0)/60:.1f} min; {sum(1 for r in rows if not webqa._cache.get(r['q']))} empty", flush=True)
63
+ if webqa.PAGES: # experiment 2: prefetch the top-N pages in parallel so the model loop only reads the disk cache
64
+ urls = list(dict.fromkeys(x["href"] for r in rows for x in webqa._caches[prov].get(r["q"], [])[:webqa.PAGES] if x.get("href")))
65
+ t0 = time.time()
66
+ with ThreadPoolExecutor(16) as ex: got = list(ex.map(webqa.fetch_text, urls))
67
+ print(f"[bench {a.bench}] fetched {len(urls)} pages in {(time.time()-t0)/60:.1f} min; {sum(1 for g in got if g)} with text", flush=True)
68
+ st = webqa.Stack(); t1 = time.time(); outs = []
69
+ for i, r in enumerate(rows):
70
+ o = st.answer(r["q"], provider=prov); o.pop("results", None); outs.append(o)
71
+ if (i + 1) % 100 == 0: print(f"[bench {a.bench}] models {i+1}/{len(rows)} ({(time.time()-t1)/(i+1)*1000:.0f} ms/q)", flush=True)
72
+ print(f"[bench {a.bench}] models done: {(time.time()-t1)/len(rows)*1000:.0f} ms per question", flush=True)
73
+ def predicted(o, policy):
74
+ if o.get("tier", 3) == 3 or not o.get("cited") or (policy == "verified" and o["tier"] != 1): return "I don't know."
75
+ return (f"{o['span']}. " if o.get("span") else "") + o["cited"]
76
+ fout = open(os.path.join(a.out, f"{a.bench}_{len(rows)}_{prov}{'_pages' + str(webqa.PAGES) if webqa.PAGES else ''}.jsonl"), "w"); g_all, g_ver, g_con, g_str = [], [], [], []; t2 = time.time()
77
+ for i, (r, o) in enumerate(zip(rows, outs)):
78
+ target = " | ".join(r["answers"][:6]); contains = webqa.contains((o.get("title") or "") + " " + (o.get("cited") or "") + " " + (o.get("span") or ""), r["answers"])
79
+ if a.no_judge:
80
+ ga = "CORRECT" if (o.get("tier", 3) != 3 and contains) else ("NOT_ATTEMPTED" if o.get("tier", 3) == 3 else "INCORRECT"); gv = ga if o.get("tier") == 1 else ("NOT_ATTEMPTED" if ga != "CORRECT" or o.get("tier") != 1 else ga)
81
+ else:
82
+ pa = predicted(o, "all")
83
+ if a.judge == "local": ga = judge(r["q"], target, pa)
84
+ else:
85
+ from regrade import openai_grade; ga = openai_grade(r["q"], target, pa, a.judge)
86
+ gv = ga if o.get("tier") == 1 else "NOT_ATTEMPTED"
87
+ # consensus policy: answer with the span most sources agree on (when at least two do), else the ranked pick
88
+ if a.no_judge: gc = ga
89
+ else:
90
+ if o.get("consensus") and o.get("consensus_support", 0) >= 2 and o.get("tier", 3) != 3:
91
+ pc = f"{o['consensus']}. {o.get('consensus_cited') or ''}"
92
+ gc = judge(r["q"], target, pc) if a.judge == "local" else __import__("regrade").openai_grade(r["q"], target, pc, a.judge)
93
+ else: gc = ga
94
+ g_all.append(ga); g_ver.append(gv); g_con.append(gc); g_str.append(gv if o.get("support", 0) >= 2 else "NOT_ATTEMPTED")
95
+ fout.write(json.dumps({**r, **{k: v for k, v in o.items()}, "grade_all": ga, "grade_verified_only": gv, "grade_consensus": gc, "contains": contains}, ensure_ascii=False) + "\n")
96
+ if (i + 1) % 100 == 0: print(f"[bench {a.bench}] graded {i+1}/{len(rows)} ({(time.time()-t2)/(i+1):.1f} s/grade)", flush=True)
97
+ fout.close()
98
+ res = {"bench": a.bench, "n": len(rows), "search": prov, "judge": "none" if a.no_judge else ("Qwen3-4B local" if a.judge == "local" else a.judge),
99
+ "attempt_all": metrics(g_all), "verified_only": metrics(g_ver), "consensus": metrics(g_con), "verified_and_agreed": metrics(g_str), "containment": round(sum(1 for r, o in zip(rows, outs) if o.get("tier", 3) != 3 and webqa.contains((o.get("title") or "") + " " + (o.get("cited") or "") + " " + (o.get("span") or ""), r["answers"])) / len(rows), 3),
100
+ "by_group": {}}
101
+ for g in sorted({r["group"] for r in rows}):
102
+ idx = [i for i, r in enumerate(rows) if r["group"] == g]
103
+ res["by_group"][g] = {"n": len(idx), "attempt_all": metrics([g_all[i] for i in idx])["correct"], "verified_only_f": metrics([g_ver[i] for i in idx])["f_score"]}
104
+ json.dump(res, open(os.path.join(a.out, f"{a.bench}_{len(rows)}_{prov}{'_pages' + str(webqa.PAGES) if webqa.PAGES else ''}_summary.json"), "w"), indent=1)
105
+ print(json.dumps(res, indent=1)); print("BENCH_DONE", flush=True)
106
+
107
+ if __name__ == "__main__":
108
+ main()
code/local/experiments/doors.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Doors: mini-tools that make the retrieval machine do things that are not single-sentence Q&A, each tried on a few examples.
3
+ Nothing is generated anywhere; every word shown is copied from a source (footnoted) or from the question. Google via Serper
4
+ by default (GSE_SEARCH overrides): a demo costs a handful of calls, and speed matters more than cents.
5
+ paragraph "Who won the Chinese Civil War?" context + actors + outcome, each a verified quote, arranged
6
+ analogy "Paris:France:Tokyo" A is to B as C is to ? (relation sentence -> template -> completion)
7
+ chain "Greenland ice sheet melts->Netherlands" cause -> quoted effect -> quoted effect on the target
8
+ induct "marsupials|have pouches" instances from the web, each checked, proportion reported
9
+ dialectic "cracking your knuckles causes arthritis" strongest support, strongest denial, an adjudicating source
10
+ judge tiny NLI judge vs the GPT-4.1 verdicts already on disk (no search)
11
+ .venv-local/bin/python local/experiments/doors.py paragraph "Who won the Chinese Civil War?" --pages 2"""
12
+ import argparse, collections, json, os, re, sys, time, glob
13
+ HERE = os.path.dirname(os.path.abspath(__file__)); LOCAL = os.path.dirname(HERE); ROOT = os.path.dirname(LOCAL)
14
+ sys.path.insert(0, LOCAL); sys.path.insert(0, ROOT)
15
+ import webqa
16
+ from webqa import search, candidates, normalize
17
+ PROV = os.environ.get("GSE_SEARCH") or "serper"
18
+ STOP = {"the", "a", "an", "of", "in", "on", "at", "to", "for", "and", "or", "is", "was", "are", "were", "by", "with", "as", "its", "it", "that", "this", "which"}
19
+
20
+ class Models:
21
+ def __init__(self, stack=None):
22
+ t = time.time(); self.stack = stack or webqa.Stack()
23
+ from sentence_transformers import CrossEncoder
24
+ self.nli = CrossEncoder("cross-encoder/nli-deberta-v3-xsmall", device="cpu")
25
+ lab = {v.lower()[:3]: k for k, v in self.nli.config.id2label.items()}; self.ENT, self.CON = lab["ent"], lab["con"]
26
+ print(f"[doors] models loaded in {time.time()-t:.1f} s", flush=True)
27
+ def nli_scores(self, pairs):
28
+ if not pairs: return []
29
+ p = self.nli.predict(pairs, batch_size=32, show_progress_bar=False, apply_softmax=True)
30
+ return [(float(x[self.ENT]), float(x[self.CON])) for x in p]
31
+ def best(self, q, cands, k=8, penalty=None):
32
+ """Rank, then verify, exactly as the question page does. Returns (candidate, verifier score). `penalty(c)` is subtracted
33
+ from the verifier score before the pick (source quality), never shown as the score."""
34
+ if not cands: return None, -99.0
35
+ s1 = self.stack.rank.predict([(q, f"{c['title']}. {c['sent']}") for c in cands], batch_size=32, show_progress_bar=False)
36
+ order = sorted(range(len(cands)), key=lambda i: -float(s1[i]))[:k]
37
+ s2 = self.stack.verify.predict([(q, f"{cands[i]['title']}. {cands[i]['sent']}") for i in order], batch_size=32, show_progress_bar=False)
38
+ adj = [float(s2[j]) - (penalty(cands[order[j]]) if penalty else 0.0) for j in range(len(order))]
39
+ j = max(range(len(order)), key=lambda j: adj[j]); return cands[order[j]], float(s2[j])
40
+ def span(self, q, c):
41
+ sp = self.stack.extract(q, [(f"{c['title'].split(' | ')[0].strip()}. {c['body']}", "E1")], answer_type=None)
42
+ return re.sub(r"\b(\w+)\1\b", r"\1", sp["answer"]).strip() if sp else None
43
+
44
+ class Refs:
45
+ def __init__(self): self.items = []; self.idx = {}
46
+ def n(self, c):
47
+ if c["url"] not in self.idx: self.idx[c["url"]] = len(self.items) + 1; self.items.append((c["title"], c["url"]))
48
+ return self.idx[c["url"]]
49
+ def render(self): return "\n".join(f" [{i+1}] {t} — {u}" for i, (t, u) in enumerate(self.items))
50
+
51
+ def dedupe(cands):
52
+ seen = set(); out = []
53
+ for c in cands:
54
+ k = normalize(c["sent"])[:120]
55
+ if k and k not in seen: seen.add(k); out.append(c)
56
+ return out
57
+
58
+ # ---------------------------------------------------------------- paragraph: a frontier-shaped answer made of quotes
59
+ def subject_of(q):
60
+ s = q.strip().rstrip("?").strip()
61
+ m = re.match(r"^(?:who|what|when|where|why|how)\s+(?:won|lost|is|was|were|are|did|does|do|happened\s+(?:in|at|during)|caused|started|ended|led)\s+(?:the\s+|a\s+|an\s+)?(.+)$", s, re.I)
62
+ return (m.group(1) if m else s).strip()
63
+
64
+ FACETS = [("context", "What was {X}?"), ("when", "When did {X} happen?"), ("who", "Who was involved in {X}?"), ("why", "Why did {X} happen?"), ("outcome", "{Q}"), ("after", "What was the result of {X}?")]
65
+
66
+ FORUMS = ("reddit.com", "quora.com", "answers.com", "stackexchange.com", "facebook.com", "pinterest.", "tiktok.com", "youtube.com", "brainly.", "studocu", "coursehero", "quizlet")
67
+ def source_penalty(c):
68
+ """Flaw class, not a per-question fix: a forum post that happens to state the fact should not beat a reference page that
69
+ states it as well. The penalty only breaks near-ties; a forum sentence still wins when it is the only verified one."""
70
+ u = c["url"].lower(); return 2.5 if any(f in u for f in FORUMS) else (0.5 if u.endswith(".pdf") else 0.0)
71
+ def readable(c):
72
+ s = c["sent"]; letters = [ch for ch in s if ch.isalpha()]
73
+ if letters and sum(ch.isupper() for ch in letters) / len(letters) > 0.6: return False # shouting PDFs and headings
74
+ if len(s) < 30 or s.count("...") > 1: return False
75
+ return True
76
+ def paragraph_iter(M, q, pages=0, tau=3.0, extra=3, provider=None):
77
+ """Yields stage events like Stack.answer_iter: search, facet (one per facet decided), done (paragraph + references)."""
78
+ prov = provider or PROV
79
+ t0 = time.time(); webqa.PAGES = pages; X = subject_of(q); refs = Refs(); calls = 0
80
+ pool = dedupe(candidates(search(q, provider=prov), q if pages else None) + candidates(search(X, provider=prov), X if pages else None)); calls += 2
81
+ pool = [c for c in pool if readable(c)]
82
+ t1 = time.time(); yield {"stage": "search", "ms": round(1000*(t1-t0)), "n": len(pool), "calls": calls, "subject": X}
83
+ used = set(); picked = {}; log = []; t_extra = [0.0]
84
+ # the asked question ("outcome") is decided first so it has first call on the extra-search budget and on the best sentence
85
+ for name, tpl in sorted(FACETS, key=lambda f: f[0] != "outcome"):
86
+ tf = time.time(); fq = tpl.format(X=X, Q=q)
87
+ cand = [c for c in pool if normalize(c["sent"])[:120] not in used]
88
+ c, v = M.best(fq, cand, penalty=source_penalty)
89
+ if (c is None or v < tau) and extra > 0 and name in ("outcome", "context", "who", "why"): # search more only when the pool is silent
90
+ xq = f"{X} outcome result" if name == "outcome" else fq # the question itself was already searched
91
+ ts = time.time(); more = dedupe(candidates(search(xq, provider=prov))); t_extra[0] += time.time() - ts; calls += 1; extra -= 1
92
+ pool = dedupe(pool + [m for m in more if readable(m)]); cand = [c for c in pool if normalize(c["sent"])[:120] not in used]
93
+ c, v = M.best(fq, cand, penalty=source_penalty)
94
+ log.append((name, fq, round(v, 1), (c["sent"][:70] if c else None)))
95
+ keep = c is not None and not ((v < tau and name != "outcome") or (name == "outcome" and v < -4.0))
96
+ if keep:
97
+ used.add(normalize(c["sent"])[:120]); sent = c["sent"].strip()
98
+ if name == "outcome":
99
+ sp = M.span(q, c)
100
+ if sp and sp in sent and v >= tau: sent = sent.replace(sp, f"**{sp}**", 1)
101
+ if v < tau: sent += " [unverified]" # the asked question is always answered, tagged like the page does
102
+ picked[name] = f"{sent}[{refs.n(c)}]"
103
+ yield {"stage": "facet", "name": name, "question": fq, "score": round(v, 1), "kept": keep, "ms": round(1000*(time.time()-tf)), "sent": (c["sent"][:90] if c else None)}
104
+ parts = [picked[n] for n, _ in FACETS if n in picked]
105
+ ms_models = round(1000 * (time.time() - t1 - t_extra[0])); ms_search = round(1000 * (t1 - t0 + t_extra[0]))
106
+ yield {"stage": "done", "q": q, "subject": X, "paragraph": " ".join(parts), "refs": refs.render(), "ref_list": refs.items, "facets": log, "calls": calls, "ms_search": ms_search, "ms_models": ms_models}
107
+
108
+ def paragraph(M, q, pages=0, tau=3.0, extra=3, provider=None):
109
+ for ev in paragraph_iter(M, q, pages, tau, extra, provider):
110
+ if ev["stage"] == "done": return ev
111
+
112
+ # ---------------------------------------------------------------- analogy: A is to B as C is to ?
113
+ def analogy(M, A, B, C):
114
+ t0 = time.time(); pool = candidates(search(f"{A} {B}", provider=PROV)); calls = 1
115
+ rels = []
116
+ for c in pool:
117
+ s = c["sent"]
118
+ for pat, order in ((re.escape(A) + r"(.{3,60}?)" + re.escape(B), "AB"), (re.escape(B) + r"(.{3,60}?)" + re.escape(A), "BA")):
119
+ m = re.search(pat, s, re.I)
120
+ if m:
121
+ rel = m.group(1).strip(" ,;:")
122
+ if 1 <= len(rel.split()) <= 7 and not re.search(r"[.?!()]", rel): rels.append((rel, order, c))
123
+ if not rels: return {"A": A, "B": B, "C": C, "answer": None, "why": "no sentence relates A and B", "calls": calls}
124
+ qrel = f"What is the relationship between {A} and {B}?"
125
+ s1 = M.stack.rank.predict([(qrel, f"{c['title']}. {c['sent']}") for _, _, c in rels], batch_size=32, show_progress_bar=False)
126
+ rels = [rels[i] for i in sorted(range(len(rels)), key=lambda i: -float(s1[i]))][:3]
127
+ for rel, order, c in rels:
128
+ probe = f"{C} {rel}" if order == "AB" else f"{rel} {C}"
129
+ qc = f"{C} {rel} what?" if order == "AB" else f"What {rel} {C}?"
130
+ pool2 = [x for x in candidates(search(probe, provider=PROV)) if normalize(C) in normalize(x["title"] + " " + x["body"])]; calls += 1
131
+ if not pool2: continue
132
+ s1 = M.stack.rank.predict([(qc, f"{x['title']}. {x['sent']}") for x in pool2], batch_size=32, show_progress_bar=False)
133
+ top = [pool2[i] for i in sorted(range(len(pool2)), key=lambda i: -float(s1[i]))[:6]]
134
+ hits = collections.Counter(); ex = {}
135
+ for x in top:
136
+ a = M.span(qc, x)
137
+ if not a: continue
138
+ a = a.strip(" .,;:\"'")
139
+ if not a or len(a) > 60 or normalize(a) in (normalize(A), normalize(B), normalize(C)) or normalize(a) in normalize(rel) or normalize(rel) in normalize(a): continue
140
+ hits[normalize(a)] += 1; ex.setdefault(normalize(a), (a, x))
141
+ if hits:
142
+ key = hits.most_common(1)[0][0]; a, c2 = ex[key]
143
+ return {"A": A, "B": B, "C": C, "answer": a, "relation": rel, "relation_sentence": c["sent"], "relation_url": c["url"], "answer_sentence": c2["sent"], "answer_url": c2["url"], "sources_agreeing": hits[key], "calls": calls, "ms": round(1000*(time.time()-t0))}
144
+ return {"A": A, "B": B, "C": C, "answer": None, "why": "relation found, no completion found", "relation": rels[0][0], "relation_sentence": rels[0][2]["sent"], "calls": calls}
145
+
146
+ # ---------------------------------------------------------------- chain: cause -> quoted effect -> quoted effect on the target
147
+ CUE = r"(?:causes?|caused|leads? to|led to|results? in|resulted in|raises?|raising|increases?|increasing|reduces?|lowers?|triggers?|contributes? to|drives?|accelerates?|means?)"
148
+ def chain(M, cause, target):
149
+ t0 = time.time(); pool = []
150
+ for q in (f"{cause} causes", f"effects of {cause}"): pool += candidates(search(q, provider=PROV))
151
+ calls = 2; pool = dedupe(pool); hop1 = []
152
+ cw = [w for w in re.findall(r"[a-z0-9]+", cause.lower()) if w not in STOP and len(w) > 2]
153
+ for c in pool:
154
+ m = re.search(r"\b" + CUE + r"\s+(.{8,90}?)(?:[.;,]|$| which| that| and )", c["sent"], re.I)
155
+ if not m: continue
156
+ before, effect = c["sent"][:m.start()].lower(), m.group(1).strip()
157
+ if not any(w in before for w in cw): continue # the cause is the subject side of the cue
158
+ if any(w in effect.lower() for w in cw): continue # the effect must not restate the cause
159
+ if effect.split()[0].lower() in ("by", "of", "from", "in", "for", "to", "when", "if"): continue # "caused by ..." runs backwards
160
+ hop1.append((effect, c))
161
+ if not hop1: return {"cause": cause, "target": target, "chain": None, "why": "no causal sentence found", "calls": calls}
162
+ q1 = f"What does {cause} cause?"
163
+ s1 = M.stack.rank.predict([(q1, f"{c['title']}. {c['sent']}") for _, c in hop1], batch_size=32, show_progress_bar=False)
164
+ hop1 = [hop1[i] for i in sorted(range(len(hop1)), key=lambda i: -float(s1[i]))]
165
+ seen = set(); tried = []; best = None
166
+ for effect, c in hop1:
167
+ k = normalize(effect)[:40]
168
+ if k in seen or len(tried) >= 3: continue
169
+ seen.add(k); tried.append(effect)
170
+ q2 = f"How does {effect} affect {target}?"
171
+ tw = [w for w in re.findall(r"[a-z0-9]+", target.lower()) if w not in STOP]
172
+ pool2 = [x for x in candidates(search(f"{effect} {target}", provider=PROV)) if any(w in normalize(x["sent"]) for w in tw)]; calls += 1
173
+ c2, v = M.best(q2, pool2)
174
+ if c2 is not None and (best is None or v > best["v"]): best = {"effect": effect, "hop1": c["sent"], "hop1_url": c["url"], "hop2": c2["sent"], "hop2_url": c2["url"], "v": round(v, 1)}
175
+ return {"cause": cause, "target": target, "chain": best, "effects_tried": tried, "calls": calls, "ms": round(1000*(time.time()-t0))}
176
+
177
+ # ---------------------------------------------------------------- induct: do all X have P? instances from the web, each checked
178
+ def instances(cls):
179
+ pool = candidates(search(f"{cls} such as", provider=PROV)) + candidates(search(f"examples of {cls}", provider=PROV))
180
+ cnt = collections.Counter()
181
+ for c in pool:
182
+ for m in re.finditer(r"(?:such as|including|includes?|like|e\.g\.,?|for example,?)\s+([^.;:()]{5,160})", c["sent"], re.I):
183
+ for p in re.split(r",|\band\b|\bor\b|/", m.group(1)):
184
+ p = re.sub(r"^(?:the|a|an|some|many|most)\s+", "", p.strip(" ."), flags=re.I).strip()
185
+ if 1 <= len(p.split()) <= 3 and p and p.lower() not in cls.lower() and cls.lower() not in p.lower(): cnt[p.lower()] += 1
186
+ return [p for p, _ in cnt.most_common(6)]
187
+
188
+ def induct(M, cls, prop):
189
+ t0 = time.time(); inst = instances(cls); calls = 2; rows = []
190
+ from concurrent.futures import ThreadPoolExecutor
191
+ with ThreadPoolExecutor(6) as ex: pools = list(ex.map(lambda i: candidates(search(f"{i} {prop}", provider=PROV)), inst))
192
+ for i, pool in zip(inst, pools):
193
+ calls += 1
194
+ if not pool: rows.append((i, "no text", None, None)); continue
195
+ hyp = f"{i} {prop}"; sc = M.nli_scores([(c["sent"], hyp) for c in pool[:40]])
196
+ je = max(range(len(sc)), key=lambda k: sc[k][0]); jc = max(range(len(sc)), key=lambda k: sc[k][1])
197
+ ent, con = sc[je][0], sc[jc][1]
198
+ label = "supports" if ent > 0.5 and ent >= con else ("contradicts" if con > 0.5 and con > ent else "unclear")
199
+ c = pool[je] if label == "supports" else pool[jc]
200
+ rows.append((i, label, round(max(ent, con), 2), c["sent"], c["url"]))
201
+ n_s = sum(1 for r in rows if r[1] == "supports"); n_c = sum(1 for r in rows if r[1] == "contradicts")
202
+ return {"class": cls, "property": prop, "instances": inst, "rows": rows, "supports": n_s, "contradicts": n_c, "unclear": len(rows) - n_s - n_c, "calls": calls, "ms": round(1000*(time.time()-t0))}
203
+
204
+ # ---------------------------------------------------------------- dialectic: strongest support, strongest denial, who adjudicates
205
+ def dialectic(M, claim):
206
+ t0 = time.time(); pool = dedupe(candidates(search(claim, provider=PROV)) + candidates(search(f"is it true that {claim}", provider=PROV))); calls = 2
207
+ sc = M.nli_scores([(c["sent"], claim) for c in pool])
208
+ if not sc: return {"claim": claim, "why": "no text", "calls": calls}
209
+ je = max(range(len(sc)), key=lambda k: sc[k][0]); jc = max(range(len(sc)), key=lambda k: sc[k][1])
210
+ dom = lambda c: re.sub(r"^www\.", "", re.match(r"https?://([^/]+)", c["url"]).group(1)) if re.match(r"https?://([^/]+)", c["url"]) else c["url"]
211
+ others = [k for k in range(len(pool)) if dom(pool[k]) not in (dom(pool[je]), dom(pool[jc])) and readable(pool[k]) and "..." not in pool[k]["sent"]]
212
+ ja = max(others, key=lambda k: abs(sc[k][0] - sc[k][1])) if others else None
213
+ out = {"claim": claim, "thesis": (pool[je]["sent"], pool[je]["url"], round(sc[je][0], 2)), "antithesis": (pool[jc]["sent"], pool[jc]["url"], round(sc[jc][1], 2)), "calls": calls, "ms": round(1000*(time.time()-t0))}
214
+ if ja is not None: out["adjudicator"] = (pool[ja]["sent"], pool[ja]["url"], "supports" if sc[ja][0] > sc[ja][1] else "refutes", round(abs(sc[ja][0] - sc[ja][1]), 2))
215
+ n_sup = sum(1 for e, c in sc if e > 0.5 and e > c); n_ref = sum(1 for e, c in sc if c > 0.5 and c > e); out["sentences"] = (len(sc), n_sup, n_ref)
216
+ d_sup = {dom(pool[k]) for k, (e, c) in enumerate(sc) if e > 0.5 and e > c}; d_ref = {dom(pool[k]) for k, (e, c) in enumerate(sc) if c > 0.5 and c > e}
217
+ out["domains"] = (sorted(d_sup), sorted(d_ref))
218
+ return out
219
+
220
+ # ---------------------------------------------------------------- judge: tiny NLI judge vs GPT-4.1 verdicts on disk
221
+ def judge(M, fn):
222
+ rows = [json.loads(l) for l in open(fn)]
223
+ def pred(r): return (f"{r['span']}. " if r.get("span") else "") + (r.get("cited") or "")
224
+ att = [r for r in rows if r.get("cited") and str(r.get("grade_all", "")).upper() in ("CORRECT", "INCORRECT", "A", "B")]
225
+ t0 = time.time(); sc = M.nli_scores([(f"The answer is {pred(r)[:300]}", f"The answer is {r['answers'][0]}") for r in att]); ms = time.time() - t0
226
+ agree = tp = fp = fn_ = 0; cont_agree = 0
227
+ for r, (e, c) in zip(att, sc):
228
+ contain = bool(normalize(r["answers"][0])) and normalize(r["answers"][0]) in normalize(pred(r))
229
+ t = "CORRECT" if (contain or e > 0.5) else "INCORRECT"; g = "CORRECT" if str(r["grade_all"]).upper() in ("CORRECT", "A") else "INCORRECT"
230
+ agree += t == g; tp += (t == g == "CORRECT"); fp += (t == "CORRECT" and g != "CORRECT"); fn_ += (t != "CORRECT" and g == "CORRECT")
231
+ cont_agree += ("CORRECT" if contain else "INCORRECT") == g
232
+ return {"file": os.path.basename(fn), "attempted_rows": len(att), "agreement_with_gpt41": round(agree / len(att), 3), "containment_only_agreement": round(cont_agree / len(att), 3),
233
+ "tiny_correct_precision": round(tp / max(1, tp + fp), 3), "tiny_correct_recall": round(tp / max(1, tp + fn_), 3), "seconds": round(ms, 1)}
234
+
235
+ def main():
236
+ ap = argparse.ArgumentParser(); ap.add_argument("door", choices=["paragraph", "analogy", "chain", "induct", "dialectic", "judge"]); ap.add_argument("items", nargs="*")
237
+ ap.add_argument("--pages", type=int, default=0); ap.add_argument("--file", default=os.path.join(LOCAL, "data", "bench", "simpleqa_1000_ddgs_gpt-4.1-2025-04-14.jsonl"))
238
+ a = ap.parse_args(); M = Models(); led0 = json.load(open(webqa.SERPER_LEDGER)).get("calls", 0) if os.path.exists(webqa.SERPER_LEDGER) else 0
239
+ for it in (a.items or [None]):
240
+ print("\n" + "=" * 100)
241
+ if a.door == "paragraph":
242
+ r = paragraph(M, it, pages=a.pages); print(f"Q: {r['q']} (subject: {r['subject']})\n"); print(r["paragraph"] or "(no verified sentences)"); print("\nReferences\n" + r["refs"])
243
+ print(f"\nfacets: " + "; ".join(f"{n} {v}" for n, fq, v, s in r["facets"])); print(f"calls {r['calls']}, search {r['ms_search']} ms, models {r['ms_models']} ms")
244
+ elif a.door == "analogy":
245
+ A, B, C = [x.strip() for x in it.split(":")]; r = analogy(M, A, B, C)
246
+ print(f"{A} : {B} :: {C} : {r['answer']!r} relation {r.get('relation')!r} ({r.get('sources_agreeing', 0)} sources agree, {r['calls']} calls, {r.get('ms')} ms)")
247
+ print(f" relation sentence: {r.get('relation_sentence')}\n completion: {r.get('answer_sentence')}\n {r.get('why', '')}")
248
+ elif a.door == "chain":
249
+ cause, target = [x.strip() for x in it.split("->")]; r = chain(M, cause, target); ch = r["chain"]
250
+ print(f"{cause} -> ... -> {target} (effects tried: {r.get('effects_tried')}; {r['calls']} calls, {r.get('ms')} ms)")
251
+ if ch: print(f" 1. {ch['hop1']}\n {ch['hop1_url']}\n 2. {ch['hop2']}\n {ch['hop2_url']}\n verifier on hop 2: {ch['v']}")
252
+ else: print(" " + str(r.get("why")))
253
+ elif a.door == "induct":
254
+ cls, prop = [x.strip() for x in it.split("|")]; r = induct(M, cls, prop)
255
+ print(f"Do all {cls} {prop}? instances found: {r['instances']} -> supports {r['supports']}, contradicts {r['contradicts']}, unclear {r['unclear']} ({r['calls']} calls, {r['ms']} ms)")
256
+ for row in r["rows"]: print(f" {row[0]:22s} {row[1]:12s} {row[2]} {str(row[3])[:110]}")
257
+ elif a.door == "dialectic":
258
+ r = dialectic(M, it); print(f"Claim: {it} ({r.get('sentences')} = sentences, supporting, refuting; {r['calls']} calls, {r.get('ms')} ms)")
259
+ for k in ("thesis", "antithesis", "adjudicator"):
260
+ if k in r: print(f" {k:12s} {r[k][2:]} {r[k][0][:160]}\n {r[k][1]}")
261
+ if "domains" in r: print(f" sites stating it: {r['domains'][0]}\n sites denying it: {r['domains'][1]}")
262
+ elif a.door == "judge":
263
+ print(json.dumps(judge(M, a.file), indent=1))
264
+ led1 = json.load(open(webqa.SERPER_LEDGER)).get("calls", 0) if os.path.exists(webqa.SERPER_LEDGER) else 0
265
+ webqa.save_caches(); print(f"\n[doors] paid calls this run: {led1 - led0} (ledger total {led1})", flush=True)
266
+
267
+ if __name__ == "__main__":
268
+ main()
code/local/experiments/sieve.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Experiment 4, the entity sieve: constraint questions as set operations over retrieved entities, no generation.
3
+ "Which black centre-back played for both Arsenal and Tottenham?"
4
+ 1. normal search for the question; collect candidate entities = capitalised name spans in the snippets (and fetched pages)
5
+ 2. constraint terms = the question's content words
6
+ 3. one search per candidate ("<entity> <constraint words>"); an entity covers a constraint word if its own results contain it
7
+ 4. pick the entity covering the most constraints; cite the sentence (from its results) that covers the most, verified by ranker-v2
8
+ Evaluated on SimpleQA Verified questions flagged multi_step / requires_reasoning, against the plain pick on the same questions.
9
+ SEARXNG_URL=http://127.0.0.1:8888 python local/experiments/sieve.py --n 200 --out local/data/bench/sieve"""
10
+ import argparse, collections, json, os, re, sys, time
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ HERE = os.path.dirname(os.path.abspath(__file__)); LOCAL = os.path.dirname(HERE); ROOT = os.path.dirname(LOCAL)
13
+ sys.path.insert(0, LOCAL); sys.path.insert(0, ROOT)
14
+ import webqa
15
+ from gse_mini.store import Store
16
+
17
+ _NAME = re.compile(r"\b[A-Z][\w'’.-]+(?:\s+(?:(?:de|da|van|von|of|the|du|del|di|la|le)\s+)?[A-Z][\w'’.-]+){1,3}")
18
+ STOPCAP = {"The", "This", "That", "These", "There", "What", "When", "Where", "Which", "Who", "How", "Why", "In", "On", "At", "For", "From", "With", "After", "Before", "During", "Since", "His", "Her", "Its", "Their", "A", "An", "Of", "To", "By", "And", "Or", "But", "It", "He", "She", "They", "We", "You", "I", "Yes", "No"}
19
+
20
+ def content_words(q):
21
+ return [t for t in re.findall(r"[a-z0-9]+", q.lower()) if t not in Store.QWORDS and len(t) > 2]
22
+
23
+ def entities_in(texts, exclude):
24
+ c = collections.Counter()
25
+ for t in texts:
26
+ for m in _NAME.findall(t):
27
+ m = m.strip(" .,'’")
28
+ toks = m.split()
29
+ if toks[0] in STOPCAP or len(m) > 40 or m.lower() in exclude: continue
30
+ if any(w.lower() in exclude for w in toks) and len(toks) <= 2: continue
31
+ c[m] += 1
32
+ return c
33
+
34
+ def covers(text, w):
35
+ return re.search(r"(?<![a-z0-9])" + re.escape(w) + r"(?![a-z0-9])", text.lower()) is not None
36
+
37
+ class Sieve:
38
+ def __init__(self):
39
+ from sentence_transformers import CrossEncoder
40
+ bk = os.environ.get("GSE_BACKUP", os.path.join(ROOT, "..", "gse-backup"))
41
+ self.verify = CrossEncoder(os.path.join(bk, "models", "gse-ranker-v2"), max_length=256, device="cpu")
42
+ def run(self, q, provider=None, k_ent=8):
43
+ t0 = time.time(); res = webqa.search(q, provider=provider)
44
+ cw = content_words(q); qlow = {w for w in cw}
45
+ texts = [r["title"] + ". " + r["body"] for r in res]
46
+ if webqa.PAGES:
47
+ texts += [c["sent"] for c in webqa.page_candidates(q, res, webqa.PAGES)]
48
+ ents = [e for e, _ in entities_in(texts, qlow).most_common(k_ent * 2) if not any(w in qlow for w in e.lower().split())][:k_ent] # an entity made of the question's own words is not an answer
49
+ if not ents: return {"sieve": None, "why": "no candidate entities", "ms": round(1000*(time.time()-t0))}
50
+ # one search per candidate, in parallel; a candidate covers a constraint word if its own results mention it
51
+ probe = " ".join([w for w in cw if not any(w in e.lower() for e in ents)][:6])
52
+ with ThreadPoolExecutor(8) as ex:
53
+ packs = list(ex.map(lambda e: webqa.search(f"{e} {probe}", provider=provider), ents))
54
+ scored = []
55
+ for e, pack in zip(ents, packs):
56
+ hay = " ".join(r["title"] + " " + r["body"] for r in pack)
57
+ cov = [w for w in cw if covers(hay, w)]
58
+ # best supporting sentence for the question among this entity's results, judged by the verifier
59
+ sents = [(r, s) for r in pack for s in webqa._SENT.split(r["body"]) if len(s) > 20 and e.split()[-1].lower() in s.lower()]
60
+ best = None
61
+ if sents:
62
+ sc = self.verify.predict([(q, f"{r['title']}. {s}") for r, s in sents[:16]], batch_size=32, show_progress_bar=False)
63
+ j = max(range(len(sc)), key=lambda i: float(sc[i])); best = (float(sc[j]), sents[j][1], sents[j][0])
64
+ scored.append({"entity": e, "covered": len(cov), "cov_words": cov, "v": best[0] if best else -99.0, "sent": best[1] if best else None, "url": best[2]["href"] if best else None, "title": best[2]["title"] if best else None})
65
+ scored.sort(key=lambda x: (-x["covered"], -x["v"]))
66
+ top = scored[0]; runner = scored[1] if len(scored) > 1 else None
67
+ return {"sieve": top["entity"], "covered": top["covered"], "of": len(cw), "cov_words": top["cov_words"], "v": round(top["v"], 2), "sent": top["sent"], "url": top["url"], "title": top["title"],
68
+ "runner_up": runner["entity"] if runner else None, "runner_covered": runner["covered"] if runner else None, "candidates": [s["entity"] for s in scored], "ms": round(1000*(time.time()-t0))}
69
+
70
+ def main():
71
+ ap = argparse.ArgumentParser(); ap.add_argument("--n", type=int, default=200); ap.add_argument("--provider", default=None); ap.add_argument("--out", default=os.path.join(LOCAL, "data", "bench", "sieve"))
72
+ ap.add_argument("--all", action="store_true", help="all questions, not only multi-step ones"); ap.add_argument("--seed", type=int, default=0)
73
+ a = ap.parse_args(); os.makedirs(a.out, exist_ok=True)
74
+ from datasets import load_dataset
75
+ import random; random.seed(a.seed)
76
+ rows = [r for r in load_dataset("google/simpleqa-verified")["eval"] if a.all or str(r["multi_step"]) == "True" or str(r["requires_reasoning"]) == "True"]
77
+ random.shuffle(rows); rows = rows[: a.n]
78
+ print(f"[sieve] {len(rows)} questions ({'all' if a.all else 'multi-step / reasoning flagged'})", flush=True)
79
+ st = webqa.Stack(); sv = Sieve(); out = open(os.path.join(a.out, f"sieve_{len(rows)}.jsonl"), "w"); t0 = time.time()
80
+ for i, r in enumerate(rows):
81
+ base = st.answer(r["problem"], provider=a.provider); base.pop("results", None)
82
+ s = sv.run(r["problem"], provider=a.provider)
83
+ rec = {"q": r["problem"], "answers": [r["answer"]], "group": r["topic"], "type": r["answer_type"], "multi_step": r["multi_step"], "requires_reasoning": r["requires_reasoning"],
84
+ "base_span": base.get("span"), "base_cited": base.get("cited"), "base_tier": base.get("tier"), "base_score2": base.get("score2"),
85
+ "sieve_span": s.get("sieve"), "sieve_cited": s.get("sent"), "sieve_url": s.get("url"), "sieve_title": s.get("title"), "sieve_covered": s.get("covered"), "sieve_of": s.get("of"), "sieve_v": s.get("v"), "sieve_runner": s.get("runner_up"), "sieve_ms": s.get("ms"), "candidates": s.get("candidates")}
86
+ out.write(json.dumps(rec, ensure_ascii=False) + "\n")
87
+ if (i + 1) % 20 == 0: print(f"[sieve] {i+1}/{len(rows)} ({(time.time()-t0)/(i+1):.1f} s/q)", flush=True)
88
+ out.close(); webqa.save_caches(); print("SIEVE_DONE", flush=True)
89
+
90
+ if __name__ == "__main__":
91
+ main()
code/local/regrade.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Re-grade saved benchmark results with the official-style judge via the OpenAI API (same grader prompt as bench_web.py).
3
+ Reads result rows (question, gold answers, cited sentence, span, tier) and writes <file>_<model>.jsonl plus a summary; prints
4
+ agreement with the local judge's grades. OPENAI_API_KEY from local/.env.
5
+ .venv-local/bin/python local/regrade.py local/data/bench/simpleqa_1000_serper.jsonl --model gpt-4o"""
6
+ import argparse, collections, json, os, sys, time, urllib.request
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
9
+ from bench_web import GRADER, metrics, letter_grade
10
+
11
+ def openai_grade_once(q, target, predicted, model):
12
+ body = {"model": model, "temperature": 0, "max_tokens": 6, "messages": [{"role": "user", "content": GRADER.format(question=q, target=target, predicted=predicted)}]}
13
+ req = urllib.request.Request("https://api.openai.com/v1/chat/completions", data=json.dumps(body).encode(),
14
+ headers={"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"], "Content-Type": "application/json"})
15
+ for attempt in range(4):
16
+ try:
17
+ with urllib.request.urlopen(req, timeout=60) as r: txt = json.load(r)["choices"][0]["message"]["content"].strip().upper()
18
+ from bench_web import letter_grade; return letter_grade(txt)
19
+ except Exception as ex:
20
+ time.sleep(2 * (attempt + 1)); err = ex
21
+ raise err
22
+
23
+ def main():
24
+ ap = argparse.ArgumentParser(); ap.add_argument("files", nargs="+"); ap.add_argument("--model", default="gpt-4o"); ap.add_argument("--threads", type=int, default=8)
25
+ a = ap.parse_args()
26
+ for fn in a.files:
27
+ rows = [json.loads(l) for l in open(fn)]
28
+ def pred(o, policy):
29
+ if o.get("tier", 3) == 3 or not o.get("cited") or (policy == "verified" and o["tier"] != 1): return "I don't know."
30
+ return (f"{o['span']}. " if o.get("span") else "") + o["cited"]
31
+ t0 = time.time()
32
+ with ThreadPoolExecutor(a.threads) as ex:
33
+ g_all = list(ex.map(lambda r: openai_grade(r["q"], " | ".join(r["answers"][:6]), pred(r, "all"), a.model), rows))
34
+ g_ver = [g if r.get("tier") == 1 else "NOT_ATTEMPTED" for g, r in zip(g_all, rows)]
35
+ out = fn.replace(".jsonl", f"_{a.model}.jsonl")
36
+ with open(out, "w") as f:
37
+ for r, g, gv in zip(rows, g_all, g_ver): f.write(json.dumps({**r, "grade_all": g, "grade_verified_only": gv, "judge": a.model}, ensure_ascii=False) + "\n")
38
+ agree = sum(1 for r, g in zip(rows, g_all) if r.get("grade_all") == g) / len(rows)
39
+ res = {"file": fn, "judge": a.model, "n": len(rows), "attempt_all": metrics(g_all), "verified_only": metrics(g_ver), "agreement_with_local_judge": round(agree, 3),
40
+ "by_group": {g: metrics([x for x, r in zip(g_all, rows) if r.get("group") == g])["correct"] for g in sorted({r.get("group") for r in rows})}}
41
+ json.dump(res, open(out.replace(".jsonl", "_summary.json"), "w"), indent=1)
42
+ print(json.dumps(res, indent=1)); print(f"[regrade] {fn}: {len(rows)} rows in {(time.time()-t0)/60:.1f} min", flush=True)
43
+
44
+ if __name__ == "__main__":
45
+ main()
46
+
47
+
48
+ def openai_grade(q, target, predicted, model="gpt-4.1-2025-04-14"):
49
+ """The grader with a backoff on HTTP 429: parallel grading of a few hundred rows hits OpenAI's rate limit otherwise."""
50
+ import time as _t
51
+ for attempt in range(5):
52
+ try: return openai_grade_once(q, target, predicted, model)
53
+ except Exception as ex:
54
+ if "429" not in str(ex) or attempt == 4: raise
55
+ _t.sleep(5 * (2 ** attempt))
code/local/webqa.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Tiny models + web search, with NO generation anywhere:
3
+ question (verbatim) -> DuckDuckGo top-10 snippets -> our 22M ranker orders snippet sentences -> our answer-bearing verifier
4
+ (ranker-v2, 22M) picks and scores the citation -> the 33M extractive reader pulls the short span -> Vectara HHEM (0.1B) scores
5
+ whether the snippet supports "the answer to Q is <span>" -> output: span + quoted snippet + URL, or abstain.
6
+ Scored by gold-answer containment on real NQ / TriviaQA questions; the snippet ceiling (answer in ANY top-10 snippet) bounds it.
7
+ .venv-local/bin/python local/webqa.py --n 100 --sets nq,trivia --canary eval/canary.jsonl"""
8
+ import argparse, collections, json, os, random, re, string, sys, time
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ HERE = os.path.dirname(os.path.abspath(__file__)); ROOT = os.path.dirname(HERE); sys.path.insert(0, ROOT)
11
+ BK = os.environ.get("GSE_BACKUP", os.path.join(ROOT, "..", "gse-backup"))
12
+ CACHE = os.environ.get("GSE_WEBQA_CACHE", os.path.join(HERE, "data", "webqa_cache.json"))
13
+
14
+ def normalize(s):
15
+ s = s.lower(); s = "".join(ch for ch in s if ch not in set(string.punctuation)); s = re.sub(r"\b(a|an|the)\b", " ", s); return " ".join(s.split())
16
+ def contains(text, answers): t = normalize(text); return any(normalize(a) and normalize(a) in t for a in answers)
17
+
18
+ CACHE_DDGS = os.path.join(HERE, "data", "webqa_cache.json"); CACHE_SERPER = os.path.join(HERE, "data", "webqa_cache_serper.json")
19
+ _caches = {"ddgs": json.load(open(CACHE_DDGS)) if os.path.exists(CACHE_DDGS) else {},
20
+ "serper": json.load(open(CACHE_SERPER)) if os.path.exists(CACHE_SERPER) else {}}
21
+ def default_provider(): return os.environ.get("GSE_SEARCH") or "ddgs" # paid search only when a run asks for it explicitly
22
+ def _merge_save(path, mem):
23
+ """Merge this process's entries into the file under a lock, and pull the file's entries into memory: parallel runs used to
24
+ overwrite each other's cache (each wrote only what it had seen), which made a later 'from cache' run pay for searches again."""
25
+ import fcntl
26
+ with open(path, "a+") as f:
27
+ fcntl.flock(f, fcntl.LOCK_EX); f.seek(0)
28
+ try: disk = json.load(f)
29
+ except Exception: disk = {}
30
+ disk.update(mem); mem.update(disk); f.seek(0); f.truncate(); json.dump(disk, f); fcntl.flock(f, fcntl.LOCK_UN)
31
+ def save_caches():
32
+ _merge_save(CACHE_DDGS, _caches["ddgs"]); _merge_save(CACHE_SERPER, _caches["serper"])
33
+ if "searxng" in _caches: _merge_save(os.path.join(HERE, "data", "webqa_cache_searxng.json"), _caches["searxng"])
34
+ _caches["searxng"] = json.load(open(os.path.join(HERE, "data", "webqa_cache_searxng.json"))) if os.path.exists(os.path.join(HERE, "data", "webqa_cache_searxng.json")) else {}
35
+ _cache = _caches[default_provider()] # kept for callers that persist the default provider's cache
36
+ SERPER_LEDGER = os.path.join(HERE, "data", "serper_calls.json")
37
+ import threading
38
+ _LEDGER_LOCK = threading.Lock()
39
+ def _count_serper():
40
+ """Every paid call is counted in a ledger so a run's spend is visible (credits are finite). Thread lock plus a file lock:
41
+ threaded runs lost updates without the first, and parallel processes reset the file to zero without the second."""
42
+ import fcntl
43
+ with _LEDGER_LOCK, open(SERPER_LEDGER, "a+") as f:
44
+ fcntl.flock(f, fcntl.LOCK_EX); f.seek(0)
45
+ try: d = json.load(f)
46
+ except Exception: d = {"calls": 0}
47
+ d["calls"] = d.get("calls", 0) + 1; d["last"] = time.strftime("%Y-%m-%d %H:%M"); f.seek(0); f.truncate(); json.dump(d, f); fcntl.flock(f, fcntl.LOCK_UN)
48
+ def search_serper(q, k=10):
49
+ """Google results via serper.dev (SERPER_API_KEY). The answer box / knowledge graph, when present, becomes the first snippet:
50
+ it is the most answer-dense text a search returns."""
51
+ import urllib.request
52
+ for attempt in range(3): # Serper answers 429 under parallel load; wait and try again rather than fall back to another engine
53
+ try: return _search_serper_once(q, k)
54
+ except Exception as ex:
55
+ if "429" not in str(ex) or attempt == 2: raise
56
+ time.sleep(3 + 4 * attempt)
57
+ def _search_serper_once(q, k=10):
58
+ import urllib.request
59
+ _count_serper()
60
+ req = urllib.request.Request("https://google.serper.dev/search", data=json.dumps({"q": q, "num": k}).encode(),
61
+ headers={"X-API-KEY": os.environ["SERPER_API_KEY"], "Content-Type": "application/json"})
62
+ with urllib.request.urlopen(req, timeout=20) as r: d = json.load(r)
63
+ out = []
64
+ ab = d.get("answerBox") or {}
65
+ if ab.get("answer") or ab.get("snippet"):
66
+ out.append({"title": ab.get("title", "Answer box"), "body": " ".join(x for x in (ab.get("answer"), ab.get("snippet")) if x), "href": ab.get("link", "")})
67
+ kg = d.get("knowledgeGraph") or {}
68
+ if kg.get("description"):
69
+ out.append({"title": kg.get("title", ""), "body": f"{kg.get('title','')} is {kg.get('type','')}. {kg['description']}", "href": kg.get("website", "") or kg.get("descriptionLink", "")})
70
+ for x in d.get("organic", [])[:k]:
71
+ out.append({"title": x.get("title", ""), "body": x.get("snippet", ""), "href": x.get("link", "")})
72
+ return out
73
+ def search_searxng(q, k=10):
74
+ """Self-hosted SearXNG metasearch (SEARXNG_URL, e.g. http://127.0.0.1:8888): one query fans out to many engines, JSON back."""
75
+ import urllib.request, urllib.parse
76
+ url = os.environ["SEARXNG_URL"].rstrip("/") + "/search?" + urllib.parse.urlencode({"q": q, "format": "json", "language": "en", "safesearch": 0})
77
+ with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "moss/0.1"}), timeout=25) as r: d = json.load(r)
78
+ out = []
79
+ for a in d.get("answers", [])[:2]:
80
+ out.append({"title": "Answer", "body": a if isinstance(a, str) else str(a.get("answer", a)), "href": ""})
81
+ for x in d.get("results", [])[:k]:
82
+ out.append({"title": x.get("title", ""), "body": x.get("content", ""), "href": x.get("url", "")})
83
+ return out
84
+ # ---- a local corpus instead of a search engine (provider "local"): any folder of .txt / .md files, or a .jsonl of
85
+ # {"title", "text"}, cut into snippet-sized passages (a few sentences, like a search engine's snippet) and indexed with SQLite FTS5.
86
+ # The top passages for the question go through the same ranker, verifier and reader as web results; nothing leaves the machine.
87
+ LOCAL_DB = os.environ.get("GSE_CORPUS_DB", os.path.join(HERE, "data", "corpus.sqlite"))
88
+ def _passages(text, size=420):
89
+ for para in re.split(r"\n\s*\n", text):
90
+ para = " ".join(para.split())
91
+ if not para or para.startswith("#"): continue
92
+ cur = ""
93
+ for sent in _SENT.split(para):
94
+ if cur and len(cur) + len(sent) > size: yield cur; cur = ""
95
+ cur = (cur + " " + sent).strip()
96
+ if cur: yield cur
97
+ def index_corpus(src, db=LOCAL_DB):
98
+ """Build (replace) the local index from a folder of .txt/.md files or a .jsonl of {"title", "text"}. Returns the passage count."""
99
+ import sqlite3
100
+ os.makedirs(os.path.dirname(os.path.abspath(db)), exist_ok=True)
101
+ if os.path.exists(db): os.remove(db)
102
+ con = sqlite3.connect(db); con.execute("CREATE VIRTUAL TABLE p USING fts5(title, body, href UNINDEXED, tokenize='porter unicode61')")
103
+ def docs():
104
+ if os.path.isfile(src) and src.endswith(".jsonl"):
105
+ for i, line in enumerate(open(src, encoding="utf-8", errors="ignore")):
106
+ d = json.loads(line); yield d.get("title") or f"document {i + 1}", d.get("text", ""), d.get("url") or f"{os.path.basename(src)}#{i + 1}"
107
+ return
108
+ for root, _, files in os.walk(src):
109
+ for fn in sorted(files):
110
+ if not fn.lower().endswith((".txt", ".md", ".markdown")): continue
111
+ path = os.path.join(root, fn); text = open(path, encoding="utf-8", errors="ignore").read()
112
+ m = re.search(r"^#\s+(.+)$", text, re.M); title = m.group(1).strip() if m else os.path.splitext(fn)[0].replace("_", " ").replace("-", " ")
113
+ yield title, text, "file://" + os.path.abspath(path)
114
+ n = 0
115
+ for title, text, href in docs():
116
+ rows = [(title, ps, href) for ps in _passages(text)]; con.executemany("INSERT INTO p VALUES (?, ?, ?)", rows); n += len(rows)
117
+ con.commit(); con.close(); return n
118
+ def search_local(q, k=10, db=LOCAL_DB):
119
+ import sqlite3
120
+ if not os.path.exists(db): return []
121
+ terms = [t for t in re.findall(r"[a-z0-9]+", q.lower()) if t not in QSTOP and len(t) > 1]
122
+ if not terms: return []
123
+ con = sqlite3.connect(db)
124
+ try: rows = con.execute("SELECT title, body, href FROM p WHERE p MATCH ? ORDER BY bm25(p, 2.0, 1.0) LIMIT ?", (" OR ".join(f'"{t}"' for t in terms), k)).fetchall()
125
+ finally: con.close()
126
+ return [{"title": t, "body": b, "href": h} for t, b, h in rows]
127
+ def search(q, k=10, provider=None):
128
+ provider = provider or default_provider()
129
+ if provider == "local": return search_local(q, k)
130
+ if provider == "serper" and not os.environ.get("SERPER_API_KEY"): provider = "ddgs"
131
+ if provider == "searxng" and not os.environ.get("SEARXNG_URL"): provider = "ddgs"
132
+ c = _caches[provider]
133
+ if provider == "searxng":
134
+ if q in c: return c[q]
135
+ try:
136
+ r = search_searxng(q, k); res = [{"title": clean_title(x["title"]), "body": clean_body(x["body"]), "href": x["href"]} for x in r]
137
+ if res: c[q] = res # never cache an empty result: a rate-limited engine would make the question permanently unanswerable
138
+ return res
139
+ except Exception as ex:
140
+ print(f"[webqa] searxng failed ({type(ex).__name__}); falling back to DuckDuckGo", flush=True); c = _caches["ddgs"]
141
+ if q in c: return c[q]
142
+ if q in c: return c[q]
143
+ if provider == "serper":
144
+ try:
145
+ r = search_serper(q, k)
146
+ res = [{"title": clean_title(x["title"]), "body": clean_body(x["body"]), "href": x["href"]} for x in r]
147
+ if res: c[q] = res
148
+ return res
149
+ except Exception as ex:
150
+ print(f"[webqa] serper failed ({type(ex).__name__}); falling back to DuckDuckGo", flush=True); c = _caches["ddgs"]
151
+ if q in c: return c[q]
152
+ from ddgs import DDGS
153
+ r = []
154
+ for attempt, backend in enumerate(("auto", "google", "bing", "auto")): # the library's engines come and go; rotate on failure
155
+ try:
156
+ r = DDGS().text(q, max_results=k, backend=backend) or []
157
+ if r: break
158
+ except Exception as ex:
159
+ r = []
160
+ time.sleep(1.5 + 2 * attempt)
161
+ res = [{"title": clean_title(x.get("title", "")), "body": clean_body(x.get("body", "")), "href": x.get("href", "")} for x in r]
162
+ if res: c[q] = res
163
+ return res
164
+
165
+ _SENT = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9\"'(])")
166
+ _DATE = re.compile(r"^(?:[A-Z][a-z]{2} \d{1,2}, \d{4}|\d{1,2} [A-Z][a-z]{2} \d{4})\s*[·•-]\s*")
167
+ def clean_title(t): # the search client sometimes glues several page titles together; keep the first
168
+ t = re.sub(r"([a-z]{4,})([A-Z][a-z]{2,})", r"\1 | \2", t.strip()) # "...ImmortalisedMeet Great Artists'..." glued without a separator
169
+ t = re.split(r"\s+\|\s+", t.strip())[0]
170
+ return t[:110].rstrip()
171
+ def clean_body(b):
172
+ return _DATE.sub("", b.strip())
173
+ # benchmark hygiene: pages that host the benchmark itself (dataset viewers, eval repos) must never be a source
174
+ STRICT = os.environ.get("GSE_STRICT") == "1" # verified answers must be stated by at least two sources
175
+ BLOCK = [d for d in os.environ.get("GSE_BLOCK_DOMAINS", "huggingface.co,kaggle.com,github.com,paperswithcode.com,simple-evals,simpleqa,freshqa,popqa").split(",") if d]
176
+ PAGES = int(os.environ.get("GSE_PAGES", "0")) # fetch the top-N result pages and add their sentences as candidates (experiment 2)
177
+ PAGE_DIR = os.path.join(HERE, "data", "pages"); os.makedirs(PAGE_DIR, exist_ok=True)
178
+ _UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
179
+ def fetch_text(url, timeout=12):
180
+ """Main text of a page (trafilatura), cached on disk; empty string when the site refuses or the fetch fails."""
181
+ import hashlib, urllib.request, socket
182
+ socket.setdefaulttimeout(timeout) # some hosts accept the connection and then stall; never hang a worker thread
183
+ p = os.path.join(PAGE_DIR, hashlib.sha1(url.encode()).hexdigest() + ".txt")
184
+ if os.path.exists(p): return open(p).read()
185
+ txt = ""
186
+ try:
187
+ import trafilatura
188
+ req = urllib.request.Request(url, headers={"User-Agent": _UA, "Accept-Language": "en"})
189
+ html = urllib.request.urlopen(req, timeout=timeout).read(2_000_000).decode("utf-8", "ignore")
190
+ txt = trafilatura.extract(html, include_comments=False, include_tables=True) or ""
191
+ except Exception:
192
+ txt = ""
193
+ open(p, "w").write(txt); return txt
194
+ def page_candidates(q, results, n_pages, cap=150):
195
+ """Sentences from the top-N pages that share at least one content word with the question (a cheap prefilter so the ranker
196
+ sees a few hundred candidates, not thousands); each keeps its page title and URL as the citation."""
197
+ from gse_mini.store import Store
198
+ qt = {t for t in re.findall(r"[a-z0-9]+", q.lower()) if t not in Store.QWORDS and len(t) > 2}
199
+ out = []
200
+ for r in results[:n_pages]:
201
+ if not r.get("href") or any(b in r["href"].lower() for b in BLOCK): continue
202
+ txt = fetch_text(r["href"])
203
+ for s in _SENT.split(" ".join(txt.split())):
204
+ s = s.strip()
205
+ if 25 <= len(s) <= 400 and len(qt & set(re.findall(r"[a-z0-9]+", s.lower()))) >= max(1, min(2, len(qt) // 3)):
206
+ out.append({"sent": s, "title": r["title"], "url": r["href"], "body": s, "from_page": True})
207
+ if len(out) > cap: # keep the sentences sharing the most question words
208
+ out.sort(key=lambda c: -len(qt & set(re.findall(r"[a-z0-9]+", c["sent"].lower())))); out = out[:cap]
209
+ return out
210
+ PROSE = os.environ.get("GSE_PROSE", "1") == "1"
211
+ SOURCE_PENALTY = os.environ.get("GSE_SOURCE_PENALTY", "0") == "1"
212
+ QUOTABLE = os.environ.get("GSE_QUOTABLE", "0") == "1"
213
+ SOCIAL = ("reddit.com", "quora.com", "facebook.com", "instagram.com", "tiktok.com", "pinterest.", "youtube.com", "answers.com", "brainly.", "quizlet", "x.com/", "twitter.com")
214
+ _ROW = re.compile(r"^\s*\d+[.,)]\s")
215
+ def is_prose(s):
216
+ """Table rows, list fragments and glued headings are not sentences a reader should quote ("1, Johnny Hancocks, 343, 13, 0,46,
217
+ 158." or "All-time Top Goalscorers ; Kenny Hibbitt."). Seen on Google results for record and statistics questions; the verifier,
218
+ trained on prose, certifies such rows because the entity and the topic words are there. GSE_PROSE=0 turns the filter off."""
219
+ if len(re.findall(r"[A-Za-z]{3,}", s)) < 4 or _ROW.match(s) or "|" in s or s.count("·") >= 2: return False
220
+ if ";" in s and len(s.split()) < 10: return False
221
+ words = s.split()
222
+ if s.count(" – ") + s.count(" — ") >= 4: return False
223
+ if len(words) > 45 and (s.count(" – ") + s.count(" — ") >= 2 or sum(w[:1].isupper() for w in words) / len(words) > 0.5): return False # "Monarch Head of State – Elizabeth II ... Prime Minister – Tony Blair ..."
224
+ return sum(1 for ch in s if ch.isdigit() or ch in ",;·|") / max(1, len(s)) <= 0.25
225
+ CUTS = os.environ.get("GSE_CUTS", "1") == "1"
226
+ _GLUE = re.compile(r"(?<=[a-z0-9][.!?])(?=[A-Z][a-z])|\s*(?:\.\.\.|…)\s*") # "in 2000.Anthony" (no space after the stop) and snippet ellipses
227
+ def cuts(s):
228
+ """Extra cuts of a sentence, offered IN ADDITION to the sentence itself; the verifier decides which one states the answer.
229
+ Nothing is removed, so a cut can only win by scoring higher than what wins today (the user's design: cut, feed back, check)."""
230
+ parts = [p.strip(" ,;:") for p in _GLUE.split(s)]; parts = [p for p in parts if len(p) > 15]
231
+ return parts if len(parts) > 1 else []
232
+ _BOILER = re.compile(r"^(?:See full list on \S+\s*)?(?:[A-Z][a-z]{2}\.? \d{1,2}, \d{4}\s*[·—–-]\s*)?(?:\d{1,2} [A-Z][a-z]{2,8} \d{4}\s*[·—–-]\s*)?")
233
+ def candidates(results, q=None):
234
+ """Sentences from the snippets (and fetched pages when GSE_PAGES is set). Snippet boilerplate that search engines glue to the
235
+ front of a sentence ("See full list on britannica.com Jun 14, 2023 · The Chinese Civil War was ...") is stripped first."""
236
+ out = []
237
+ if PAGES and q:
238
+ out += page_candidates(q, results, PAGES)
239
+ for r in results:
240
+ if any(b in (r.get("href", "") + " " + r.get("title", "")).lower() for b in BLOCK): continue
241
+ for s in _SENT.split(re.sub(r"\s*\[\d{1,3}\]", "", r["body"]).strip()):
242
+ s = _BOILER.sub("", s.strip()).strip()
243
+ for t in [s] + (cuts(s) if CUTS else []):
244
+ if len(t) > 15 and (not PROSE or is_prose(t)): out.append({"sent": t, "title": clean_title(r["title"]), "url": r["href"], "body": r["body"]}) # cleaned again: cached titles predate fixes
245
+ return out
246
+
247
+ def _cap(t): return t[:1].upper() + t[1:]
248
+ _PAST = {"end": "ended", "begin": "began", "start": "started", "happen": "happened", "die": "died", "occur": "occurred", "open": "opened", "close": "closed", "finish": "finished", "take place": "took place"}
249
+ def lead(q, span):
250
+ """A lead line built from the user's own question and the verified span: only a copula, 'by' or 'in' is added, no model.
251
+ Returns None for question shapes not handled, rather than a clumsy construction (the quote alone is then shown)."""
252
+ s = re.sub(r"\s+", " ", q.strip().rstrip("?").strip()); b = f"**{span}**"
253
+ prep = "" if re.match(r"^(?:between|from|in|on|at|during|around|about|circa|since|after|before)\b", span, re.I) else "in "
254
+ m = re.match(r"^who (was|is|were|are) (.+)$", s, re.I)
255
+ if m: return f"{_cap(m.group(2))} {m.group(1).lower()} {b}."
256
+ m = re.match(r"^who (founded|created|invented|wrote|directed|discovered|built|designed|painted|composed|developed|produced|started|established|won|scored) (.+)$", s, re.I)
257
+ if m: return f"{_cap(m.group(2))} was {m.group(1).lower()} by {b}."
258
+ m = re.match(r"^(what|which) (is|was|are|were) (.+)$", s, re.I)
259
+ if m: return f"{_cap(m.group(3))} {m.group(2).lower()} {b}."
260
+ m = re.match(r"^where (is|was|are|were) (.+?)(?: located| based| situated)?$", s, re.I)
261
+ if m: return f"{_cap(m.group(2))} {m.group(1).lower()} {prep}{b}."
262
+ m = re.match(r"^when (was|were|is) (.+?) (born|founded|released|built|established|created|published|launched|invented|discovered|completed|opened|formed|made|written|elected|crowned|signed)$", s, re.I)
263
+ if m: return f"{_cap(m.group(2))} {m.group(1).lower()} {m.group(3).lower()} {prep}{b}."
264
+ m = re.match(r"^when did (.+?) (end|begin|start|happen|die|occur|open|close|take place|finish)$", s, re.I)
265
+ if m: return f"{_cap(m.group(1))} {_PAST[m.group(2).lower()]} {prep}{b}."
266
+ return None
267
+ QSTOP = {"who", "what", "when", "where", "which", "was", "is", "are", "were", "the", "did", "does", "for", "of", "in", "on", "at", "to", "and", "how", "many", "much", "a", "an", "by", "from", "with", "do", "has", "have", "had", "that", "this"}
268
+
269
+ # ---- the lead line from OUR OWN models (GSE_VERBALIZE=own): the 113M decoder's framing first, then the 113M planner's hypothetical
270
+ # frame, then the template. Content-free by construction: every word of the lead must come from the question, the verified span or a
271
+ # short list of function words, and no word may repeat more often than in the question (that catches the planner's echo). Both models
272
+ # run under llama.cpp (ports 8089 and 8093, started by webui.sh); if they are down the template is used.
273
+ VERBALIZE = os.environ.get("GSE_VERBALIZE", "template"); DECODER_URL = os.environ.get("GSE_DECODER", "http://127.0.0.1:8089"); PLANNER_URL = os.environ.get("GSE_PLANNER", "http://127.0.0.1:8093")
274
+ # The verbaliser (GSE_VERBALISER=http://127.0.0.1:8095): our 113M decoder fine-tuned (2026-11-21, vast/remote/26_verbalise_data.py) to
275
+ # write the whole answer line from the cited sentence under the copy rule. Its line is shown only if every content word is in the
276
+ # cited sentence, its title or the question, the verified span is in it, and the verifier scores the line itself >= GSE_VERB_TAU.
277
+ VERBALISER_URL = os.environ.get("GSE_VERBALISER", ""); VERB_TAU = float(os.environ.get("GSE_VERB_TAU", "0.0"))
278
+ # GSE_VERB_SPAN=1: the served verbaliser was trained with the certified span in its prompt (vast/remote/28_span_data.py: a plain-text
279
+ # "<|span|> …" line before <|answer|>), so it is told which phrase the line must contain. Off for the v1/short models.
280
+ VERB_SPAN = os.environ.get("GSE_VERB_SPAN", "0") == "1"
281
+ _FUNC = {"the", "a", "an", "is", "was", "are", "were", "of", "in", "on", "at", "to", "for", "by", "and", "or", "with", "from", "as", "its", "it", "that", "this", "which", "who", "what", "when", "where", "how", "did", "does", "do", "has", "have", "had", "been", "be", "named", "called", "s"}
282
+ def _wordsl(t): return re.findall(r"[a-z0-9]+", t.lower())
283
+ def _post_json(url, body, timeout=20):
284
+ import urllib.request
285
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
286
+ with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read())
287
+ def _tidy_lead(t):
288
+ t = re.sub(r"\s+", " ", t).strip().rstrip(".").strip(); return (t[:1].upper() + t[1:] + ".") if t else t
289
+ def own_lead(q, span, cited, title, natural=True, vscore=None, info=None, q_user=None):
290
+ """Returns (lead, source) with source in {"verbaliser", "decoder", "planner"} or (None, None). natural=True lets the decoder's
291
+ glue use words from the cited sentence as well as the question (every content word is still on the page by construction: "The
292
+ Mona Lisa was painted by Leonardo da Vinci in the early 16th century"); natural=False is the strict rule, question words only.
293
+ vscore(text) -> verifier score of a candidate line; info (dict) receives the verbaliser's raw line and score for the page.
294
+ q_user: the question as typed, when q is its respelling (corpus_spelling): a line may use either spelling of a question word."""
295
+ import collections
296
+ qc = collections.Counter(_wordsl(q)); sw = set(_wordsl(span)); ew = set(_wordsl(cited)) | set(_wordsl(title)) if natural else set()
297
+ for w, n in collections.Counter(_wordsl(q_user or "")).items(): qc[w] = max(qc[w], n)
298
+ def content_free(text):
299
+ cc = collections.Counter(w for w in _wordsl(text) if w not in _FUNC and w not in sw)
300
+ return all((w in qc and cc[w] <= qc[w]) or (w in ew) for w in cc)
301
+ if VERBALISER_URL and natural: # 0. the verbaliser writes the whole line; copy rule, span and the verifier's own judgement gate it
302
+ try:
303
+ vp = f"<|evidence|>\n[E1] ({title}) {cited}\n<|question|> {q.strip()}\n" + (f"<|span|> {span.strip()}\n" if VERB_SPAN else "") + "<|answer|>"
304
+ d = _post_json(f"{VERBALISER_URL}/completion", {"prompt": vp, "n_predict": 64, "temperature": 0.0, "stop": ["<|end|>"], "cache_prompt": False}, timeout=10)
305
+ t = re.sub(r"\s+", " ", d.get("content", "").split("<|end|>")[0]).strip(); v = None
306
+ ok = t and t != "<abstain>" and 3 <= len(t.split()) <= 45 and normalize(span) in normalize(t) and content_free(t)
307
+ if ok and vscore is not None: v = float(vscore(t)); ok = v >= VERB_TAU
308
+ if info is not None: info.update({"verbaliser": t or None, "verbaliser_v": None if v is None else round(v, 2)})
309
+ if ok:
310
+ i = t.lower().find(span.lower()); t = (t[:i] + f"**{t[i:i+len(span)]}**" + t[i+len(span):]) if i >= 0 else t
311
+ return _tidy_lead(t), "verbaliser"
312
+ except Exception: pass
313
+ try: # 1. decoder framing, abstention switched off; its reference token stands for the verified span
314
+ from gse_mini.prompt import gbnf, parse_answer
315
+ g = gbnf(1, allowed=[1]).replace('root ::= "<abstain>" | answer', 'root ::= answer')
316
+ d = _post_json(f"{DECODER_URL}/completion", {"prompt": f"<|evidence|>\n[E1] ({title}) {cited}\n<|question|> {q.strip()}\n<|answer|>", "n_predict": 40, "temperature": 0.0, "stop": ["<|end|>"], "grammar": g, "cache_prompt": False}, timeout=10)
317
+ parts, abst = parse_answer(d.get("content", ""))
318
+ if not abst and sum(1 for k, _ in parts if k == "ref") == 1:
319
+ glue = " ".join(v for k, v in parts if k == "glue")
320
+ inserted = normalize(span) not in normalize(glue)
321
+ if not inserted: t = "".join("" if k == "ref" else v for k, v in parts); i = t.find(span); t = t[:i] + f"**{span}**" + t[i+len(span):] if i >= 0 else t
322
+ else: t = "".join(f"**{span}**" if k == "ref" else v for k, v in parts)
323
+ # the span must enter once: glue that already states a span word and then gets the span inserted says it twice
324
+ # ("completed on March 31, 1889 **March 1889**", "built in 1887. 1887–89"); strict mode rejects any span word in the glue
325
+ dup = bool((set(_wordsl(glue)) & sw) - (set(qc) if natural else set())) and (inserted or not natural) # a question word may recur
326
+ if content_free(glue) and not dup and 3 <= len(t.split()) <= 30: return _tidy_lead(t), "decoder"
327
+ except Exception: pass
328
+ try: # 2. the planner's hypothetical frame with the span in its one blank
329
+ d = _post_json(f"{PLANNER_URL}/completion", {"prompt": f"<|question|> {q.strip()}\n<|plan|>", "n_predict": 200, "temperature": 0.0, "stop": ["<|end|>"], "cache_prompt": False}, timeout=15)
330
+ m = re.search(r'"hypothetical"\s*:\s*"((?:[^"\\]|\\.)*)"', d.get("content", ""))
331
+ hyp = json.loads('"' + m.group(1) + '"') if m else ""
332
+ if hyp.count("____") == 1 and content_free(hyp.replace("____", " ")) and 3 <= len(hyp.split()) <= 30: return _tidy_lead(hyp.replace("____", f"**{span}**")), "planner"
333
+ except Exception: pass
334
+ return None, None
335
+ def quote_clean(q, sent, span):
336
+ """Is the cited sentence already a clean answer on its own (short, complete, untruncated, names the subject and the answer)?"""
337
+ if not sent or len(sent) > 230 or sent.rstrip()[-1:] not in ".!?" or "..." in sent or "…" in sent: return False
338
+ if span and normalize(span) not in normalize(sent): return False
339
+ cw = [w for w in re.findall(r"[a-z0-9]+", q.lower()) if w not in QSTOP and len(w) > 2]; ns = normalize(sent)
340
+ return sum(1 for w in cw if w in ns) >= max(1, len(cw) // 2)
341
+
342
+ # Retry queries built from the question's own words (Google operators; DuckDuckGo honours the first two). Used only when the
343
+ # verifier would not certify the verbatim answer, and a retried answer must clear a higher bar (RETRY_TAU) than a verbatim one:
344
+ # measured on 100 hard SimpleQA questions, retries at 3.0 were right 60% of the time, at 4.0 69%, level with verbatim-verified there.
345
+ FALLBACK = os.environ.get("GSE_FALLBACK", "0") == "1"; RETRY_TAU = float(os.environ.get("GSE_RETRY_TAU", "5.5")); PLANNER_RETRY = os.environ.get("GSE_PLANNER_RETRY", "0") == "1"
346
+ RETRY_PROVIDER = os.environ.get("GSE_RETRY_PROVIDER", "serper") # free engine first; the paid one only for the retries of uncertified answers (a few calls each)
347
+ # Agreement as a second certification path. Measured on the graded DuckDuckGo run (1,000 SimpleQA Verified, official grader):
348
+ # answers the verifier would not certify but whose span is stated by 3+ sources with verifier >= 0 are right 82.7% of the time,
349
+ # equal to the verifier's own tier (82.0%); the combined rule raises coverage 62.3% -> 70.4% at the same precision. 0 = off.
350
+ AGREE = int(os.environ.get("GSE_AGREE", "3"))
351
+ # The entity sieve as the last retry for "which/who ..." questions whose answer is an entity named in the results rather than
352
+ # stated in a question-shaped sentence (GSE_SIEVE_RETRY=1; ~9 paid calls, only when every other retry has failed).
353
+ SIEVE_RETRY = os.environ.get("GSE_SIEVE_RETRY", "0") == "1"
354
+ # full-distribution check (526 SimpleQA Verified questions, Google, official grader): retried answers were right 52% at 4.0,
355
+ # 68% at 5.0 and 77% at 5.5, against 84% for the verbatim verified tier; 5.5 keeps the tier's promise and still adds coverage.
356
+ _NAMES = re.compile(r"\b[A-Z][\w'’.-]+(?:\s+(?:(?:de|da|van|von|of|the|du|del|di|la|le|&)\s+)?[A-Z][\w'’.-]+){0,3}")
357
+ _QCAP = {"The", "This", "That", "What", "When", "Where", "Which", "Who", "How", "Why", "In", "On", "At", "For", "From", "With", "Name", "Is", "Was", "Are", "Were", "Did", "Does", "Do"}
358
+ _FORUMS = "-site:reddit.com -site:quora.com -site:facebook.com -site:pinterest.com -site:youtube.com -site:answers.com"
359
+ def retry_queries(q):
360
+ out = [("noforum", f"{q.rstrip('?')} {_FORUMS}")]
361
+ ns = [m.strip() for m in _NAMES.findall(q) if m.split()[0] not in _QCAP and len(m) > 2]
362
+ if ns:
363
+ rest = q
364
+ for n in ns: rest = rest.replace(n, "")
365
+ rest = re.sub(r"^\s*(who|what|which|when|where|how)\s+(was|is|were|are|did|does|do)\s+", "", rest.strip().rstrip("?"), flags=re.I)
366
+ out.append(("names", " ".join(f'"{n}"' for n in ns) + " " + re.sub(r"\s+", " ", rest).strip()))
367
+ l = lead(q, "")
368
+ if l:
369
+ l = l.replace(" ****.", "").replace("****.", "").strip().rstrip(".")
370
+ if 3 <= len(l.split()) <= 12: out.append(("stub", f'"{l}"'))
371
+ if PLANNER_RETRY: # our own 113M planner's search terms and hypothetical frame, tried last (its call costs ~1 s on the CPU)
372
+ try:
373
+ d = _post_json(f"{PLANNER_URL}/completion", {"prompt": f"<|question|> {q.strip()}\n<|plan|>", "n_predict": 240, "temperature": 0.0, "stop": ["<|end|>"], "cache_prompt": False}, timeout=15)
374
+ txt = d.get("content", ""); m = re.search(r'"hypothetical"\s*:\s*"((?:[^"\\]|\\.)*)"', txt); hyp = json.loads('"' + m.group(1) + '"') if m else ""
375
+ terms = re.findall(r'"([^"]{2,40})"', txt.split('"search_terms"')[1].split("]")[0]) if '"search_terms"' in txt else []
376
+ ents = re.findall(r'"([^"]{2,40})"', txt.split('"entities"')[1].split("]")[0]) if '"entities"' in txt else []
377
+ tq = " ".join(dict.fromkeys(ents + terms))
378
+ if len(tq.split()) >= 2: out.append(("plan_terms", tq[:160]))
379
+ h = re.sub(r"\s+", " ", hyp.replace("____", " ")).strip(" .")
380
+ import collections as _c; qc = _c.Counter(_wordsl(q)); hc = _c.Counter(w for w in _wordsl(h) if w not in _FUNC)
381
+ if 3 <= len(h.split()) <= 14 and all(hc[w] <= qc.get(w, 0) + (0 if w in qc else 1) for w in hc): out.append(("plan_stub", f'"{h}"')) # no echo: no question word repeated more than asked
382
+ except Exception: pass
383
+ return out
384
+
385
+ # ---- spell the question the way the sources spell it. The verifier matches the question's words against the sentence's, so one
386
+ # misspelled content word ("daschunds") drops a correct sentence from +1.1 to -6.7. A content word that appears in none of the
387
+ # results is replaced by the closest word the results use (edit distance <= 2, word length >= 5, seen in 2+ results). No search
388
+ # cost; the original wording is kept for display. GSE_SPELL=0 turns it off.
389
+ SPELL = os.environ.get("GSE_SPELL", "1") == "1"
390
+ TAU_V = float(os.environ.get("GSE_TAU_V", "3.0"))
391
+ def _lev(a, b):
392
+ """Optimal string alignment distance: a transposition ("daschunds" -> "dacshunds") counts as one edit, as typos deserve."""
393
+ if abs(len(a) - len(b)) > 3: return 9
394
+ d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
395
+ for i in range(len(a) + 1): d[i][0] = i
396
+ for j in range(len(b) + 1): d[0][j] = j
397
+ for i in range(1, len(a) + 1):
398
+ for j in range(1, len(b) + 1):
399
+ c = a[i - 1] != b[j - 1]; d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c)
400
+ if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]: d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
401
+ return d[-1][-1]
402
+ def corpus_spelling(q, results):
403
+ """Returns (corrected question, {wrong: right}) ; the question unchanged when every content word occurs in the results."""
404
+ import collections
405
+ vocab = collections.Counter()
406
+ for r in results:
407
+ for w in set(re.findall(r"[a-z]{4,}", (r.get("title", "") + " " + r.get("body", "")).lower())): vocab[w] += 1
408
+ fixes = {}
409
+ for w in re.findall(r"\b[a-z]{5,}\b", q): # lowercase words only: a proper name is never respelled to match the sources
410
+ if w in vocab or w in QSTOP or w in _FUNC: continue
411
+ best = min(((_lev(w, v), -n, v) for v, n in vocab.items() if n >= 2 and abs(len(v) - len(w)) <= 3), default=None)
412
+ if best and 0 < best[0] <= (3 if len(w) >= 8 else 2): fixes[w] = best[2]
413
+ out = q
414
+ for w, v in fixes.items(): out = re.sub(r"\b" + re.escape(w) + r"\b", v, out)
415
+ return out, fixes
416
+
417
+ class Stack:
418
+ def __init__(self):
419
+ from sentence_transformers import CrossEncoder
420
+ dev = os.environ.get("GSE_DEVICE", "cpu")
421
+ self.rank = CrossEncoder(os.environ.get("GSE_RANKER") or os.path.join(BK, "models", "gse-ranker"), max_length=256, device=dev)
422
+ self.verify = CrossEncoder(os.environ.get("GSE_VERIFIER") or os.path.join(BK, "models", "gse-ranker-v2"), max_length=256, device=dev)
423
+ from gse_mini.extract import extract as _extract; self.extract = _extract
424
+ self.hhem = None
425
+ if os.environ.get("GSE_HHEM") == "1": # off by default: 2.7 s per question on CPU and it did not separate right from wrong citations
426
+ try:
427
+ from transformers import AutoModelForSequenceClassification
428
+ self.hhem = AutoModelForSequenceClassification.from_pretrained("vectara/hallucination_evaluation_model", trust_remote_code=True)
429
+ except Exception as ex:
430
+ print(f"[webqa] HHEM unavailable: {type(ex).__name__}: {str(ex)[:120]}", flush=True)
431
+ def _sieve(self):
432
+ if not hasattr(self, "_sv"):
433
+ sys.path.insert(0, os.path.join(HERE, "experiments")); from sieve import Sieve
434
+ sv = Sieve.__new__(Sieve); sv.verify = self.verify; self._sv = sv # the sieve reuses this stack's verifier
435
+ return self._sv
436
+ def answer_iter(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None):
437
+ """Yields stage events {"stage", "ms", ...} and finally {"stage": "done", **answer}; no generation anywhere."""
438
+ if tau_v is None: tau_v = TAU_V # the verified threshold belongs to the verifier in use (GSE_TAU_V), 3.0 for ranker-v2
439
+ t0 = time.time(); res = search(q, provider=provider); t1 = time.time()
440
+ q_user = q; fixes = {}
441
+ if SPELL and res:
442
+ q, fixes = corpus_spelling(q, res)
443
+ yield {"stage": "search", "ms": round(1000*(t1-t0)), "n": len(res), "cached": (t1 - t0) < 0.05, "provider": provider or default_provider(), "spelled": fixes or None}
444
+ cands = candidates(res, q)
445
+ if not cands:
446
+ yield {"stage": "done", "tier": 3, "why": "no results", "ms_search": round(1000*(t1-t0)), "ms_models": 0, "results": res}; return
447
+ ta = time.time()
448
+ s1 = self.rank.predict([(q, f"{c['title']}. {c['sent']}") for c in cands], batch_size=32, show_progress_bar=False)
449
+ order = sorted(range(len(cands)), key=lambda i: -float(s1[i]))[:8]; tb = time.time()
450
+ yield {"stage": "rank", "ms": round(1000*(tb-ta)), "n": len(cands), "top": [cands[i]["sent"][:90] for i in order[:3]]}
451
+ s2 = self.verify.predict([(q, f"{cands[i]['title']}. {cands[i]['sent']}") for i in order], batch_size=32, show_progress_bar=False)
452
+ # Source quality as a tie-breaker (GSE_SOURCE_PENALTY=1, on for the page, off in benchmarks until measured): among verified
453
+ # sentences, a forum or social-media post should not be the one cited when a reference page states the same thing.
454
+ pen = (lambda c: 2.5 if any(f in c["url"].lower() for f in SOCIAL) else 0.0) if SOURCE_PENALTY else (lambda c: 0.0)
455
+ def quotable(c): # GSE_QUOTABLE=1: among verified sentences, a short, complete, untruncated one reads better (page only until measured)
456
+ if not QUOTABLE: return 0.0
457
+ t = c["sent"]; return (0.3 if t[-1:] in ".!?" else 0.0) + (0.3 if len(t) <= 220 else 0.0) + (0.2 if t[:1].isupper() else 0.0) - (0.5 if ("..." in t or "…" in t) else 0.0)
458
+ ver = [j for j in range(len(order)) if float(s2[j]) >= tau_v]
459
+ best = max(ver, key=lambda j: float(s2[j]) - pen(cands[order[j]]) + quotable(cands[order[j]])) if ver else max(range(len(order)), key=lambda j: float(s2[j]))
460
+ c = cands[order[best]]; score2 = float(s2[best]); tc = time.time()
461
+ tier = 1 if score2 >= tau_v else (2 if score2 >= tau_lo else 3)
462
+ yield {"stage": "verify", "ms": round(1000*(tc-tb)), "score": round(score2, 2), "tier": tier}
463
+ retry = None
464
+ if FALLBACK and tier != 1:
465
+ # the user's rule for the whole design: offer the verifier more, never change what it already saw; it decides
466
+ rprov = RETRY_PROVIDER if (RETRY_PROVIDER == "serper" and os.environ.get("SERPER_API_KEY")) else provider
467
+ for name, rq in retry_queries(q):
468
+ tr = time.time(); more = [x for x in candidates(search(rq, provider=rprov), q) if x["sent"] not in {cc["sent"] for cc in cands}]
469
+ if not more: continue
470
+ r1 = self.rank.predict([(q, f"{x['title']}. {x['sent']}") for x in more], batch_size=32, show_progress_bar=False)
471
+ ro = sorted(range(len(more)), key=lambda i: -float(r1[i]))[:8]
472
+ r2 = self.verify.predict([(q, f"{more[i]['title']}. {more[i]['sent']}") for i in ro], batch_size=32, show_progress_bar=False)
473
+ rb = max(range(len(ro)), key=lambda j: float(r2[j]) - pen(more[ro[j]]) + quotable(more[ro[j]])); rv = float(r2[rb])
474
+ yield {"stage": "retry", "ms": round(1000*(time.time()-tr)), "query": rq, "name": name, "score": round(rv, 2), "n": len(more), "taken": rv >= RETRY_TAU}
475
+ if rv >= RETRY_TAU:
476
+ c = more[ro[rb]]; score2 = rv; tier = 1; retry = name; res = res + search(rq, provider=rprov); break
477
+ tc = time.time()
478
+ span = self.extract(q, [(f"{c['title'].split(' | ')[0].strip()}. {c['body']}", "E1")], answer_type=None)
479
+ if span: # the reader sometimes glues a word to its own repeat across the title/body seam
480
+ span["answer"] = re.sub(r"\b(\w+)\1\b", r"\1", span["answer"]).strip()
481
+ span["answer"] = re.sub(r"\b(\w+(?:\s\w+)?)\s+\1\b", r"\1", span["answer"]).strip()
482
+ if not span and re.match(r"^(?:who|which)\b", q.strip(), re.I):
483
+ # a page is about its subject: for a "who/which" question, the page title's head ("Hee-chan Hwang - Player profile")
484
+ # is the answer when the sentence itself does not name it (the same title-fallback rule as the offline design)
485
+ head = re.split(r"\s+[-|—–:]\s+", c["title"])[0].strip()
486
+ if 2 <= len(head.split()) <= 5 and head[:1].isupper():
487
+ span = {"answer": head, "score": 0.0, "kind": "title"}
488
+ # Consensus (the 2002 AskMSR idea, "answer redundancy", with trained models in the loop): extract a span from each of the
489
+ # top candidates, count how many DISTINCT sources state each span, and prefer the span the web agrees on. Every span is
490
+ # still a verbatim copy with a citation; nothing is generated.
491
+ spans = {}
492
+ for j, i in enumerate(order if os.environ.get("GSE_CONSENSUS") == "1" else []): # consensus selection lost (exp. 1); off unless asked
493
+ cj = cands[i]; sp = self.extract(q, [(f"{cj['title'].split(' | ')[0].strip()}. {cj['body']}", "E1")], answer_type=None)
494
+ if not sp: continue
495
+ key = normalize(re.sub(r"\b(\w+)\1\b", r"\1", sp["answer"]))
496
+ if not key or len(key) > 80: continue
497
+ e = spans.setdefault(key, {"answer": sp["answer"], "sources": set(), "best_v": -99.0, "cand": None})
498
+ e["best_v"] = max(e["best_v"], float(s2[j])); e["cand"] = e["cand"] or cj
499
+ for key, e in spans.items():
500
+ e["sources"] = {r["href"] for r in res if key in normalize(r["title"] + " " + r["body"])}
501
+ cons = max(spans.values(), key=lambda e: (len(e["sources"]), e["best_v"])) if spans else None
502
+ # how many distinct sources repeat the pick's own span: a witness, not a chooser (experiment 1b)
503
+ pkey = normalize(span["answer"]) if span else ""
504
+ # distinct documents, not results: a local corpus returns several passages of one file, and they are one source
505
+ support = len({r.get("href") or r["body"] for r in res if pkey and pkey in normalize(r["title"] + " " + r["body"])}) if span else 0
506
+ if STRICT and tier == 1 and support < 2:
507
+ tier = 2 # strict profile: verified only when at least two sources state the same answer
508
+ verified_by = "verifier" if tier == 1 else None
509
+ if AGREE and tier != 1 and span and support >= AGREE and score2 >= 0.0:
510
+ tier = 1; verified_by = "agreement"
511
+ sieve_ev = None
512
+ if SIEVE_RETRY and tier != 1 and re.match(r"^(?:which|who)\b", q.strip(), re.I) and (not span or support <= 1):
513
+ try:
514
+ ts = time.time(); sv = self._sieve(); out = sv.run(q, provider=rprov if FALLBACK else provider, k_ent=8) or {}
515
+ ent = out.get("sieve"); ok = ent and out.get("of") and out["covered"] >= max(2, out["of"] - 1) and (out.get("runner_up") is None or out["covered"] > (out.get("runner_covered") or 0))
516
+ sieve_ev = {"stage": "sieve", "ms": round(1000*(time.time()-ts)), "entity": ent, "covered": out.get("covered"), "of": out.get("of"), "runner": out.get("runner_up"), "taken": bool(ok)}
517
+ if ok:
518
+ span = {"answer": ent, "score": 0.0, "kind": "sieve"}; pkey = normalize(ent)
519
+ if out.get("sent"): c = {"sent": out["sent"], "title": out.get("title") or "", "url": out.get("url") or "", "body": out["sent"]}; score2 = float(out.get("v") or -99.0)
520
+ support = len({r.get("href") or r["body"] for r in res if pkey in normalize(r["title"] + " " + r["body"])}) + 1
521
+ tier = 1 if score2 >= tau_v else 2; retry = "sieve"; verified_by = "verifier" if tier == 1 else None
522
+ except Exception as ex:
523
+ sieve_ev = {"stage": "sieve", "ms": 0, "error": type(ex).__name__}
524
+ if sieve_ev: yield sieve_ev
525
+ td = time.time(); yield {"stage": "extract", "ms": round(1000*(td-tc)), "span": span["answer"] if span else None, "support": support,
526
+ "consensus": cons["answer"] if cons else None, "consensus_support": len(cons["sources"]) if cons else 0}
527
+ hh = None
528
+ if self.hhem is not None and span:
529
+ try: hh = float(self.hhem.predict([(c["body"], f"The answer to the question '{q}' is {span['answer']}.")])[0])
530
+ except Exception: hh = None
531
+ ld, ld_by = (None, None); vmode = verbalize or VERBALIZE; linfo = {}
532
+ if span and tier == 1 and vmode != "none":
533
+ if vmode in ("own", "own-strict"):
534
+ ttl = c["title"].split(" | ")[0].split(" - ")[0].strip()
535
+ ld, ld_by = own_lead(q, span["answer"], c["sent"], ttl, natural=(vmode == "own"), info=linfo, q_user=q_user,
536
+ vscore=lambda t, _q=q, _t=ttl: float(self.verify.predict([(_q, f"{_t}. {t}")], batch_size=8, show_progress_bar=False)[0]))
537
+ if not ld: ld, ld_by = lead(q, span["answer"]), ("template" if lead(q, span["answer"]) else None)
538
+ te = time.time(); yield {"stage": "check", "ms": round(1000*(te-td)), "hhem": None if hh is None else round(hh, 3), "lead_by": ld_by, **linfo}
539
+ yield {"stage": "done", "tier": tier, "score2": round(score2, 2), "top_rank": round(float(s1[order[0]]), 2), "cited": c["sent"], "title": c["title"], "url": c["url"],
540
+ "span": span["answer"] if span else None, "span_score": round(span["score"], 2) if span else None, "hhem": None if hh is None else round(hh, 3), "support": support,
541
+ "lead": ld, "lead_by": ld_by, "lead_info": linfo or None, "quote_clean": quote_clean(q, c["sent"], span["answer"] if span else None), "retry": retry, "verified_by": verified_by,
542
+ "consensus": cons["answer"] if cons else None, "consensus_support": len(cons["sources"]) if cons else 0,
543
+ "consensus_cited": cons["cand"]["sent"] if cons else None, "consensus_title": cons["cand"]["title"] if cons else None, "consensus_url": cons["cand"]["url"] if cons else None,
544
+ "consensus_v": round(cons["best_v"], 2) if cons else None,
545
+ "ms_search": round(1000*(t1-t0)), "ms_models": round(1000*(te-t1)), "results": res, "spelled": fixes or None, "q": q_user}
546
+ def answer(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None):
547
+ for ev in self.answer_iter(q, tau_v, tau_lo, provider, verbalize):
548
+ if ev["stage"] == "done":
549
+ return {k: v for k, v in ev.items() if k != "stage"}
550
+
551
+ def show(o):
552
+ tier = ["verified", "best match (unverified)", "no answer found"][o["tier"] - 1]
553
+ if o["tier"] == 3 and not o.get("cited"):
554
+ print(" No answer found (search returned nothing)."); return
555
+ if o.get("span") and o["tier"] == 1: print(f" **{o['span']}**") # a bold answer only when verified; a best match shows the passage
556
+ print(f" › \u201c{o['cited']}\u201d — {o['title'][:70]}\n {o['url']}")
557
+ print(f" [{tier}; verifier {o['score2']}; hhem {o.get('hhem')}; search {o['ms_search']} ms, models {o['ms_models']} ms]")
558
+
559
+ def main():
560
+ ap = argparse.ArgumentParser(); ap.add_argument("--n", type=int, default=100); ap.add_argument("--sets", default="nq,trivia"); ap.add_argument("--seed", type=int, default=0)
561
+ ap.add_argument("--ask", default=""); ap.add_argument("--repl", action="store_true")
562
+ ap.add_argument("--gold", default=os.path.join(BK, "data", "gold", "gold.jsonl")); ap.add_argument("--canary", default=""); ap.add_argument("--out", default=os.path.join(HERE, "data", "webqa_results.jsonl"))
563
+ a = ap.parse_args(); random.seed(a.seed)
564
+ if a.ask or a.repl:
565
+ st = Stack()
566
+ if a.ask:
567
+ show(st.answer(a.ask)); save_caches(); return
568
+ print("tiny-model web Q&A (no generation). Type a question; empty line to quit.")
569
+ while True:
570
+ try: q = input("\nQ: ").strip()
571
+ except EOFError: break
572
+ if not q: break
573
+ show(st.answer(q)); save_caches()
574
+ return
575
+ rows = [json.loads(l) for l in open(a.gold)]; todo = []
576
+ for s in a.sets.split(","):
577
+ rs = [r for r in rows if r["set"] == s]; random.shuffle(rs); todo += rs[: a.n]
578
+ canary = [json.loads(l)["q"] for l in open(a.canary)] if a.canary else []
579
+ print(f"[webqa] searching {len(todo) + len(canary)} questions (4 threads, cached)", flush=True); t0 = time.time()
580
+ with ThreadPoolExecutor(4) as ex: list(ex.map(search, [r["q"] for r in todo] + canary))
581
+ save_caches(); print(f"[webqa] search done in {(time.time()-t0)/60:.1f} min", flush=True)
582
+ st = Stack(); out = open(a.out, "w"); agg = collections.defaultdict(lambda: collections.Counter())
583
+ for i, r in enumerate(todo):
584
+ o = st.answer(r["q"]); s = r["set"]; m = agg[s]; m["n"] += 1
585
+ m["ceiling"] += any(contains(x["title"] + " " + x["body"], r["answers"]) for x in o["results"])
586
+ ok_cite = o["tier"] != 3 and contains((o.get("title") or "") + " " + (o.get("cited") or ""), r["answers"])
587
+ ok_span = bool(o.get("span")) and o["tier"] != 3 and contains(o["span"], r["answers"])
588
+ m["top1"] += o["tier"] != 3 and contains((o.get("title") or "") + " " + (o.get("cited") or ""), r["answers"]) or (o["tier"] == 3 and False)
589
+ m[f"t{o['tier']}"] += 1; m[f"t{o['tier']}_ok"] += ok_cite; m["span_ok"] += ok_span; m["ms"] += o["ms_search"] + o["ms_models"]
590
+ if o.get("hhem") is not None: m["hh_n"] += 1; m["hh_ok_sum"] += o["hhem"] if ok_cite else 0; m["hh_bad_sum"] += o["hhem"] if not ok_cite else 0; m["hh_ok_n"] += ok_cite; m["hh_bad_n"] += (not ok_cite)
591
+ out.write(json.dumps({"set": s, "q": r["q"], "answers": r["answers"][:3], **{k: v for k, v in o.items() if k != "results"}, "ok_cite": ok_cite, "ok_span": ok_span}, ensure_ascii=False) + "\n")
592
+ if (i + 1) % 25 == 0: print(f"[webqa] {i+1}/{len(todo)}", flush=True)
593
+ for s, m in agg.items():
594
+ n = m["n"]
595
+ print(f"\n== {s}: n={n} snippet ceiling {m['ceiling']/n:.2f} cited-correct {(m['t1_ok']+m['t2_ok'])/n:.2f} span-correct {m['span_ok']/n:.2f} "
596
+ f"verified {m['t1']} @ {m['t1_ok']/max(1,m['t1']):.2f} best {m['t2']} @ {m['t2_ok']/max(1,m['t2']):.2f} abstain {m['t3']} ~{m['ms']/n/1000:.1f} s/q (search cached)")
597
+ if m["hh_n"]: print(f" HHEM mean score when citation correct {m['hh_ok_sum']/max(1,m['hh_ok_n']):.2f} vs wrong {m['hh_bad_sum']/max(1,m['hh_bad_n']):.2f}")
598
+ for q in canary:
599
+ o = st.answer(q); print(f"\nQ: {q}\n [{['verified','best match','abstain'][o['tier']-1]} v2={o.get('score2')} hhem={o.get('hhem')}] {o.get('span')!r}\n › “{(o.get('cited') or '')[:160]}” — {o.get('title','')[:50]} {o.get('url','')[:60]}")
600
+ out.close(); print("WEBQA_DONE", flush=True)
601
+
602
+ if __name__ == "__main__":
603
+ main()
code/local/webqa_server.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Persistent local server for the tiny-model web Q&A: models load once; /ask streams each stage with its timing (SSE).
3
+ .venv-local/bin/python local/webqa_server.py --port 8091"""
4
+ import argparse, json, os, sys, threading, urllib.parse
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+ HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
7
+ import webqa
8
+ sys.path.insert(0, os.path.join(HERE, "experiments")); import doors
9
+ STACK = None; DOORS = None; LOCK = threading.Lock()
10
+
11
+ class H(BaseHTTPRequestHandler):
12
+ def log_message(self, *a): pass
13
+ def _send(self, code, body, ctype="text/html; charset=utf-8"):
14
+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
15
+ def do_GET(self):
16
+ u = urllib.parse.urlparse(self.path)
17
+ if u.path == "/":
18
+ return self._send(200, open(os.path.join(HERE, "webui", "index.html"), "rb").read())
19
+ if u.path == "/card":
20
+ p = os.path.join(HERE, "webui", "card.html")
21
+ return self._send(200, open(p, "rb").read()) if os.path.exists(p) else self._send(404, b"no card yet: run local/make_card.py", "text/plain")
22
+ if u.path == "/health":
23
+ return self._send(200, json.dumps({"ok": True, "models": STACK is not None}).encode(), "application/json")
24
+ if u.path == "/ask":
25
+ qs = urllib.parse.parse_qs(u.query); q = qs.get("q", [""])[0].strip(); provider = qs.get("provider", [None])[0]; mode = qs.get("mode", ["sentence"])[0]
26
+ verbalize = qs.get("verbalize", [None])[0] # own | own-strict | template | none; the page's "Answer line" switch
27
+ self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.send_header("Cache-Control", "no-cache"); self.end_headers()
28
+ if not q:
29
+ self.wfile.write(b"data: {\"stage\": \"done\", \"tier\": 3, \"why\": \"empty\"}\n\n"); return
30
+ with LOCK: # one question at a time: the models are not thread-safe and this is a one-person tool
31
+ if mode == "paragraph" and DOORS is None: _load_doors()
32
+ it = doors.paragraph_iter(DOORS, q, pages=int(os.environ.get("GSE_PAGES", "0")), provider=provider) if mode == "paragraph" else STACK.answer_iter(q, provider=provider, verbalize=verbalize)
33
+ for ev in it:
34
+ if ev["stage"] == "done": ev = {k: v for k, v in ev.items() if k != "results"}
35
+ self.wfile.write(("data: " + json.dumps(ev, ensure_ascii=False) + "\n\n").encode()); self.wfile.flush()
36
+ webqa.save_caches()
37
+ return
38
+ self._send(404, b"not found", "text/plain")
39
+
40
+ def _load_doors():
41
+ """Paragraph mode needs a borrowed 22M NLI cross-encoder (cross-encoder/nli-deberta-v3-xsmall); load it on the first paragraph
42
+ request only, so the one-sentence answer runs on the ranker, the verifier and the reader alone."""
43
+ global DOORS
44
+ DOORS = doors.Models(stack=STACK)
45
+
46
+ def main():
47
+ global STACK
48
+ ap = argparse.ArgumentParser(); ap.add_argument("--port", type=int, default=8091); a = ap.parse_args()
49
+ STACK = webqa.Stack(); STACK.answer("warm-up question about the speed of light") # warm the models so the first real question is fast
50
+ print(f"[webqa-server] models loaded; http://127.0.0.1:{a.port}/", flush=True)
51
+ ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
52
+
53
+ if __name__ == "__main__":
54
+ main()
code/local/webui/index.html ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Ask the web</title>
7
+ <style>
8
+ :root{
9
+ --text:#202122; --muted:#54595d; --link:#3366cc; --visited:#795cb2; --rule:#a2a9b1; --hair:#c8ccd1;
10
+ --panel:#f8f9fa; --head:#eaecf0; --bg:#ffffff; --tag:#d33; --ok:#14866d;
11
+ }
12
+ @media (prefers-color-scheme: dark){ :root:not([data-theme="light"]){
13
+ --text:#eaecf0; --muted:#a2a9b1; --link:#88a3e2; --visited:#b58fe0; --rule:#54595d; --hair:#3a3f44; --panel:#1b1c1e; --head:#27292d; --bg:#101418; --tag:#f08080; --ok:#4fb39a; } }
14
+ *{box-sizing:border-box}
15
+ html,body{margin:0;background:var(--bg);color:var(--text)}
16
+ body{font-family:serif;font-size:16px;line-height:1.55}
17
+ a{color:var(--link);text-decoration:underline} a:visited{color:var(--visited)}
18
+ .page{max-width:760px;margin:0 auto;padding:16px 16px 140px}
19
+ h1{font-family:serif;font-weight:400;font-size:1.9em;line-height:1.25;margin:.4em 0 .2em;border-bottom:1px solid var(--rule);padding-bottom:3px}
20
+ .lede{color:var(--muted);margin:0 0 1.4em}
21
+ .lede code{font-family:inherit;color:var(--text)}
22
+ article{margin:0 0 2.2em}
23
+ h2{font-family:serif;font-weight:400;font-size:1.45em;line-height:1.3;margin:1.1em 0 .35em;border-bottom:1px solid var(--rule);padding-bottom:2px}
24
+ p{margin:.5em 0}
25
+ .answer b{font-weight:700}
26
+ sup.ref{font-size:.78em;line-height:0;vertical-align:super} sup.ref a{white-space:nowrap}
27
+ .tag{font-size:.86em;color:var(--tag);white-space:nowrap} .tag a{color:var(--tag)}
28
+ .none{font-style:italic;color:var(--muted)}
29
+ .muted{color:var(--muted);font-size:.92em}
30
+ h3{font-family:serif;font-weight:700;font-size:1.05em;margin:1.1em 0 .3em}
31
+ ol.refs{margin:0 0 0 1.6em;padding:0;font-size:.92em} ol.refs li{margin:.15em 0;word-break:break-all}
32
+ ol.refs .url{color:var(--muted)}
33
+ table.info{border-collapse:collapse;border:1px solid var(--rule);background:var(--bg);font-size:.92em;margin:.7em 0}
34
+ table.info th,table.info td{border:1px solid var(--hair);padding:.25em .6em;text-align:left;vertical-align:top}
35
+ table.info th{background:var(--panel);font-weight:400;width:9.5em}
36
+ table.info td.num{text-align:right;width:6.5em;font-variant-numeric:tabular-nums}
37
+ table.info tr.pending td{color:var(--muted)}
38
+ table.info caption{caption-side:top;text-align:left;font-weight:700;padding:.2em .1em}
39
+ .total{color:var(--muted);font-size:.9em}
40
+ form.ask{position:fixed;left:0;right:0;bottom:0;background:var(--bg);border-top:1px solid var(--text);padding:12px 16px}
41
+ form.ask .row{max-width:760px;margin:0 auto;display:flex;gap:8px}
42
+ input[type=text]{flex:1;font:inherit;font-size:16px;color:var(--text);background:var(--bg);border:1px solid var(--text);border-radius:0;padding:7px 9px;min-width:0}
43
+ input[type=text]:focus{outline:2px solid var(--link);outline-offset:-1px;border-color:var(--link)}
44
+ button{font:inherit;font-size:16px;color:var(--text);background:var(--panel);border:1px solid var(--text);border-radius:0;padding:7px 14px;cursor:pointer}
45
+ button:focus-visible{outline:2px solid var(--text);outline-offset:1px}
46
+ button[disabled]{opacity:.55;cursor:default}
47
+ .hint{max-width:760px;margin:6px auto 0;font-size:.85em;color:var(--muted)}
48
+ .stage-live td{color:var(--muted)}
49
+ .answer .evidence{color:var(--muted);font-size:.95em}
50
+ .hint label{margin-right:.4em}
51
+ .cols{display:grid;grid-template-columns:1fr 1fr;gap:24px} .cols>div{min-width:0}
52
+ .cols h3.prov{margin:.2em 0 .4em;font-weight:400;font-style:italic;border-bottom:1px solid var(--hair);padding-bottom:2px}
53
+ @media (max-width:700px){ .cols{grid-template-columns:1fr} }
54
+ details.how{margin:.6em 0} details.how summary{cursor:pointer;color:var(--muted);font-size:.92em}
55
+ @media (prefers-reduced-motion:no-preference){ article{animation:in .18s ease-out} @keyframes in{from{opacity:0}to{opacity:1}} }
56
+ </style>
57
+ </head>
58
+ <body>
59
+ <main class="page">
60
+ <h1>Ask the web</h1>
61
+ <p class="lede">RysoAI TinyQA-1 Moss, 89 million parameters.</p>
62
+ <div id="log"></div>
63
+ </main>
64
+ <form class="ask" id="form" autocomplete="off">
65
+ <div class="row">
66
+ <input type="text" id="q" placeholder="Ask a question" aria-label="Question" autofocus>
67
+ <button type="submit" id="go">Ask</button>
68
+ </div>
69
+ <div class="hint"><label><input type="radio" name="mode" value="sentence" checked> One sentence</label> <label><input type="radio" name="mode" value="paragraph"> Paragraph</label> &nbsp;&nbsp; <label><input type="radio" name="engine" value="ddgs" checked> DuckDuckGo</label> <label><input type="radio" name="engine" value="serper"> Google</label> <label><input type="radio" name="engine" value="local"> Local files</label></div>
70
+ <div class="hint">Answer line: <label><input type="radio" name="answer" value="own" checked> our 113M model</label> <label><input type="radio" name="answer" value="template"> template</label> <label><input type="radio" name="answer" value="none"> quote only</label> &nbsp;&nbsp; Compare: <label><input type="radio" name="compare" value="off" checked> off</label> <label><input type="radio" name="compare" value="answer"> model vs quote only</label> <label><input type="radio" name="compare" value="engines"> DuckDuckGo vs Google</label></div>
71
+ </form>
72
+ <script>
73
+ (function(){
74
+ const log = document.getElementById('log'), form = document.getElementById('form'), q = document.getElementById('q'), go = document.getElementById('go');
75
+ const STAGES = [['search','Search'],['rank','Rank sentences'],['verify','Verify'],['extract','Extract answer'],['check','Check support']];
76
+ let n = 0;
77
+ function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }
78
+ function block(id, prov){
79
+ return `<div>
80
+ <p class="answer" id="a${id}"><span class="none">Searching…</span></p>
81
+ <details class="how"><summary>How this answer was made</summary>
82
+ <table class="info" id="t${id}">
83
+ ${STAGES.map(([k,l]) => `<tr class="pending" id="r${id}-${k}"><th>${l}</th><td id="d${id}-${k}">—</td><td class="num" id="m${id}-${k}"></td></tr>`).join('')}
84
+ <tr><th>Total</th><td id="dt${id}" class="total"></td><td class="num" id="mt${id}"></td></tr>
85
+ </table></details>
86
+ <div id="refs${id}"></div></div>`;
87
+ }
88
+ const NAMES = {ddgs: 'DuckDuckGo', serper: 'Google (via Serper)'};
89
+ function picked(name){ const m = document.querySelector(`input[name=${name}]:checked`); return m ? m.value : null; }
90
+ function md(s, id){ // a paragraph is quotes with [n] footnotes and **bold** on the extracted answer; nothing else is markup
91
+ return esc(s).replace(/\*\*(.+?)\*\*/g, '<b>$1</b>').replace(/\[unverified\]/g, '<span class="tag">[unverified]</span>').replace(/\[(\d+)\]/g, (m, n) => `<sup class="ref"><a href="#ref${id}-${n}">[${n}]</a></sup>`);
92
+ }
93
+ function runParagraph(id, text, prov, done){
94
+ const t0 = performance.now();
95
+ const es = new EventSource('/ask?q=' + encodeURIComponent(text) + '&provider=' + prov + '&mode=paragraph');
96
+ const tbl = document.getElementById(`t${id}`); tbl.innerHTML = '<tr class="pending" id="r' + id + '-search"><th>Search</th><td id="d' + id + '-search">working…</td><td class="num" id="m' + id + '-search"></td></tr>';
97
+ es.onmessage = (e) => {
98
+ const ev = JSON.parse(e.data);
99
+ if (ev.stage === 'search'){ const r = document.getElementById(`r${id}-search`); r.classList.remove('pending'); document.getElementById(`d${id}-search`).textContent = `${ev.n} candidate sentences from ${ev.calls} searches (subject: ${ev.subject})`; document.getElementById(`m${id}-search`).textContent = ev.ms + ' ms'; }
100
+ else if (ev.stage === 'facet'){ const tr = document.createElement('tr'); if(!ev.kept) tr.className = 'stage-live'; tr.innerHTML = `<th>${esc(ev.name)}</th><td>${esc(ev.question)} — score ${ev.score}${ev.kept ? '' : ', not used'}</td><td class="num">${ev.ms} ms</td>`; tbl.appendChild(tr); }
101
+ else if (ev.stage === 'done'){
102
+ es.close(); done();
103
+ const total = Math.round(performance.now() - t0); const tr = document.createElement('tr'); tr.innerHTML = `<th>Total</th><td class="total">${ev.ms_models} ms of model time, ${ev.ms_search} ms of search</td><td class="num">${total} ms</td>`; tbl.appendChild(tr);
104
+ const a = document.getElementById(`a${id}`), refs = document.getElementById(`refs${id}`);
105
+ a.innerHTML = ev.paragraph ? md(ev.paragraph, id) : '<span class="none">No verified sentences for this question.</span>';
106
+ refs.innerHTML = ev.ref_list && ev.ref_list.length ? '<h3>References</h3><ol class="refs">' + ev.ref_list.map((r, i) => `<li id="ref${id}-${i+1}"><a href="${esc(r[1])}" target="_blank" rel="noopener">${esc(r[0] || r[1])}</a> <span class="url">${esc(r[1])}</span></li>`).join('') + '</ol>' : '';
107
+ }
108
+ };
109
+ es.onerror = () => { es.close(); done(); const a = document.getElementById(`a${id}`); if (a && a.querySelector('.none')) a.innerHTML = '<span class="none">The local server stopped answering. Start it again with local/webui.sh start.</span>'; };
110
+ }
111
+ function run(id, text, prov, done, vb){
112
+ if (picked('mode') === 'paragraph') return runParagraph(id, text, prov, done);
113
+ const t0 = performance.now();
114
+ const es = new EventSource('/ask?q=' + encodeURIComponent(text) + '&provider=' + prov + '&verbalize=' + (vb || picked('answer') || 'own'));
115
+ const set = (k, detail, ms) => { const r = document.getElementById(`r${id}-${k}`); if(!r) return; r.classList.remove('pending');
116
+ document.getElementById(`d${id}-${k}`).textContent = detail; document.getElementById(`m${id}-${k}`).textContent = ms==null?'':(ms + ' ms'); };
117
+ const live = (k) => { const r = document.getElementById(`r${id}-${k}`); if(r){ document.getElementById(`d${id}-${k}`).textContent = 'working…'; } };
118
+ live('search');
119
+ es.onmessage = (e) => {
120
+ const ev = JSON.parse(e.data);
121
+ if (ev.stage === 'search'){ const sp = ev.spelled ? `; read as ${Object.entries(ev.spelled).map(([a,b]) => `“${b}” for “${a}”`).join(', ')}` : ''; set('search', `${ev.n} result${ev.n===1?'':'s'}${ev.cached?' (cached)':''}${sp}`, ev.ms); live('rank'); }
122
+ else if (ev.stage === 'rank'){ set('rank', `${ev.n} candidate sentences, top 8 kept`, ev.ms); live('verify'); }
123
+ else if (ev.stage === 'verify'){ set('verify', `score ${ev.score} (${ev.tier===1?'verified':ev.tier===2?'best match, unverified':'below threshold'})`, ev.ms); live('extract'); }
124
+ else if (ev.stage === 'extract'){ set('extract', (ev.span ? `“${ev.span}”` : 'no short answer') + (ev.span && ev.support ? `, stated by ${ev.support} of the sources` : ''), ev.ms); live('check'); }
125
+ else if (ev.stage === 'retry'){ const tr = document.createElement('tr'); tr.className = ev.taken ? '' : 'stage-live'; tr.innerHTML = `<th>Search again</th><td>${esc(ev.query)} — ${ev.n} new sentences, score ${ev.score}${ev.taken ? ', verified' : ', not certified'}</td><td class="num">${ev.ms} ms</td>`; const chk = document.getElementById(`r${id}-check`); chk.parentNode.insertBefore(tr, chk); }
126
+ else if (ev.stage === 'sieve'){ const tr = document.createElement('tr'); tr.className = ev.taken ? '' : 'stage-live'; tr.innerHTML = `<th>Sieve</th><td>${ev.error ? 'failed' : `candidates named in the results: “${esc(ev.entity)}” covers ${ev.covered} of ${ev.of} constraint words${ev.runner ? `, next “${esc(ev.runner)}”` : ''}${ev.taken ? '' : '; not decisive'}`}</td><td class="num">${ev.ms} ms</td>`; const chk = document.getElementById(`r${id}-check`); chk.parentNode.insertBefore(tr, chk); }
127
+ else if (ev.stage === 'check'){ const by = {verbaliser: 'answer line written by our 113M verbaliser' + (ev.verbaliser_v==null ? '' : ` (verifier ${ev.verbaliser_v})`), decoder: 'lead line written by our 113M decoder', planner: 'lead line from our 113M planner\'s frame', template: 'lead line from a template'}[ev.lead_by]; const rej = ev.verbaliser && ev.lead_by !== 'verbaliser' ? ` (verbaliser line rejected: “${ev.verbaliser}”)` : ''; set('check', (by || (ev.hhem==null ? 'no lead line' : `support ${ev.hhem}`)) + rej, ev.ms); }
128
+ else if (ev.stage === 'done'){
129
+ es.close(); done();
130
+ const total = Math.round(performance.now() - t0);
131
+ document.getElementById(`mt${id}`).textContent = total + ' ms';
132
+ document.getElementById(`dt${id}`).textContent = ev.ms_models!=null ? `${ev.ms_models} ms of model time, the rest is the search` : '';
133
+ const a = document.getElementById(`a${id}`), refs = document.getElementById(`refs${id}`);
134
+ if (ev.tier === 3 && !ev.cited){
135
+ a.innerHTML = `<span class="none">There were no results matching the query.</span>`;
136
+ ['rank','verify','extract','check'].forEach(k => set(k, 'skipped', null)); return;
137
+ }
138
+ const tag = ev.tier === 1 ? '' : ' <span class="tag">[unverified]</span>'; // the models found a best match but would not certify it
139
+ const quote = esc(ev.cited);
140
+ let lead;
141
+ if (ev.span && ev.tier === 1){
142
+ const i = ev.cited.indexOf(ev.span);
143
+ lead = i >= 0 ? esc(ev.cited.slice(0,i)) + '<b>' + esc(ev.span) + '</b>' + esc(ev.cited.slice(i + ev.span.length)) : '<b>' + esc(ev.span) + '</b> — ' + quote;
144
+ } else { lead = quote; }
145
+ const witness = (ev.span && ev.support >= 2) ? ` <span class="muted">(stated by ${ev.support} sources${ev.verified_by === 'agreement' ? ', verified by their agreement' : ''})</span>` : '';
146
+ // the statement comes first when our own models wrote it (or when the quote is not a clean answer by itself); the quote is the evidence beneath it
147
+ const showLead = ev.lead && ev.tier === 1 && (ev.lead_by === 'verbaliser' || ev.lead_by === 'decoder' || ev.lead_by === 'planner' || !ev.quote_clean);
148
+ if (showLead){
149
+ a.innerHTML = `${md(ev.lead, id)}<br><span class="evidence">${quote}<sup class="ref"><a href="#ref${id}-1">[1]</a></sup>${witness}</span>`;
150
+ } else {
151
+ a.innerHTML = `${lead}<sup class="ref"><a href="#ref${id}-1">[1]</a></sup>${tag}${witness}`;
152
+ }
153
+ refs.innerHTML = `<h3>References</h3><ol class="refs"><li id="ref${id}-1"><a href="${esc(ev.url)}" target="_blank" rel="noopener">${esc(ev.title || ev.url)}</a> <span class="url">${esc(ev.url)}</span></li></ol>`;
154
+ }
155
+ };
156
+ es.onerror = () => { es.close(); done(); const a = document.getElementById(`a${id}`); if (a && a.querySelector('.none')) a.innerHTML = '<span class="none">The local server stopped answering. Start it again with local/webui.sh start.</span>'; };
157
+ }
158
+ function ask(text){
159
+ n += 1; const base = n;
160
+ const eng = picked('engine') || 'ddgs', vb = picked('answer') || 'own', cmp = picked('compare') || 'off';
161
+ const LEADNAME = {own: 'our 113M model writes the answer line', template: 'template answer line', none: 'quote only'};
162
+ let cols = [{prov: eng, vb, label: ''}];
163
+ if (cmp === 'engines') cols = [{prov: 'ddgs', vb, label: NAMES.ddgs}, {prov: 'serper', vb, label: NAMES.serper}];
164
+ if (cmp === 'answer') cols = [{prov: eng, vb: 'own', label: LEADNAME.own}, {prov: eng, vb: 'none', label: LEADNAME.none}];
165
+ const art = document.createElement('article');
166
+ art.innerHTML = `<h2>${esc(text)}</h2>` + (cols.length > 1 ? `<div class="cols">${cols.map((c, i) => `<div><h3 class="prov">${esc(c.label)}</h3>` + block(`${base}-${i}`, c.prov) + `</div>`).join('')}</div>` : block(`${base}-0`, cols[0].prov));
167
+ log.appendChild(art); art.scrollIntoView({block:'end'});
168
+ go.disabled = true; let pending = cols.length;
169
+ const done = () => { pending -= 1; if (pending <= 0){ go.disabled = false; q.focus(); } };
170
+ // the server answers one question at a time, so the second column's stages start when the first finishes
171
+ cols.forEach((c, i) => run(`${base}-${i}`, text, c.prov, done, c.vb));
172
+ }
173
+ form.addEventListener('submit', (e) => { e.preventDefault(); const t = q.value.trim(); if (!t || go.disabled) return; q.value = ''; ask(t); });
174
+ })();
175
+ </script>
176
+ </body>
177
+ </html>
gguf/gse-planner-120m-v2-Q8_0.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92d4c498657415ea67883dba13d3221123b16fd330930dc1989c94339a87fcb7
3
+ size 122229952
gguf/gse-sft-120m-Q8_0.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb0196c2904ad648d3397397b6515767c10d13a48764de8b93804a2cbf54b688
3
+ size 122229920
gguf/gse-verbaliser-120m-short-Q8_0.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7665ef5997222de701c43360dbd89ca3f62af100cf95badfb56c2ed691347b1
3
+ size 122229984
models/gse-ranker/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_cross_attention": false,
3
+ "architectures": [
4
+ "BertForSequenceClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": null,
8
+ "classifier_dropout": null,
9
+ "dtype": "float32",
10
+ "eos_token_id": null,
11
+ "gradient_checkpointing": false,
12
+ "hidden_act": "gelu",
13
+ "hidden_dropout_prob": 0.1,
14
+ "hidden_size": 384,
15
+ "id2label": {
16
+ "0": "LABEL_0"
17
+ },
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 1536,
20
+ "is_decoder": false,
21
+ "label2id": {
22
+ "LABEL_0": 0
23
+ },
24
+ "layer_norm_eps": 1e-12,
25
+ "max_position_embeddings": 512,
26
+ "model_type": "bert",
27
+ "num_attention_heads": 12,
28
+ "num_hidden_layers": 6,
29
+ "pad_token_id": 0,
30
+ "position_embedding_type": "absolute",
31
+ "sbert_ce_default_activation_function": "torch.nn.modules.linear.Identity",
32
+ "tie_word_embeddings": true,
33
+ "transformers_version": "5.22.1",
34
+ "type_vocab_size": 2,
35
+ "use_cache": true,
36
+ "vocab_size": 30522
37
+ }
models/gse-ranker/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7dde2650d4e130fa5681e2537fc1875a83971f4f28a346b7ceb26ae1a8758f30
3
+ size 90866412
models/gse-ranker/ranker_meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"gold_at_1": 0.9491945477075588, "n_test": 807, "pairs": 382361, "steps": 5974, "minutes": 2.916218602657318}
models/gse-ranker/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/gse-ranker/tokenizer_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "clean_up_tokenization_spaces": true,
4
+ "cls_token": "[CLS]",
5
+ "do_basic_tokenize": true,
6
+ "do_lower_case": true,
7
+ "is_local": false,
8
+ "local_files_only": false,
9
+ "mask_token": "[MASK]",
10
+ "model_max_length": 512,
11
+ "never_split": null,
12
+ "pad_token": "[PAD]",
13
+ "sep_token": "[SEP]",
14
+ "strip_accents": null,
15
+ "tokenize_chinese_chars": true,
16
+ "tokenizer_class": "BertTokenizer",
17
+ "unk_token": "[UNK]"
18
+ }
models/gse-verifier-v4-33m/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForSequenceClassification"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "classifier_dropout": null,
7
+ "gradient_checkpointing": false,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 384,
11
+ "id2label": {
12
+ "0": "LABEL_0"
13
+ },
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 1536,
16
+ "label2id": {
17
+ "LABEL_0": 0
18
+ },
19
+ "layer_norm_eps": 1e-12,
20
+ "max_position_embeddings": 512,
21
+ "model_type": "bert",
22
+ "num_attention_heads": 12,
23
+ "num_hidden_layers": 12,
24
+ "pad_token_id": 0,
25
+ "position_embedding_type": "absolute",
26
+ "sbert_ce_default_activation_function": "torch.nn.modules.linear.Identity",
27
+ "torch_dtype": "float32",
28
+ "transformers_version": "4.51.3",
29
+ "type_vocab_size": 2,
30
+ "use_cache": true,
31
+ "vocab_size": 30522
32
+ }
models/gse-verifier-v4-33m/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14f34669c51af8f27ea206b29d5bb0de45e2b69030db0927bb41e8f9cb632b2d
3
+ size 133464836
models/gse-verifier-v4-33m/special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
models/gse-verifier-v4-33m/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/gse-verifier-v4-33m/tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": true,
48
+ "extra_special_tokens": {},
49
+ "mask_token": "[MASK]",
50
+ "model_max_length": 512,
51
+ "never_split": null,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "strip_accents": null,
55
+ "tokenize_chinese_chars": true,
56
+ "tokenizer_class": "BertTokenizer",
57
+ "unk_token": "[UNK]"
58
+ }
models/gse-verifier-v4-33m/verifier_meta.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base": "cross-encoder/ms-marco-MiniLM-L-12-v2",
3
+ "train_pairs": 838763,
4
+ "steps": 13104,
5
+ "minutes": 5.3,
6
+ "eval": {
7
+ "n": 12439,
8
+ "pos": 1710,
9
+ "auc": 0.9401,
10
+ "thresholds": {
11
+ "0.0": {
12
+ "coverage_of_pos": 0.689,
13
+ "precision": 0.686,
14
+ "hard_neg_accepted": 493
15
+ },
16
+ "1.0": {
17
+ "coverage_of_pos": 0.58,
18
+ "precision": 0.782,
19
+ "hard_neg_accepted": 255
20
+ },
21
+ "2.0": {
22
+ "coverage_of_pos": 0.447,
23
+ "precision": 0.847,
24
+ "hard_neg_accepted": 128
25
+ },
26
+ "3.0": {
27
+ "coverage_of_pos": 0.301,
28
+ "precision": 0.923,
29
+ "hard_neg_accepted": 39
30
+ },
31
+ "4.0": {
32
+ "coverage_of_pos": 0.182,
33
+ "precision": 0.957,
34
+ "hard_neg_accepted": 13
35
+ }
36
+ }
37
+ }
38
+ }
models/gse-verifier-v4-33m/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
moss.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # RysoAI TinyQA-1 Moss: start the models and the question page, or ask one question from the terminal.
3
+ # ./moss.sh setup one-off: Python 3.11 venv with CPU torch and the pinned packages (~1 GB download)
4
+ # ./moss.sh start models + page on http://127.0.0.1:8091 (DuckDuckGo search, no keys needed)
5
+ # ./moss.sh ask "Who painted the Night Watch?" one answer in the terminal (needs ./moss.sh start)
6
+ # ./moss.sh index ~/Documents/notes index a folder of .txt/.md files (or a .jsonl of {"title","text"}) for offline use
7
+ # ./moss.sh ask --local "What is the boiling point of water at altitude?" answer from the indexed files, no network
8
+ # ./moss.sh stop | status
9
+ # Optional: put SERPER_API_KEY=... in .env next to this script for Google results and verifier-gated retries.
10
+ set -uo pipefail
11
+ ROOT=$(cd "$(dirname "$0")" && pwd); CODE="$ROOT/code"; PY="$ROOT/.venv/bin/python"; PORT=${MOSS_PORT:-8091}; URL="http://127.0.0.1:$PORT"
12
+ LOGS="$CODE/local/data"; mkdir -p "$LOGS"
13
+ stop_all() { pkill -f "webqa_server.py --port $PORT" 2>/dev/null; pkill -f "llama-server.*--port 80(89|93|95)" 2>/dev/null; true; }
14
+ case "${1:-start}" in
15
+ setup)
16
+ command -v python3.11 >/dev/null || { echo "needs Python 3.11 (macOS: brew install python@3.11)"; exit 1; }
17
+ python3.11 -m venv "$ROOT/.venv" && "$ROOT/.venv/bin/pip" install -q --upgrade pip && "$ROOT/.venv/bin/pip" install -q -r "$ROOT/requirements.txt" || exit 1
18
+ command -v llama-server >/dev/null || echo "optional: install llama.cpp (macOS: brew install llama.cpp) so our 113M models write the answer line; without it a template writes it"
19
+ echo "setup done; next: ./moss.sh start";;
20
+ start)
21
+ [ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
22
+ stop_all; sleep 1
23
+ [ -f "$ROOT/.env" ] && set -a && . "$ROOT/.env" && set +a
24
+ export GSE_BACKUP="$ROOT" GSE_VERIFIER="$ROOT/models/gse-verifier-v4-33m" GSE_RANKER="$ROOT/models/gse-ranker" GSE_TAU_V=1.5
25
+ export GSE_SOURCE_PENALTY=1 GSE_QUOTABLE=1 GSE_SEARCH=ddgs
26
+ # retries for uncertified answers go to Google; DuckDuckGo retries take 10-40 s, so without a Serper key they stay off
27
+ if [ -n "${SERPER_API_KEY:-}" ]; then export GSE_FALLBACK=1 GSE_PLANNER_RETRY=1 GSE_SIEVE_RETRY=1; else export GSE_FALLBACK=0 GSE_PLANNER_RETRY=0 GSE_SIEVE_RETRY=0; fi
28
+ if command -v llama-server >/dev/null; then
29
+ export GSE_VERBALIZE=own GSE_VERBALISER=http://127.0.0.1:8095
30
+ (nohup llama-server -m "$ROOT/gguf/gse-sft-120m-Q8_0.gguf" -c 2048 --port 8089 -t 4 --special > "$LOGS/decoder.log" 2>&1 &)
31
+ (nohup llama-server -m "$ROOT/gguf/gse-planner-120m-v2-Q8_0.gguf" -c 1024 --port 8093 -t 4 --special > "$LOGS/planner.log" 2>&1 &)
32
+ (nohup llama-server -m "$ROOT/gguf/gse-verbaliser-120m-short-Q8_0.gguf" -c 1024 --port 8095 -t 4 --special > "$LOGS/verbaliser.log" 2>&1 &)
33
+ else export GSE_VERBALIZE=template; echo "llama-server not found: the answer line comes from a template"; fi
34
+ (cd "$CODE" && nohup "$PY" local/webqa_server.py --port "$PORT" > "$LOGS/webui.log" 2>&1 &)
35
+ for i in $(seq 1 180); do curl -s -m 1 "$URL/health" | grep -q '"models": true' && { echo "ready: $URL/"; [ -t 1 ] && command -v open >/dev/null && open "$URL/"; exit 0; }; sleep 1; done
36
+ echo "did not start; see $LOGS/webui.log"; exit 1;;
37
+ index)
38
+ [ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
39
+ src=${2:?usage: ./moss.sh index <folder-or-jsonl>}; src=$(cd "$(dirname "$src")" && pwd)/$(basename "$src")
40
+ (cd "$CODE/local" && "$PY" -c 'import sys, webqa; print(f"indexed {webqa.index_corpus(sys.argv[1]):,} passages from {sys.argv[1]}")' "$src" 2>&1 | grep -v -i warning)
41
+ echo "restart the page (./moss.sh start) to pick up a new index";;
42
+ stop) stop_all; echo stopped;;
43
+ status) curl -s -m 1 "$URL/health" || echo "not running"; echo;;
44
+ ask)
45
+ curl -s -m 1 "$URL/health" | grep -q '"models": true' || { echo "not running: ./moss.sh start first"; exit 1; }
46
+ shift; PROV=ddgs; [ "${1:-}" = "--local" ] && { PROV=local; shift; }
47
+ Q=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(" ".join(sys.argv[1:])))' "$@")
48
+ curl -s -N -m 120 "$URL/ask?q=$Q&provider=$PROV" | grep '"stage": "done"' | python3 -c '
49
+ import sys, json; d = json.loads(sys.stdin.read()[6:])
50
+ if d.get("tier") == 1:
51
+ if d.get("lead"): print(d["lead"].replace("**", ""))
52
+ print(" \u201c" + d["cited"] + "\u201d" + (" (stated by %d sources)" % d["support"] if (d.get("support") or 0) >= 2 else ""))
53
+ print(" " + str(d.get("url")))
54
+ else: print("No verified answer. The page shows the closest sentences it found, unchecked.")' ;;
55
+ *) sed -n 2,8p "$0";;
56
+ esac
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # RysoAI TinyQA-1 Moss, tested on Python 3.11, CPU only. Versions are the ones the benchmarks ran on.
2
+ torch==2.15.0
3
+ transformers==5.22.1
4
+ sentence-transformers==6.2.0
5
+ ddgs==9.16.1
6
+ numpy==2.4.6
7
+ # only for page reading (GSE_PAGES) and for re-running the benchmarks
8
+ trafilatura==2.3.1
9
+ datasets==5.2.0
results/freshqa_600_serper_summary.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bench": "freshqa",
3
+ "n": 600,
4
+ "search": "serper",
5
+ "judge": "gpt-4.1-2025-04-14",
6
+ "attempt_all": {
7
+ "n": 600,
8
+ "correct": 0.395,
9
+ "incorrect": 0.523,
10
+ "not_attempted": 0.082,
11
+ "correct_given_attempted": 0.43,
12
+ "f_score": 0.412
13
+ },
14
+ "verified_only": {
15
+ "n": 600,
16
+ "correct": 0.308,
17
+ "incorrect": 0.202,
18
+ "not_attempted": 0.49,
19
+ "correct_given_attempted": 0.605,
20
+ "f_score": 0.408
21
+ },
22
+ "consensus": {
23
+ "n": 600,
24
+ "correct": 0.395,
25
+ "incorrect": 0.523,
26
+ "not_attempted": 0.082,
27
+ "correct_given_attempted": 0.43,
28
+ "f_score": 0.412
29
+ },
30
+ "verified_and_agreed": {
31
+ "n": 600,
32
+ "correct": 0.265,
33
+ "incorrect": 0.132,
34
+ "not_attempted": 0.603,
35
+ "correct_given_attempted": 0.668,
36
+ "f_score": 0.379
37
+ },
38
+ "containment": 0.358,
39
+ "by_group": {
40
+ "fast-changing": {
41
+ "n": 155,
42
+ "attempt_all": 0.135,
43
+ "verified_only_f": 0.131
44
+ },
45
+ "never-changing": {
46
+ "n": 223,
47
+ "attempt_all": 0.574,
48
+ "verified_only_f": 0.571
49
+ },
50
+ "slow-changing": {
51
+ "n": 222,
52
+ "attempt_all": 0.396,
53
+ "verified_only_f": 0.412
54
+ }
55
+ }
56
+ }
results/popqa_1000_serper_summary.json ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bench": "popqa",
3
+ "n": 1000,
4
+ "search": "serper",
5
+ "judge": "gpt-4.1-2025-04-14",
6
+ "attempt_all": {
7
+ "n": 1000,
8
+ "correct": 0.474,
9
+ "incorrect": 0.485,
10
+ "not_attempted": 0.041,
11
+ "correct_given_attempted": 0.494,
12
+ "f_score": 0.484
13
+ },
14
+ "verified_only": {
15
+ "n": 1000,
16
+ "correct": 0.421,
17
+ "incorrect": 0.236,
18
+ "not_attempted": 0.343,
19
+ "correct_given_attempted": 0.641,
20
+ "f_score": 0.508
21
+ },
22
+ "consensus": {
23
+ "n": 1000,
24
+ "correct": 0.474,
25
+ "incorrect": 0.485,
26
+ "not_attempted": 0.041,
27
+ "correct_given_attempted": 0.494,
28
+ "f_score": 0.484
29
+ },
30
+ "verified_and_agreed": {
31
+ "n": 1000,
32
+ "correct": 0.323,
33
+ "incorrect": 0.146,
34
+ "not_attempted": 0.531,
35
+ "correct_given_attempted": 0.689,
36
+ "f_score": 0.44
37
+ },
38
+ "containment": 0.492,
39
+ "by_group": {
40
+ "author": {
41
+ "n": 175,
42
+ "attempt_all": 0.371,
43
+ "verified_only_f": 0.414
44
+ },
45
+ "capital": {
46
+ "n": 21,
47
+ "attempt_all": 0.619,
48
+ "verified_only_f": 0.667
49
+ },
50
+ "capital of": {
51
+ "n": 3,
52
+ "attempt_all": 0.0,
53
+ "verified_only_f": 0.0
54
+ },
55
+ "composer": {
56
+ "n": 42,
57
+ "attempt_all": 0.31,
58
+ "verified_only_f": 0.343
59
+ },
60
+ "country": {
61
+ "n": 114,
62
+ "attempt_all": 0.684,
63
+ "verified_only_f": 0.751
64
+ },
65
+ "director": {
66
+ "n": 121,
67
+ "attempt_all": 0.289,
68
+ "verified_only_f": 0.33
69
+ },
70
+ "father": {
71
+ "n": 31,
72
+ "attempt_all": 0.581,
73
+ "verified_only_f": 0.615
74
+ },
75
+ "genre": {
76
+ "n": 91,
77
+ "attempt_all": 0.198,
78
+ "verified_only_f": 0.206
79
+ },
80
+ "mother": {
81
+ "n": 4,
82
+ "attempt_all": 0.5,
83
+ "verified_only_f": 0.333
84
+ },
85
+ "occupation": {
86
+ "n": 72,
87
+ "attempt_all": 0.764,
88
+ "verified_only_f": 0.758
89
+ },
90
+ "place of birth": {
91
+ "n": 98,
92
+ "attempt_all": 0.704,
93
+ "verified_only_f": 0.737
94
+ },
95
+ "producer": {
96
+ "n": 61,
97
+ "attempt_all": 0.115,
98
+ "verified_only_f": 0.13
99
+ },
100
+ "religion": {
101
+ "n": 18,
102
+ "attempt_all": 0.889,
103
+ "verified_only_f": 0.839
104
+ },
105
+ "screenwriter": {
106
+ "n": 62,
107
+ "attempt_all": 0.242,
108
+ "verified_only_f": 0.304
109
+ },
110
+ "sport": {
111
+ "n": 87,
112
+ "attempt_all": 0.805,
113
+ "verified_only_f": 0.727
114
+ }
115
+ }
116
+ }
results/repro.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "simpleqa_1000_ddgs": {
3
+ "n": 1000,
4
+ "compared": 1000,
5
+ "identical": 996,
6
+ "differ": 4,
7
+ "official_correct": 71.3,
8
+ "release_correct_bounds": [
9
+ 71.3,
10
+ 71.7
11
+ ],
12
+ "official_verified_correct": 60.9,
13
+ "release_verified_correct_bounds": [
14
+ 60.9,
15
+ 61.3
16
+ ],
17
+ "tier_changes": 4
18
+ },
19
+ "simpleqa_1000_serper": {
20
+ "n": 1000,
21
+ "compared": 1000,
22
+ "identical": 1000,
23
+ "differ": 0,
24
+ "official_correct": 69.6,
25
+ "release_correct_bounds": [
26
+ 69.6,
27
+ 69.6
28
+ ],
29
+ "official_verified_correct": 59.2,
30
+ "release_verified_correct_bounds": [
31
+ 59.2,
32
+ 59.2
33
+ ],
34
+ "tier_changes": 0
35
+ },
36
+ "freshqa_600_serper": {
37
+ "n": 600,
38
+ "compared": 600,
39
+ "identical": 600,
40
+ "differ": 0,
41
+ "official_correct": 39.5,
42
+ "release_correct_bounds": [
43
+ 39.5,
44
+ 39.5
45
+ ],
46
+ "official_verified_correct": 30.8,
47
+ "release_verified_correct_bounds": [
48
+ 30.8,
49
+ 30.8
50
+ ],
51
+ "tier_changes": 0
52
+ },
53
+ "popqa_1000_serper": {
54
+ "n": 1000,
55
+ "compared": 991,
56
+ "identical": 991,
57
+ "differ": 0,
58
+ "official_correct": 47.4,
59
+ "release_correct_bounds": [
60
+ 47.4,
61
+ 47.4
62
+ ],
63
+ "official_verified_correct": 42.1,
64
+ "release_verified_correct_bounds": [
65
+ 42.1,
66
+ 42.1
67
+ ],
68
+ "tier_changes": 0
69
+ }
70
+ }
results/simpleqa_1000_ddgs_summary.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bench": "simpleqa",
3
+ "n": 1000,
4
+ "search": "ddgs",
5
+ "judge": "gpt-4.1-2025-04-14",
6
+ "attempt_all": {
7
+ "n": 1000,
8
+ "correct": 0.713,
9
+ "incorrect": 0.137,
10
+ "not_attempted": 0.15,
11
+ "correct_given_attempted": 0.839,
12
+ "f_score": 0.771
13
+ },
14
+ "verified_only": {
15
+ "n": 1000,
16
+ "correct": 0.609,
17
+ "incorrect": 0.062,
18
+ "not_attempted": 0.329,
19
+ "correct_given_attempted": 0.908,
20
+ "f_score": 0.729
21
+ },
22
+ "consensus": {
23
+ "n": 1000,
24
+ "correct": 0.713,
25
+ "incorrect": 0.137,
26
+ "not_attempted": 0.15,
27
+ "correct_given_attempted": 0.839,
28
+ "f_score": 0.771
29
+ },
30
+ "verified_and_agreed": {
31
+ "n": 1000,
32
+ "correct": 0.518,
33
+ "incorrect": 0.045,
34
+ "not_attempted": 0.437,
35
+ "correct_given_attempted": 0.92,
36
+ "f_score": 0.663
37
+ },
38
+ "containment": 0.535,
39
+ "by_group": {
40
+ "Art": {
41
+ "n": 145,
42
+ "attempt_all": 0.71,
43
+ "verified_only_f": 0.771
44
+ },
45
+ "Geography": {
46
+ "n": 111,
47
+ "attempt_all": 0.82,
48
+ "verified_only_f": 0.819
49
+ },
50
+ "History": {
51
+ "n": 52,
52
+ "attempt_all": 0.75,
53
+ "verified_only_f": 0.764
54
+ },
55
+ "Music": {
56
+ "n": 102,
57
+ "attempt_all": 0.765,
58
+ "verified_only_f": 0.74
59
+ },
60
+ "Other": {
61
+ "n": 102,
62
+ "attempt_all": 0.716,
63
+ "verified_only_f": 0.743
64
+ },
65
+ "Politics": {
66
+ "n": 176,
67
+ "attempt_all": 0.705,
68
+ "verified_only_f": 0.727
69
+ },
70
+ "Science and technology": {
71
+ "n": 160,
72
+ "attempt_all": 0.65,
73
+ "verified_only_f": 0.62
74
+ },
75
+ "Sports": {
76
+ "n": 117,
77
+ "attempt_all": 0.684,
78
+ "verified_only_f": 0.728
79
+ },
80
+ "TV shows": {
81
+ "n": 20,
82
+ "attempt_all": 0.85,
83
+ "verified_only_f": 0.824
84
+ },
85
+ "Video games": {
86
+ "n": 15,
87
+ "attempt_all": 0.267,
88
+ "verified_only_f": 0.19
89
+ }
90
+ }
91
+ }
results/simpleqa_1000_serper_summary.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bench": "simpleqa",
3
+ "n": 1000,
4
+ "search": "serper",
5
+ "judge": "gpt-4.1-2025-04-14",
6
+ "attempt_all": {
7
+ "n": 1000,
8
+ "correct": 0.696,
9
+ "incorrect": 0.186,
10
+ "not_attempted": 0.118,
11
+ "correct_given_attempted": 0.789,
12
+ "f_score": 0.74
13
+ },
14
+ "verified_only": {
15
+ "n": 1000,
16
+ "correct": 0.592,
17
+ "incorrect": 0.075,
18
+ "not_attempted": 0.333,
19
+ "correct_given_attempted": 0.888,
20
+ "f_score": 0.71
21
+ },
22
+ "consensus": {
23
+ "n": 1000,
24
+ "correct": 0.696,
25
+ "incorrect": 0.186,
26
+ "not_attempted": 0.118,
27
+ "correct_given_attempted": 0.789,
28
+ "f_score": 0.74
29
+ },
30
+ "verified_and_agreed": {
31
+ "n": 1000,
32
+ "correct": 0.443,
33
+ "incorrect": 0.042,
34
+ "not_attempted": 0.515,
35
+ "correct_given_attempted": 0.913,
36
+ "f_score": 0.597
37
+ },
38
+ "containment": 0.531,
39
+ "by_group": {
40
+ "Art": {
41
+ "n": 145,
42
+ "attempt_all": 0.697,
43
+ "verified_only_f": 0.714
44
+ },
45
+ "Geography": {
46
+ "n": 111,
47
+ "attempt_all": 0.766,
48
+ "verified_only_f": 0.774
49
+ },
50
+ "History": {
51
+ "n": 52,
52
+ "attempt_all": 0.731,
53
+ "verified_only_f": 0.744
54
+ },
55
+ "Music": {
56
+ "n": 102,
57
+ "attempt_all": 0.657,
58
+ "verified_only_f": 0.663
59
+ },
60
+ "Other": {
61
+ "n": 102,
62
+ "attempt_all": 0.775,
63
+ "verified_only_f": 0.768
64
+ },
65
+ "Politics": {
66
+ "n": 176,
67
+ "attempt_all": 0.693,
68
+ "verified_only_f": 0.73
69
+ },
70
+ "Science and technology": {
71
+ "n": 160,
72
+ "attempt_all": 0.637,
73
+ "verified_only_f": 0.64
74
+ },
75
+ "Sports": {
76
+ "n": 117,
77
+ "attempt_all": 0.675,
78
+ "verified_only_f": 0.677
79
+ },
80
+ "TV shows": {
81
+ "n": 20,
82
+ "attempt_all": 0.8,
83
+ "verified_only_f": 0.824
84
+ },
85
+ "Video games": {
86
+ "n": 15,
87
+ "attempt_all": 0.467,
88
+ "verified_only_f": 0.476
89
+ }
90
+ }
91
+ }