RysoAI commited on
Commit
da32fba
·
verified ·
1 Parent(s): bdfee6e

Clean package: terminal code only, neutral names, no comments

Browse files
Files changed (48) hide show
  1. .gitattributes +3 -0
  2. NOTICE.md +2 -2
  3. README.md +6 -6
  4. SHA256SUMS +23 -41
  5. code/gse_mini/__init__.py +0 -1
  6. code/gse_mini/answer.py +0 -263
  7. code/gse_mini/dense.py +0 -31
  8. code/gse_mini/ingest/__init__.py +0 -1
  9. code/gse_mini/ingest/text.py +0 -45
  10. code/gse_mini/ingest/zim.py +0 -91
  11. code/gse_mini/planner.py +0 -167
  12. code/gse_mini/prompt.py +0 -60
  13. code/gse_mini/reader.py +0 -44
  14. code/gse_mini/render.py +0 -67
  15. code/gse_mini/rerank.py +0 -66
  16. code/gse_mini/retrieve.py +0 -429
  17. code/gse_mini/serve.py +0 -37
  18. code/gse_mini/store.py +0 -378
  19. code/gse_mini/verify.py +0 -65
  20. code/local/bench_web.py +0 -108
  21. code/local/experiments/sieve.py +0 -91
  22. code/local/moss_cli.py +0 -30
  23. code/local/moss_server.py +0 -37
  24. code/local/regrade.py +0 -55
  25. code/local/webqa.py +0 -603
  26. code/tinyqa/__init__.py +0 -0
  27. code/tinyqa/cli.py +35 -0
  28. code/{gse_mini → tinyqa}/extract.py +35 -39
  29. code/tinyqa/pipeline.py +691 -0
  30. code/tinyqa/server.py +49 -0
  31. code/tinyqa/sieve.py +57 -0
  32. gguf/{gse-planner-120m-v2-Q8_0.gguf → tinyqa-1-moss-glue-Q8_0.gguf} +2 -2
  33. gguf/{gse-sft-120m-Q8_0.gguf → tinyqa-1-moss-planner-Q8_0.gguf} +2 -2
  34. gguf/{gse-verbaliser-120m-short-Q8_0.gguf → tinyqa-1-moss-verbaliser-Q8_0.gguf} +2 -2
  35. models/gse-ranker/ranker_meta.json +0 -1
  36. models/gse-verifier-v4-33m/verifier_meta.json +0 -38
  37. models/{gse-ranker → ranker}/config.json +0 -0
  38. models/{gse-ranker → ranker}/model.safetensors +0 -0
  39. models/{gse-ranker → ranker}/tokenizer.json +0 -0
  40. models/{gse-ranker → ranker}/tokenizer_config.json +0 -0
  41. models/{gse-verifier-v4-33m → verifier}/config.json +0 -0
  42. models/{gse-verifier-v4-33m → verifier}/model.safetensors +0 -0
  43. models/{gse-verifier-v4-33m → verifier}/special_tokens_map.json +0 -0
  44. models/{gse-verifier-v4-33m → verifier}/tokenizer.json +0 -0
  45. models/{gse-verifier-v4-33m → verifier}/tokenizer_config.json +0 -0
  46. models/{gse-verifier-v4-33m → verifier}/vocab.txt +0 -0
  47. moss.sh +15 -15
  48. requirements.txt +1 -3
.gitattributes CHANGED
@@ -36,3 +36,6 @@ saved_model/**/* 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
 
 
 
 
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
39
+ gguf/tinyqa-1-moss-glue-Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
40
+ gguf/tinyqa-1-moss-planner-Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
41
+ gguf/tinyqa-1-moss-verbaliser-Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
NOTICE.md CHANGED
@@ -6,8 +6,8 @@ RysoAI TinyQA-1 Moss code and the weights in `models/` and `gguf/` are released
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
 
 
6
 
7
  | component | file | license |
8
  |---|---|---|
9
+ | Ranker, 22M | `models/ranker` | Apache-2.0; fine-tuned from `cross-encoder/ms-marco-MiniLM-L6-v2` (Apache-2.0) |
10
+ | Verifier, 33M | `models/verifier` | 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
 
README.md CHANGED
@@ -92,12 +92,12 @@ 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
 
@@ -120,7 +120,7 @@ scratch on public educational web text and then fine-tuned. Training data was dr
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 in the benchmark runs.
124
 
125
  ## 5. Evaluations
126
 
 
92
 
93
  | component | role | parameters | file |
94
  |---|---|---|---|
95
+ | Ranker | orders candidate sentences by relevance to the question | 22M | `models/ranker` |
96
+ | Verifier | scores whether a sentence states the answer; this score is the confidence | 33M | `models/verifier` |
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/tinyqa-1-moss-verbaliser-Q8_0.gguf` |
99
+ | Glue decoder (optional) | fallback answer-line writer | 113M | `gguf/tinyqa-1-moss-glue-Q8_0.gguf` |
100
+ | Planner (optional) | rewrites queries for retries and supplies answer frames | 113M | `gguf/tinyqa-1-moss-planner-Q8_0.gguf` |
101
 
102
  **Parameters.** 89M for the core answering path (ranker, verifier, reader), 429M with all three optional decoders.
103
 
 
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 were excluded as sources in the benchmark runs.
124
 
125
  ## 5. Evaluations
126
 
SHA256SUMS CHANGED
@@ -1,45 +1,27 @@
1
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./LICENSE
2
- d1f106ed157597e0420995633b499c9c60211a3769491cff3a7802c8b9b8e036 ./NOTICE.md
3
- 10952257d29078b82f64ea50a971207459d647d4c586e75fb5fabd93a14e6ff3 ./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
- c831fcf7c72aeb837a2d8d0a5958a2068c115b76c973a0876e12eee70ba9bb07 ./code/local/experiments/sieve.py
22
- 1ff4fd443ebd65e72099b8e9e264fed95b8b58b954d306109f54fb857fd21600 ./code/local/moss_cli.py
23
- 9d1bb0cfdefbe1e2de2eac3abe00915db6dba1fb6dd8bca79024c0700c39232e ./code/local/moss_server.py
24
- ad1fd84941ed0f772077a450e548741da4837449c3000fd48d8fcdaab93582cd ./code/local/regrade.py
25
- 7e2de6af191529298c3907703e36176f9773c65559a0ecbc5a81d5baf5ce0857 ./code/local/webqa.py
26
- 92d4c498657415ea67883dba13d3221123b16fd330930dc1989c94339a87fcb7 ./gguf/gse-planner-120m-v2-Q8_0.gguf
27
- cb0196c2904ad648d3397397b6515767c10d13a48764de8b93804a2cbf54b688 ./gguf/gse-sft-120m-Q8_0.gguf
28
- e7665ef5997222de701c43360dbd89ca3f62af100cf95badfb56c2ed691347b1 ./gguf/gse-verbaliser-120m-short-Q8_0.gguf
29
- 1890f7157c851bfea48ea028bb61d035a3f0909373a74795bc71b1e720ceccc6 ./models/gse-ranker/config.json
30
- 7dde2650d4e130fa5681e2537fc1875a83971f4f28a346b7ceb26ae1a8758f30 ./models/gse-ranker/model.safetensors
31
- 9d4edd1d931b6d3e8b59a561202f08aa068dacfaf9340236f3c5a3c6f1c28220 ./models/gse-ranker/ranker_meta.json
32
- 851ca67100d372ca3ae031a6abd168f53489eebfd7d89523f35c5c9b4d372c3c ./models/gse-ranker/tokenizer.json
33
- 649e41f8cf1cb1b67acc193795ccaef07bcaa3c4e0fc7d286ba8255fab79cffa ./models/gse-ranker/tokenizer_config.json
34
- e4288df3d671124dd6d41ee93e147b4fb268cdd2b72df1a6e369239488edd2ec ./models/gse-verifier-v4-33m/config.json
35
- 14f34669c51af8f27ea206b29d5bb0de45e2b69030db0927bb41e8f9cb632b2d ./models/gse-verifier-v4-33m/model.safetensors
36
- 5d5b662e421ea9fac075174bb0688ee0d9431699900b90662acd44b2a350503a ./models/gse-verifier-v4-33m/special_tokens_map.json
37
- 851ca67100d372ca3ae031a6abd168f53489eebfd7d89523f35c5c9b4d372c3c ./models/gse-verifier-v4-33m/tokenizer.json
38
- 7b082b48a08a0b5c5939d99472e33addce3d96202155e33f7928cecd171186a0 ./models/gse-verifier-v4-33m/tokenizer_config.json
39
- 060042f8f498f6039fc05a5771607a91d9d959dc7874f1a37cec806fb4ea21be ./models/gse-verifier-v4-33m/verifier_meta.json
40
- 07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3 ./models/gse-verifier-v4-33m/vocab.txt
41
- eba0eff6c79652da6623e50c7422b6f05b4d73e58b4d561ae1787936d8fec5e7 ./moss.sh
42
- d02efcc9918800b351ab5a719ebe0d045688c24e5ffa2ff2731c8ce8f1ab63ce ./requirements.txt
43
  16095ae79e1a75787c2e673a9c4f39a76a77aba0eb7af9faad3252a7aefb8f8f ./results/freshqa_600_serper_summary.json
44
  74a4fefd1e361e24f32c84e1f47e9ba429b18248b42402fa39e6f16647655ba7 ./results/popqa_1000_serper_summary.json
45
  4221c9e3e20152b5a7b978ba8b3f7db9ed8e59122eec01ef371fd8f235872654 ./results/repro.json
 
1
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./LICENSE
2
+ 0954bc2b4e2a508b699dc31c346ae008fa40ac40be59c0ff01988d4e100e297b ./NOTICE.md
3
+ 6cbfa9bd0a052427518da40d3b2bbb69f2a887aa4cc6851a0bbb1eb3537d39e6 ./README.md
4
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./code/tinyqa/__init__.py
5
+ cb58baa781b915bff4830b832ea0687d75aab0efd792f89e0f43c50bbca5d0c9 ./code/tinyqa/cli.py
6
+ f6d367b02c25e64f4cee86c89064192561748152891eab797ac7f83a0e0f720c ./code/tinyqa/extract.py
7
+ 097e101c069b1d140d6d95cfd6afaa6cbab6dfc03da08c528ddac54f1b4ba7f4 ./code/tinyqa/pipeline.py
8
+ d9c9ba91dc99ceeed92cd08fdb3fe126a929929e2cf25a2585509f0dd7609492 ./code/tinyqa/server.py
9
+ a6effd97e8d20ba744f1779940417ba601729d8bec165f8f3a940db138dabb62 ./code/tinyqa/sieve.py
10
+ bdb15946920cdac9ea17eaeefa38095dd2fa17516dcf0bf582f781d685554520 ./gguf/tinyqa-1-moss-glue-Q8_0.gguf
11
+ 4a963495409d2838fcc3136c0d573b1d4d907e5d043c6cc6e4652ddae7d857c5 ./gguf/tinyqa-1-moss-planner-Q8_0.gguf
12
+ dbd60b72ec1e5668c2e29e8bb70e393495a3d814e51ea9086fe39ebd649b52e4 ./gguf/tinyqa-1-moss-verbaliser-Q8_0.gguf
13
+ 1890f7157c851bfea48ea028bb61d035a3f0909373a74795bc71b1e720ceccc6 ./models/ranker/config.json
14
+ 7dde2650d4e130fa5681e2537fc1875a83971f4f28a346b7ceb26ae1a8758f30 ./models/ranker/model.safetensors
15
+ 851ca67100d372ca3ae031a6abd168f53489eebfd7d89523f35c5c9b4d372c3c ./models/ranker/tokenizer.json
16
+ 649e41f8cf1cb1b67acc193795ccaef07bcaa3c4e0fc7d286ba8255fab79cffa ./models/ranker/tokenizer_config.json
17
+ e4288df3d671124dd6d41ee93e147b4fb268cdd2b72df1a6e369239488edd2ec ./models/verifier/config.json
18
+ 14f34669c51af8f27ea206b29d5bb0de45e2b69030db0927bb41e8f9cb632b2d ./models/verifier/model.safetensors
19
+ 5d5b662e421ea9fac075174bb0688ee0d9431699900b90662acd44b2a350503a ./models/verifier/special_tokens_map.json
20
+ 851ca67100d372ca3ae031a6abd168f53489eebfd7d89523f35c5c9b4d372c3c ./models/verifier/tokenizer.json
21
+ 7b082b48a08a0b5c5939d99472e33addce3d96202155e33f7928cecd171186a0 ./models/verifier/tokenizer_config.json
22
+ 07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3 ./models/verifier/vocab.txt
23
+ 31c1b475b54d1a772ce64fd25f446fe15063ab5789786d62f8ffced6526a7549 ./moss.sh
24
+ 3cb3eb5f41a5191a28c7602324ee680cb34f2df5907b06603e7382ca521d8253 ./requirements.txt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  16095ae79e1a75787c2e673a9c4f39a76a77aba0eb7af9faad3252a7aefb8f8f ./results/freshqa_600_serper_summary.json
26
  74a4fefd1e361e24f32c84e1f47e9ba429b18248b42402fa39e6f16647655ba7 ./results/popqa_1000_serper_summary.json
27
  4221c9e3e20152b5a7b978ba8b3f7db9ed8e59122eec01ef371fd8f235872654 ./results/repro.json
code/gse_mini/__init__.py DELETED
@@ -1 +0,0 @@
1
- """GSE-mini: quote-first retrieval harness. Corpus-agnostic; see GSE-DESIGN.md §14."""
 
 
code/gse_mini/answer.py DELETED
@@ -1,263 +0,0 @@
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 DELETED
@@ -1,31 +0,0 @@
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/ingest/__init__.py DELETED
@@ -1 +0,0 @@
1
- """Source adapters. Each yields doc records: {"kb","title","path","sections":[(name,text)],"aliases":[...]}."""
 
 
code/gse_mini/ingest/text.py DELETED
@@ -1,45 +0,0 @@
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 DELETED
@@ -1,91 +0,0 @@
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 DELETED
@@ -1,167 +0,0 @@
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 DELETED
@@ -1,60 +0,0 @@
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 DELETED
@@ -1,44 +0,0 @@
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 DELETED
@@ -1,67 +0,0 @@
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 DELETED
@@ -1,66 +0,0 @@
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 DELETED
@@ -1,429 +0,0 @@
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 DELETED
@@ -1,37 +0,0 @@
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 DELETED
@@ -1,378 +0,0 @@
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 DELETED
@@ -1,65 +0,0 @@
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 DELETED
@@ -1,108 +0,0 @@
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/sieve.py DELETED
@@ -1,91 +0,0 @@
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/moss_cli.py DELETED
@@ -1,30 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Terminal front end for ./moss.sh ask: one question from the arguments, or an interactive prompt when there are none."""
3
- import json, os, sys, urllib.parse, urllib.request
4
- URL, PROV, ARGS = sys.argv[1], os.environ.get("MOSS_PROVIDER", "ddgs"), sys.argv[2:]
5
- if ARGS[:1] == ["--local"]: PROV, ARGS = "local", ARGS[1:]
6
- NAMES = {"ddgs": "DuckDuckGo", "serper": "Google", "local": "the local index"}
7
-
8
- def ask(q):
9
- try:
10
- with urllib.request.urlopen(f"{URL}/ask?q={urllib.parse.quote(q)}&provider={PROV}", timeout=180) as r: d = json.load(r)
11
- except Exception as ex:
12
- print(f"the model service stopped answering ({type(ex).__name__}); run ./moss.sh start"); return
13
- if d.get("tier") == 1:
14
- if d.get("lead"): print(d["lead"].replace("**", ""))
15
- print(" “" + d["cited"] + "”" + (" (stated by %d sources)" % d["support"] if (d.get("support") or 0) >= 2 else ""))
16
- print(" " + str(d.get("url")))
17
- elif d.get("tier") == 3 and not d.get("cited"):
18
- print("No results." + (" The local index is empty or missing: run ./moss.sh index <folder> first." if PROV == "local" else ""))
19
- else:
20
- print("No verified answer.")
21
-
22
- if ARGS:
23
- ask(" ".join(ARGS))
24
- else:
25
- print(f"RysoAI TinyQA-1 Moss, answering from {NAMES[PROV]}. Type a question, or press Enter on an empty line to quit.")
26
- while True:
27
- try: q = input("\n? ").strip()
28
- except (EOFError, KeyboardInterrupt): print(); break
29
- if not q: break
30
- ask(q)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/local/moss_server.py DELETED
@@ -1,37 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Background model service for ./moss.sh: loads the models once so each terminal question is answered in seconds.
3
- Listens on 127.0.0.1 only and has no web page: GET /health, GET /ask?q=...&provider=ddgs|serper|local returns one JSON answer."""
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
- STACK = None; LOCK = threading.Lock()
9
- KEEP = ("tier", "lead", "cited", "span", "support", "url", "title", "verified_by")
10
-
11
- class H(BaseHTTPRequestHandler):
12
- def log_message(self, *a): pass
13
- def _json(self, obj, code=200):
14
- body = json.dumps(obj, ensure_ascii=False).encode()
15
- self.send_response(code); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
16
- def do_GET(self):
17
- u = urllib.parse.urlparse(self.path)
18
- if u.path == "/health": return self._json({"ok": True, "models": STACK is not None})
19
- if u.path != "/ask": return self._json({"error": "not found"}, 404)
20
- qs = urllib.parse.parse_qs(u.query); q = qs.get("q", [""])[0].strip(); provider = qs.get("provider", ["ddgs"])[0]
21
- if not q: return self._json({"tier": 3, "why": "empty question"})
22
- with LOCK: # the models answer one question at a time
23
- out = STACK.answer(q, provider=provider)
24
- webqa.save_caches()
25
- self._json({k: out.get(k) for k in KEEP})
26
-
27
- def main():
28
- global STACK
29
- ap = argparse.ArgumentParser(); ap.add_argument("--port", type=int, default=8091); a = ap.parse_args()
30
- s = webqa.Stack()
31
- s.rank.predict([("warm up", "warm up")], show_progress_bar=False); s.verify.predict([("warm up", "warm up")], show_progress_bar=False) # no search at start-up
32
- STACK = s
33
- print(f"[moss] models loaded on 127.0.0.1:{a.port}", flush=True)
34
- ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
35
-
36
- if __name__ == "__main__":
37
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/local/regrade.py DELETED
@@ -1,55 +0,0 @@
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 DELETED
@@ -1,603 +0,0 @@
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/tinyqa/__init__.py ADDED
File without changes
code/tinyqa/cli.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, os, sys, urllib.parse, urllib.request
2
+ URL, PROV, ARGS = (sys.argv[1], os.environ.get('MOSS_PROVIDER', 'ddgs'), sys.argv[2:])
3
+ if ARGS[:1] == ['--local']:
4
+ PROV, ARGS = ('local', ARGS[1:])
5
+ NAMES = {'ddgs': 'DuckDuckGo', 'serper': 'Google', 'local': 'the local index'}
6
+
7
+ def ask(q):
8
+ try:
9
+ with urllib.request.urlopen(f'{URL}/ask?q={urllib.parse.quote(q)}&provider={PROV}', timeout=180) as r:
10
+ d = json.load(r)
11
+ except Exception as ex:
12
+ print(f'the model service stopped answering ({type(ex).__name__}); run ./moss.sh start')
13
+ return
14
+ if d.get('tier') == 1:
15
+ if d.get('lead'):
16
+ print(d['lead'].replace('**', ''))
17
+ print(' “' + d['cited'] + '”' + (' (stated by %d sources)' % d['support'] if (d.get('support') or 0) >= 2 else ''))
18
+ print(' ' + str(d.get('url')))
19
+ elif d.get('tier') == 3 and (not d.get('cited')):
20
+ print('No results.' + (' The local index is empty or missing: run ./moss.sh index <folder> first.' if PROV == 'local' else ''))
21
+ else:
22
+ print('No verified answer.')
23
+ if ARGS:
24
+ ask(' '.join(ARGS))
25
+ else:
26
+ print(f'RysoAI TinyQA-1 Moss, answering from {NAMES[PROV]}. Type a question, or press Enter on an empty line to quit.')
27
+ while True:
28
+ try:
29
+ q = input('\n? ').strip()
30
+ except (EOFError, KeyboardInterrupt):
31
+ print()
32
+ break
33
+ if not q:
34
+ break
35
+ ask(q)
code/{gse_mini → tinyqa}/extract.py RENAMED
@@ -1,31 +1,31 @@
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:
@@ -34,15 +34,14 @@ class _SpanModel:
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
@@ -50,53 +49,50 @@ def get():
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
 
 
 
 
1
  from __future__ import annotations
2
  import os, re
3
+ MODEL = os.environ.get('MOSS_READER_SPAN', 'deepset/minilm-uncased-squad2')
4
  _QA = None
5
+ _OFF = os.environ.get('MOSS_EXTRACT', '1') == '0'
6
 
7
  class _SpanModel:
8
+
9
  def __init__(self, name):
10
  import torch
11
  from transformers import AutoTokenizer, AutoModelForQuestionAnswering
12
+ torch.set_num_threads(int(os.environ.get('MOSS_EXTRACT_THREADS', '4')))
13
+ self.tok = AutoTokenizer.from_pretrained(name)
14
+ self.model = AutoModelForQuestionAnswering.from_pretrained(name).eval()
15
+
16
  def __call__(self, question, context, max_answer_tokens=24):
17
  import torch
18
+ enc = self.tok(question, context, truncation='only_second', max_length=384, return_offsets_mapping=True, return_tensors='pt')
19
+ offsets = enc.pop('offset_mapping')[0].tolist()
20
+ 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, -1000000000.0)
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:
 
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
  import math
43
  conf = 1.0 / (1.0 + math.exp(-(best_s - null) / 2.0))
44
+ return {'answer': span, 'score': conf}
45
 
46
  def get():
47
  global _QA, _OFF
 
49
  return None
50
  if _QA is None:
51
  try:
52
+ os.environ.setdefault('TOKENIZERS_PARALLELISM', 'false')
53
  _QA = _SpanModel(MODEL)
54
  except Exception:
55
+ _OFF = True
56
+ return None
57
  return _QA
58
+ _DATE = re.compile('\\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)
59
+ _NUM = re.compile('\\d[\\d,.]*')
60
+ _NAME = re.compile("^[A-Z][\\w'’.-]*(?:\\s+(?:of|the|de|da|di|von|van|and|&)\\s+)?(?:\\s*[A-Z][\\w'’.-]*){0,5}$")
 
61
 
62
  def type_ok(span: str, answer_type: str | None) -> bool:
63
  s = span.strip()
64
  if not s or len(s) > 80:
65
  return False
66
+ if answer_type == 'date':
67
  return bool(_DATE.search(s))
68
+ if answer_type == 'number':
69
  return bool(_NUM.search(s))
70
+ if answer_type in ('person', 'place', 'organization'):
71
  return bool(_NAME.match(s)) or (s[:1].isupper() and len(s.split()) <= 6)
72
  return True
73
 
74
  def normalize(s: str) -> str:
75
+ return re.sub('[^a-z0-9 ]', '', s.lower()).strip()
76
 
77
+ def extract(question: str, candidates: list[tuple[str, str]], answer_type: str | None=None, min_score: float=0.15) -> dict | None:
 
 
 
78
  qa = get()
79
  if qa is None or not candidates:
80
  return None
81
+ best, votes = (None, {})
82
  for ctx, tag in candidates[:4]:
83
  try:
84
  r = qa(question, ctx[:2000])
85
  except Exception:
86
  continue
87
+ span = (r.get('answer') or '').strip(' .,;:"\'“”')
88
+ score = float(r.get('score') or 0.0)
89
+ if not span or score < min_score or (not type_ok(span, answer_type)):
90
  continue
91
  key = normalize(span)
92
  votes[key] = votes.get(key, 0) + 1
93
+ if best is None or score > best['score']:
94
+ best = {'answer': span, 'score': round(score, 3), 'tag': tag}
95
  if best is None:
96
  return None
97
+ best['votes'] = votes.get(normalize(best['answer']), 1)
98
  return best
code/tinyqa/pipeline.py ADDED
@@ -0,0 +1,691 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections, json, os, random, re, string, sys, time
2
+ from concurrent.futures import ThreadPoolExecutor
3
+ HERE = os.path.dirname(os.path.abspath(__file__))
4
+ BK = os.environ.get('MOSS_HOME', os.path.dirname(os.path.dirname(HERE)))
5
+ DATA = os.environ.get('MOSS_DATA', os.path.join(BK, 'data'))
6
+ os.makedirs(DATA, exist_ok=True)
7
+ CACHE = os.environ.get('MOSS_WEBQA_CACHE', os.path.join(DATA, 'webqa_cache.json'))
8
+
9
+ def normalize(s):
10
+ s = s.lower()
11
+ s = ''.join((ch for ch in s if ch not in set(string.punctuation)))
12
+ s = re.sub('\\b(a|an|the)\\b', ' ', s)
13
+ return ' '.join(s.split())
14
+
15
+ def contains(text, answers):
16
+ t = normalize(text)
17
+ return any((normalize(a) and normalize(a) in t for a in answers))
18
+ CACHE_DDGS = os.path.join(DATA, 'webqa_cache.json')
19
+ CACHE_SERPER = os.path.join(DATA, 'webqa_cache_serper.json')
20
+ _caches = {'ddgs': json.load(open(CACHE_DDGS)) if os.path.exists(CACHE_DDGS) else {}, 'serper': json.load(open(CACHE_SERPER)) if os.path.exists(CACHE_SERPER) else {}}
21
+
22
+ def default_provider():
23
+ return os.environ.get('MOSS_SEARCH') or 'ddgs'
24
+
25
+ def _merge_save(path, mem):
26
+ import fcntl
27
+ with open(path, 'a+') as f:
28
+ fcntl.flock(f, fcntl.LOCK_EX)
29
+ f.seek(0)
30
+ try:
31
+ disk = json.load(f)
32
+ except Exception:
33
+ disk = {}
34
+ disk.update(mem)
35
+ mem.update(disk)
36
+ f.seek(0)
37
+ f.truncate()
38
+ json.dump(disk, f)
39
+ fcntl.flock(f, fcntl.LOCK_UN)
40
+
41
+ def save_caches():
42
+ _merge_save(CACHE_DDGS, _caches['ddgs'])
43
+ _merge_save(CACHE_SERPER, _caches['serper'])
44
+ if 'searxng' in _caches:
45
+ _merge_save(os.path.join(DATA, 'webqa_cache_searxng.json'), _caches['searxng'])
46
+ _caches['searxng'] = json.load(open(os.path.join(DATA, 'webqa_cache_searxng.json'))) if os.path.exists(os.path.join(DATA, 'webqa_cache_searxng.json')) else {}
47
+ _cache = _caches[default_provider()]
48
+ SERPER_LEDGER = os.path.join(DATA, 'serper_calls.json')
49
+ import threading
50
+ _LEDGER_LOCK = threading.Lock()
51
+
52
+ def _count_serper():
53
+ import fcntl
54
+ with _LEDGER_LOCK, open(SERPER_LEDGER, 'a+') as f:
55
+ fcntl.flock(f, fcntl.LOCK_EX)
56
+ f.seek(0)
57
+ try:
58
+ d = json.load(f)
59
+ except Exception:
60
+ d = {'calls': 0}
61
+ d['calls'] = d.get('calls', 0) + 1
62
+ d['last'] = time.strftime('%Y-%m-%d %H:%M')
63
+ f.seek(0)
64
+ f.truncate()
65
+ json.dump(d, f)
66
+ fcntl.flock(f, fcntl.LOCK_UN)
67
+
68
+ def search_serper(q, k=10):
69
+ import urllib.request
70
+ for attempt in range(3):
71
+ try:
72
+ return _search_serper_once(q, k)
73
+ except Exception as ex:
74
+ if '429' not in str(ex) or attempt == 2:
75
+ raise
76
+ time.sleep(3 + 4 * attempt)
77
+
78
+ def _search_serper_once(q, k=10):
79
+ import urllib.request
80
+ _count_serper()
81
+ req = urllib.request.Request('https://google.serper.dev/search', data=json.dumps({'q': q, 'num': k}).encode(), headers={'X-API-KEY': os.environ['SERPER_API_KEY'], 'Content-Type': 'application/json'})
82
+ with urllib.request.urlopen(req, timeout=20) as r:
83
+ d = json.load(r)
84
+ out = []
85
+ ab = d.get('answerBox') or {}
86
+ if ab.get('answer') or ab.get('snippet'):
87
+ 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', '')})
88
+ kg = d.get('knowledgeGraph') or {}
89
+ if kg.get('description'):
90
+ 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', '')})
91
+ for x in d.get('organic', [])[:k]:
92
+ out.append({'title': x.get('title', ''), 'body': x.get('snippet', ''), 'href': x.get('link', '')})
93
+ return out
94
+
95
+ def search_searxng(q, k=10):
96
+ import urllib.request, urllib.parse
97
+ url = os.environ['SEARXNG_URL'].rstrip('/') + '/search?' + urllib.parse.urlencode({'q': q, 'format': 'json', 'language': 'en', 'safesearch': 0})
98
+ with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'moss/0.1'}), timeout=25) as r:
99
+ d = json.load(r)
100
+ out = []
101
+ for a in d.get('answers', [])[:2]:
102
+ out.append({'title': 'Answer', 'body': a if isinstance(a, str) else str(a.get('answer', a)), 'href': ''})
103
+ for x in d.get('results', [])[:k]:
104
+ out.append({'title': x.get('title', ''), 'body': x.get('content', ''), 'href': x.get('url', '')})
105
+ return out
106
+ LOCAL_DB = os.environ.get('MOSS_CORPUS_DB', os.path.join(DATA, 'corpus.sqlite'))
107
+
108
+ def _passages(text, size=420):
109
+ for para in re.split('\\n\\s*\\n', text):
110
+ para = ' '.join(para.split())
111
+ if not para or para.startswith('#'):
112
+ continue
113
+ cur = ''
114
+ for sent in _SENT.split(para):
115
+ if cur and len(cur) + len(sent) > size:
116
+ yield cur
117
+ cur = ''
118
+ cur = (cur + ' ' + sent).strip()
119
+ if cur:
120
+ yield cur
121
+
122
+ def index_corpus(src, db=LOCAL_DB):
123
+ import sqlite3
124
+ os.makedirs(os.path.dirname(os.path.abspath(db)), exist_ok=True)
125
+ if os.path.exists(db):
126
+ os.remove(db)
127
+ con = sqlite3.connect(db)
128
+ con.execute("CREATE VIRTUAL TABLE p USING fts5(title, body, href UNINDEXED, tokenize='porter unicode61')")
129
+
130
+ def docs():
131
+ if os.path.isfile(src) and src.endswith('.jsonl'):
132
+ for i, line in enumerate(open(src, encoding='utf-8', errors='ignore')):
133
+ d = json.loads(line)
134
+ yield (d.get('title') or f'document {i + 1}', d.get('text', ''), d.get('url') or f'{os.path.basename(src)}#{i + 1}')
135
+ return
136
+ for root, _, files in os.walk(src):
137
+ for fn in sorted(files):
138
+ if not fn.lower().endswith(('.txt', '.md', '.markdown')):
139
+ continue
140
+ path = os.path.join(root, fn)
141
+ text = open(path, encoding='utf-8', errors='ignore').read()
142
+ m = re.search('^#\\s+(.+)$', text, re.M)
143
+ title = m.group(1).strip() if m else os.path.splitext(fn)[0].replace('_', ' ').replace('-', ' ')
144
+ yield (title, text, 'file://' + os.path.abspath(path))
145
+ n = 0
146
+ for title, text, href in docs():
147
+ rows = [(title, ps, href) for ps in _passages(text)]
148
+ con.executemany('INSERT INTO p VALUES (?, ?, ?)', rows)
149
+ n += len(rows)
150
+ con.commit()
151
+ con.close()
152
+ return n
153
+
154
+ def search_local(q, k=10, db=LOCAL_DB):
155
+ import sqlite3
156
+ if not os.path.exists(db):
157
+ return []
158
+ terms = [t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QSTOP and len(t) > 1]
159
+ if not terms:
160
+ return []
161
+ con = sqlite3.connect(db)
162
+ try:
163
+ 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()
164
+ finally:
165
+ con.close()
166
+ return [{'title': t, 'body': b, 'href': h} for t, b, h in rows]
167
+
168
+ def search(q, k=10, provider=None):
169
+ provider = provider or default_provider()
170
+ if provider == 'local':
171
+ return search_local(q, k)
172
+ if provider == 'serper' and (not os.environ.get('SERPER_API_KEY')):
173
+ provider = 'ddgs'
174
+ if provider == 'searxng' and (not os.environ.get('SEARXNG_URL')):
175
+ provider = 'ddgs'
176
+ c = _caches[provider]
177
+ if provider == 'searxng':
178
+ if q in c:
179
+ return c[q]
180
+ try:
181
+ r = search_searxng(q, k)
182
+ res = [{'title': clean_title(x['title']), 'body': clean_body(x['body']), 'href': x['href']} for x in r]
183
+ if res:
184
+ c[q] = res
185
+ return res
186
+ except Exception as ex:
187
+ print(f'[webqa] searxng failed ({type(ex).__name__}); falling back to DuckDuckGo', flush=True)
188
+ c = _caches['ddgs']
189
+ if q in c:
190
+ return c[q]
191
+ if q in c:
192
+ return c[q]
193
+ if provider == 'serper':
194
+ try:
195
+ r = search_serper(q, k)
196
+ res = [{'title': clean_title(x['title']), 'body': clean_body(x['body']), 'href': x['href']} for x in r]
197
+ if res:
198
+ c[q] = res
199
+ return res
200
+ except Exception as ex:
201
+ print(f'[webqa] serper failed ({type(ex).__name__}); falling back to DuckDuckGo', flush=True)
202
+ c = _caches['ddgs']
203
+ if q in c:
204
+ return c[q]
205
+ from ddgs import DDGS
206
+ r = []
207
+ for attempt, backend in enumerate(('auto', 'google', 'bing', 'auto')):
208
+ try:
209
+ r = DDGS().text(q, max_results=k, backend=backend) or []
210
+ if r:
211
+ break
212
+ except Exception as ex:
213
+ r = []
214
+ time.sleep(1.5 + 2 * attempt)
215
+ res = [{'title': clean_title(x.get('title', '')), 'body': clean_body(x.get('body', '')), 'href': x.get('href', '')} for x in r]
216
+ if res:
217
+ c[q] = res
218
+ return res
219
+ _SENT = re.compile('(?<=[.!?])\\s+(?=[A-Z0-9\\"\'(])')
220
+ _DATE = re.compile('^(?:[A-Z][a-z]{2} \\d{1,2}, \\d{4}|\\d{1,2} [A-Z][a-z]{2} \\d{4})\\s*[·•-]\\s*')
221
+
222
+ def clean_title(t):
223
+ t = re.sub('([a-z]{4,})([A-Z][a-z]{2,})', '\\1 | \\2', t.strip())
224
+ t = re.split('\\s+\\|\\s+', t.strip())[0]
225
+ return t[:110].rstrip()
226
+
227
+ def clean_body(b):
228
+ return _DATE.sub('', b.strip())
229
+ STRICT = os.environ.get('MOSS_STRICT') == '1'
230
+ BLOCK = [d for d in os.environ.get('MOSS_BLOCK_DOMAINS', 'huggingface.co,kaggle.com,github.com,paperswithcode.com,simple-evals,simpleqa,freshqa,popqa').split(',') if d]
231
+ PAGES = int(os.environ.get('MOSS_PAGES', '0'))
232
+ PAGE_DIR = os.path.join(DATA, 'pages')
233
+ os.makedirs(PAGE_DIR, exist_ok=True)
234
+ _UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
235
+
236
+ def fetch_text(url, timeout=12):
237
+ import hashlib, urllib.request, socket
238
+ socket.setdefaulttimeout(timeout)
239
+ p = os.path.join(PAGE_DIR, hashlib.sha1(url.encode()).hexdigest() + '.txt')
240
+ if os.path.exists(p):
241
+ return open(p).read()
242
+ txt = ''
243
+ try:
244
+ import trafilatura
245
+ req = urllib.request.Request(url, headers={'User-Agent': _UA, 'Accept-Language': 'en'})
246
+ html = urllib.request.urlopen(req, timeout=timeout).read(2000000).decode('utf-8', 'ignore')
247
+ txt = trafilatura.extract(html, include_comments=False, include_tables=True) or ''
248
+ except Exception:
249
+ txt = ''
250
+ open(p, 'w').write(txt)
251
+ return txt
252
+
253
+ def page_candidates(q, results, n_pages, cap=150):
254
+ qt = {t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QWORDS and len(t) > 2}
255
+ out = []
256
+ for r in results[:n_pages]:
257
+ if not r.get('href') or any((b in r['href'].lower() for b in BLOCK)):
258
+ continue
259
+ txt = fetch_text(r['href'])
260
+ for s in _SENT.split(' '.join(txt.split())):
261
+ s = s.strip()
262
+ if 25 <= len(s) <= 400 and len(qt & set(re.findall('[a-z0-9]+', s.lower()))) >= max(1, min(2, len(qt) // 3)):
263
+ out.append({'sent': s, 'title': r['title'], 'url': r['href'], 'body': s, 'from_page': True})
264
+ if len(out) > cap:
265
+ out.sort(key=lambda c: -len(qt & set(re.findall('[a-z0-9]+', c['sent'].lower()))))
266
+ out = out[:cap]
267
+ return out
268
+ PROSE = os.environ.get('MOSS_PROSE', '1') == '1'
269
+ SOURCE_PENALTY = os.environ.get('MOSS_SOURCE_PENALTY', '0') == '1'
270
+ QUOTABLE = os.environ.get('MOSS_QUOTABLE', '0') == '1'
271
+ SOCIAL = ('reddit.com', 'quora.com', 'facebook.com', 'instagram.com', 'tiktok.com', 'pinterest.', 'youtube.com', 'answers.com', 'brainly.', 'quizlet', 'x.com/', 'twitter.com')
272
+ _ROW = re.compile('^\\s*\\d+[.,)]\\s')
273
+
274
+ def is_prose(s):
275
+ if len(re.findall('[A-Za-z]{3,}', s)) < 4 or _ROW.match(s) or '|' in s or (s.count('·') >= 2):
276
+ return False
277
+ if ';' in s and len(s.split()) < 10:
278
+ return False
279
+ words = s.split()
280
+ if s.count(' – ') + s.count(' — ') >= 4:
281
+ return False
282
+ if len(words) > 45 and (s.count(' – ') + s.count(' — ') >= 2 or sum((w[:1].isupper() for w in words)) / len(words) > 0.5):
283
+ return False
284
+ return sum((1 for ch in s if ch.isdigit() or ch in ',;·|')) / max(1, len(s)) <= 0.25
285
+ CUTS = os.environ.get('MOSS_CUTS', '1') == '1'
286
+ _GLUE = re.compile('(?<=[a-z0-9][.!?])(?=[A-Z][a-z])|\\s*(?:\\.\\.\\.|…)\\s*')
287
+
288
+ def cuts(s):
289
+ parts = [p.strip(' ,;:') for p in _GLUE.split(s)]
290
+ parts = [p for p in parts if len(p) > 15]
291
+ return parts if len(parts) > 1 else []
292
+ _BOILER = re.compile('^(?: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*)?')
293
+
294
+ def candidates(results, q=None):
295
+ out = []
296
+ if PAGES and q:
297
+ out += page_candidates(q, results, PAGES)
298
+ for r in results:
299
+ if any((b in (r.get('href', '') + ' ' + r.get('title', '')).lower() for b in BLOCK)):
300
+ continue
301
+ for s in _SENT.split(re.sub('\\s*\\[\\d{1,3}\\]', '', r['body']).strip()):
302
+ s = _BOILER.sub('', s.strip()).strip()
303
+ for t in [s] + (cuts(s) if CUTS else []):
304
+ if len(t) > 15 and (not PROSE or is_prose(t)):
305
+ out.append({'sent': t, 'title': clean_title(r['title']), 'url': r['href'], 'body': r['body']})
306
+ return out
307
+
308
+ def _cap(t):
309
+ return t[:1].upper() + t[1:]
310
+ _PAST = {'end': 'ended', 'begin': 'began', 'start': 'started', 'happen': 'happened', 'die': 'died', 'occur': 'occurred', 'open': 'opened', 'close': 'closed', 'finish': 'finished', 'take place': 'took place'}
311
+
312
+ def lead(q, span):
313
+ s = re.sub('\\s+', ' ', q.strip().rstrip('?').strip())
314
+ b = f'**{span}**'
315
+ prep = '' if re.match('^(?:between|from|in|on|at|during|around|about|circa|since|after|before)\\b', span, re.I) else 'in '
316
+ m = re.match('^who (was|is|were|are) (.+)$', s, re.I)
317
+ if m:
318
+ return f'{_cap(m.group(2))} {m.group(1).lower()} {b}.'
319
+ m = re.match('^who (founded|created|invented|wrote|directed|discovered|built|designed|painted|composed|developed|produced|started|established|won|scored) (.+)$', s, re.I)
320
+ if m:
321
+ return f'{_cap(m.group(2))} was {m.group(1).lower()} by {b}.'
322
+ m = re.match('^(what|which) (is|was|are|were) (.+)$', s, re.I)
323
+ if m:
324
+ return f'{_cap(m.group(3))} {m.group(2).lower()} {b}.'
325
+ m = re.match('^where (is|was|are|were) (.+?)(?: located| based| situated)?$', s, re.I)
326
+ if m:
327
+ return f'{_cap(m.group(2))} {m.group(1).lower()} {prep}{b}.'
328
+ m = re.match('^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)
329
+ if m:
330
+ return f'{_cap(m.group(2))} {m.group(1).lower()} {m.group(3).lower()} {prep}{b}.'
331
+ m = re.match('^when did (.+?) (end|begin|start|happen|die|occur|open|close|take place|finish)$', s, re.I)
332
+ if m:
333
+ return f'{_cap(m.group(1))} {_PAST[m.group(2).lower()]} {prep}{b}.'
334
+ return None
335
+ 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'}
336
+ VERBALIZE = os.environ.get('MOSS_VERBALIZE', 'template')
337
+ DECODER_URL = os.environ.get('MOSS_DECODER', 'http://127.0.0.1:8089')
338
+ PLANNER_URL = os.environ.get('MOSS_PLANNER', 'http://127.0.0.1:8093')
339
+ VERBALISER_URL = os.environ.get('MOSS_VERBALISER', '')
340
+ VERB_TAU = float(os.environ.get('MOSS_VERB_TAU', '0.0'))
341
+ VERB_SPAN = os.environ.get('MOSS_VERB_SPAN', '0') == '1'
342
+ _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'}
343
+
344
+ def _wordsl(t):
345
+ return re.findall('[a-z0-9]+', t.lower())
346
+
347
+ def _post_json(url, body, timeout=20):
348
+ import urllib.request
349
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={'Content-Type': 'application/json'})
350
+ with urllib.request.urlopen(req, timeout=timeout) as r:
351
+ return json.loads(r.read())
352
+
353
+ def _tidy_lead(t):
354
+ t = re.sub('\\s+', ' ', t).strip().rstrip('.').strip()
355
+ return t[:1].upper() + t[1:] + '.' if t else t
356
+
357
+ def own_lead(q, span, cited, title, natural=True, vscore=None, info=None, q_user=None):
358
+ import collections
359
+ qc = collections.Counter(_wordsl(q))
360
+ sw = set(_wordsl(span))
361
+ ew = set(_wordsl(cited)) | set(_wordsl(title)) if natural else set()
362
+ for w, n in collections.Counter(_wordsl(q_user or '')).items():
363
+ qc[w] = max(qc[w], n)
364
+
365
+ def content_free(text):
366
+ cc = collections.Counter((w for w in _wordsl(text) if w not in _FUNC and w not in sw))
367
+ return all((w in qc and cc[w] <= qc[w] or w in ew for w in cc))
368
+ if VERBALISER_URL and natural:
369
+ try:
370
+ vp = f'<|evidence|>\n[E1] ({title}) {cited}\n<|question|> {q.strip()}\n' + (f'<|span|> {span.strip()}\n' if VERB_SPAN else '') + '<|answer|>'
371
+ d = _post_json(f'{VERBALISER_URL}/completion', {'prompt': vp, 'n_predict': 64, 'temperature': 0.0, 'stop': ['<|end|>'], 'cache_prompt': False}, timeout=10)
372
+ t = re.sub('\\s+', ' ', d.get('content', '').split('<|end|>')[0]).strip()
373
+ v = None
374
+ ok = t and t != '<abstain>' and (3 <= len(t.split()) <= 45) and (normalize(span) in normalize(t)) and content_free(t)
375
+ if ok and vscore is not None:
376
+ v = float(vscore(t))
377
+ ok = v >= VERB_TAU
378
+ if info is not None:
379
+ info.update({'verbaliser': t or None, 'verbaliser_v': None if v is None else round(v, 2)})
380
+ if ok:
381
+ i = t.lower().find(span.lower())
382
+ t = t[:i] + f'**{t[i:i + len(span)]}**' + t[i + len(span):] if i >= 0 else t
383
+ return (_tidy_lead(t), 'verbaliser')
384
+ except Exception:
385
+ pass
386
+ try:
387
+ g = gbnf(1, allowed=[1]).replace('root ::= "<abstain>" | answer', 'root ::= answer')
388
+ 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)
389
+ parts, abst = parse_answer(d.get('content', ''))
390
+ if not abst and sum((1 for k, _ in parts if k == 'ref')) == 1:
391
+ glue = ' '.join((v for k, v in parts if k == 'glue'))
392
+ inserted = normalize(span) not in normalize(glue)
393
+ if not inserted:
394
+ t = ''.join(('' if k == 'ref' else v for k, v in parts))
395
+ i = t.find(span)
396
+ t = t[:i] + f'**{span}**' + t[i + len(span):] if i >= 0 else t
397
+ else:
398
+ t = ''.join((f'**{span}**' if k == 'ref' else v for k, v in parts))
399
+ dup = bool((set(_wordsl(glue)) & sw) - (set(qc) if natural else set())) and (inserted or not natural)
400
+ if content_free(glue) and (not dup) and (3 <= len(t.split()) <= 30):
401
+ return (_tidy_lead(t), 'decoder')
402
+ except Exception:
403
+ pass
404
+ try:
405
+ 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)
406
+ m = re.search('"hypothetical"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"', d.get('content', ''))
407
+ hyp = json.loads('"' + m.group(1) + '"') if m else ''
408
+ if hyp.count('____') == 1 and content_free(hyp.replace('____', ' ')) and (3 <= len(hyp.split()) <= 30):
409
+ return (_tidy_lead(hyp.replace('____', f'**{span}**')), 'planner')
410
+ except Exception:
411
+ pass
412
+ return (None, None)
413
+
414
+ def quote_clean(q, sent, span):
415
+ if not sent or len(sent) > 230 or sent.rstrip()[-1:] not in '.!?' or ('...' in sent) or ('…' in sent):
416
+ return False
417
+ if span and normalize(span) not in normalize(sent):
418
+ return False
419
+ cw = [w for w in re.findall('[a-z0-9]+', q.lower()) if w not in QSTOP and len(w) > 2]
420
+ ns = normalize(sent)
421
+ return sum((1 for w in cw if w in ns)) >= max(1, len(cw) // 2)
422
+ FALLBACK = os.environ.get('MOSS_FALLBACK', '0') == '1'
423
+ RETRY_TAU = float(os.environ.get('MOSS_RETRY_TAU', '5.5'))
424
+ PLANNER_RETRY = os.environ.get('MOSS_PLANNER_RETRY', '0') == '1'
425
+ RETRY_PROVIDER = os.environ.get('MOSS_RETRY_PROVIDER', 'serper')
426
+ AGREE = int(os.environ.get('MOSS_AGREE', '3'))
427
+ SIEVE_RETRY = os.environ.get('MOSS_SIEVE_RETRY', '0') == '1'
428
+ _NAMES = re.compile("\\b[A-Z][\\w'’.-]+(?:\\s+(?:(?:de|da|van|von|of|the|du|del|di|la|le|&)\\s+)?[A-Z][\\w'’.-]+){0,3}")
429
+ _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'}
430
+ _FORUMS = '-site:reddit.com -site:quora.com -site:facebook.com -site:pinterest.com -site:youtube.com -site:answers.com'
431
+
432
+ def retry_queries(q):
433
+ out = [('noforum', f"{q.rstrip('?')} {_FORUMS}")]
434
+ ns = [m.strip() for m in _NAMES.findall(q) if m.split()[0] not in _QCAP and len(m) > 2]
435
+ if ns:
436
+ rest = q
437
+ for n in ns:
438
+ rest = rest.replace(n, '')
439
+ rest = re.sub('^\\s*(who|what|which|when|where|how)\\s+(was|is|were|are|did|does|do)\\s+', '', rest.strip().rstrip('?'), flags=re.I)
440
+ out.append(('names', ' '.join((f'"{n}"' for n in ns)) + ' ' + re.sub('\\s+', ' ', rest).strip()))
441
+ l = lead(q, '')
442
+ if l:
443
+ l = l.replace(' ****.', '').replace('****.', '').strip().rstrip('.')
444
+ if 3 <= len(l.split()) <= 12:
445
+ out.append(('stub', f'"{l}"'))
446
+ if PLANNER_RETRY:
447
+ try:
448
+ 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)
449
+ txt = d.get('content', '')
450
+ m = re.search('"hypothetical"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"', txt)
451
+ hyp = json.loads('"' + m.group(1) + '"') if m else ''
452
+ terms = re.findall('"([^"]{2,40})"', txt.split('"search_terms"')[1].split(']')[0]) if '"search_terms"' in txt else []
453
+ ents = re.findall('"([^"]{2,40})"', txt.split('"entities"')[1].split(']')[0]) if '"entities"' in txt else []
454
+ tq = ' '.join(dict.fromkeys(ents + terms))
455
+ if len(tq.split()) >= 2:
456
+ out.append(('plan_terms', tq[:160]))
457
+ h = re.sub('\\s+', ' ', hyp.replace('____', ' ')).strip(' .')
458
+ import collections as _c
459
+ qc = _c.Counter(_wordsl(q))
460
+ hc = _c.Counter((w for w in _wordsl(h) if w not in _FUNC))
461
+ 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)):
462
+ out.append(('plan_stub', f'"{h}"'))
463
+ except Exception:
464
+ pass
465
+ return out
466
+ SPELL = os.environ.get('MOSS_SPELL', '1') == '1'
467
+ TAU_V = float(os.environ.get('MOSS_TAU_V', '3.0'))
468
+
469
+ def _lev(a, b):
470
+ if abs(len(a) - len(b)) > 3:
471
+ return 9
472
+ d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
473
+ for i in range(len(a) + 1):
474
+ d[i][0] = i
475
+ for j in range(len(b) + 1):
476
+ d[0][j] = j
477
+ for i in range(1, len(a) + 1):
478
+ for j in range(1, len(b) + 1):
479
+ c = a[i - 1] != b[j - 1]
480
+ d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c)
481
+ if i > 1 and j > 1 and (a[i - 1] == b[j - 2]) and (a[i - 2] == b[j - 1]):
482
+ d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
483
+ return d[-1][-1]
484
+
485
+ def corpus_spelling(q, results):
486
+ import collections
487
+ vocab = collections.Counter()
488
+ for r in results:
489
+ for w in set(re.findall('[a-z]{4,}', (r.get('title', '') + ' ' + r.get('body', '')).lower())):
490
+ vocab[w] += 1
491
+ fixes = {}
492
+ for w in re.findall('\\b[a-z]{5,}\\b', q):
493
+ if w in vocab or w in QSTOP or w in _FUNC:
494
+ continue
495
+ 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)
496
+ if best and 0 < best[0] <= (3 if len(w) >= 8 else 2):
497
+ fixes[w] = best[2]
498
+ out = q
499
+ for w, v in fixes.items():
500
+ out = re.sub('\\b' + re.escape(w) + '\\b', v, out)
501
+ return (out, fixes)
502
+ QWORDS = 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 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())
503
+ MAX_EVIDENCE = 16
504
+ REF_TOKENS = [f'<q E{i}>' for i in range(1, MAX_EVIDENCE + 1)]
505
+ ABSTAIN = '<abstain>'
506
+ BOS_EVIDENCE, BOS_QUESTION, BOS_ANSWER, EOS_ANSWER = ('<|evidence|>', '<|question|>', '<|answer|>', '<|end|>')
507
+
508
+ def gbnf(n_evidence: int, max_glue_tokens: int=40, allowed: list[int] | None=None) -> str:
509
+ ids = allowed or list(range(1, n_evidence + 1))
510
+ refs = ' | '.join((f'"<q E{i}>"' for i in ids))
511
+ return f'root ::= "{ABSTAIN}" | answer\nanswer ::= segment+ glue?\nsegment ::= glue? ref\nref ::= {refs}\nglue ::= [^<]{{1,{max_glue_tokens * 5}}}\n'
512
+ REF_RE = re.compile('<q E(\\d+)>')
513
+
514
+ def parse_answer(text: str) -> tuple[list[tuple[str, str]], bool]:
515
+ text = text.split(EOS_ANSWER)[0].strip()
516
+ if text.startswith(ABSTAIN):
517
+ return ([], True)
518
+ parts: list[tuple[str, str]] = []
519
+ pos = 0
520
+ for m in REF_RE.finditer(text):
521
+ glue = text[pos:m.start()]
522
+ if glue.strip():
523
+ parts.append(('glue', glue))
524
+ parts.append(('ref', f'E{m.group(1)}'))
525
+ pos = m.end()
526
+ tail = text[pos:]
527
+ if tail.strip():
528
+ parts.append(('glue', tail))
529
+ return (parts, False)
530
+
531
+ class Stack:
532
+
533
+ def __init__(self):
534
+ from sentence_transformers import CrossEncoder
535
+ dev = os.environ.get('MOSS_DEVICE', 'cpu')
536
+ self.rank = CrossEncoder(os.environ.get('MOSS_RANKER') or os.path.join(BK, 'models', 'ranker'), max_length=256, device=dev)
537
+ self.verify = CrossEncoder(os.environ.get('MOSS_VERIFIER') or os.path.join(BK, 'models', 'verifier'), max_length=256, device=dev)
538
+ from .extract import extract as _extract
539
+ self.extract = _extract
540
+ self.hhem = None
541
+ if os.environ.get('MOSS_HHEM') == '1':
542
+ try:
543
+ from transformers import AutoModelForSequenceClassification
544
+ self.hhem = AutoModelForSequenceClassification.from_pretrained('vectara/hallucination_evaluation_model', trust_remote_code=True)
545
+ except Exception as ex:
546
+ print(f'[webqa] HHEM unavailable: {type(ex).__name__}: {str(ex)[:120]}', flush=True)
547
+
548
+ def _sieve(self):
549
+ if not hasattr(self, '_sv'):
550
+ from .sieve import Sieve
551
+ sv = Sieve.__new__(Sieve)
552
+ sv.verify = self.verify
553
+ self._sv = sv
554
+ return self._sv
555
+
556
+ def answer_iter(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None):
557
+ if tau_v is None:
558
+ tau_v = TAU_V
559
+ t0 = time.time()
560
+ res = search(q, provider=provider)
561
+ t1 = time.time()
562
+ q_user = q
563
+ fixes = {}
564
+ if SPELL and res:
565
+ q, fixes = corpus_spelling(q, res)
566
+ 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}
567
+ cands = candidates(res, q)
568
+ if not cands:
569
+ yield {'stage': 'done', 'tier': 3, 'why': 'no results', 'ms_search': round(1000 * (t1 - t0)), 'ms_models': 0, 'results': res}
570
+ return
571
+ ta = time.time()
572
+ s1 = self.rank.predict([(q, f"{c['title']}. {c['sent']}") for c in cands], batch_size=32, show_progress_bar=False)
573
+ order = sorted(range(len(cands)), key=lambda i: -float(s1[i]))[:8]
574
+ tb = time.time()
575
+ yield {'stage': 'rank', 'ms': round(1000 * (tb - ta)), 'n': len(cands), 'top': [cands[i]['sent'][:90] for i in order[:3]]}
576
+ s2 = self.verify.predict([(q, f"{cands[i]['title']}. {cands[i]['sent']}") for i in order], batch_size=32, show_progress_bar=False)
577
+ 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
578
+
579
+ def quotable(c):
580
+ if not QUOTABLE:
581
+ return 0.0
582
+ t = c['sent']
583
+ 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)
584
+ ver = [j for j in range(len(order)) if float(s2[j]) >= tau_v]
585
+ 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]))
586
+ c = cands[order[best]]
587
+ score2 = float(s2[best])
588
+ tc = time.time()
589
+ tier = 1 if score2 >= tau_v else 2 if score2 >= tau_lo else 3
590
+ yield {'stage': 'verify', 'ms': round(1000 * (tc - tb)), 'score': round(score2, 2), 'tier': tier}
591
+ retry = None
592
+ if FALLBACK and tier != 1:
593
+ rprov = RETRY_PROVIDER if RETRY_PROVIDER == 'serper' and os.environ.get('SERPER_API_KEY') else provider
594
+ for name, rq in retry_queries(q):
595
+ tr = time.time()
596
+ more = [x for x in candidates(search(rq, provider=rprov), q) if x['sent'] not in {cc['sent'] for cc in cands}]
597
+ if not more:
598
+ continue
599
+ r1 = self.rank.predict([(q, f"{x['title']}. {x['sent']}") for x in more], batch_size=32, show_progress_bar=False)
600
+ ro = sorted(range(len(more)), key=lambda i: -float(r1[i]))[:8]
601
+ r2 = self.verify.predict([(q, f"{more[i]['title']}. {more[i]['sent']}") for i in ro], batch_size=32, show_progress_bar=False)
602
+ rb = max(range(len(ro)), key=lambda j: float(r2[j]) - pen(more[ro[j]]) + quotable(more[ro[j]]))
603
+ rv = float(r2[rb])
604
+ yield {'stage': 'retry', 'ms': round(1000 * (time.time() - tr)), 'query': rq, 'name': name, 'score': round(rv, 2), 'n': len(more), 'taken': rv >= RETRY_TAU}
605
+ if rv >= RETRY_TAU:
606
+ c = more[ro[rb]]
607
+ score2 = rv
608
+ tier = 1
609
+ retry = name
610
+ res = res + search(rq, provider=rprov)
611
+ break
612
+ tc = time.time()
613
+ span = self.extract(q, [(f"{c['title'].split(' | ')[0].strip()}. {c['body']}", 'E1')], answer_type=None)
614
+ if span:
615
+ span['answer'] = re.sub('\\b(\\w+)\\1\\b', '\\1', span['answer']).strip()
616
+ span['answer'] = re.sub('\\b(\\w+(?:\\s\\w+)?)\\s+\\1\\b', '\\1', span['answer']).strip()
617
+ if not span and re.match('^(?:who|which)\\b', q.strip(), re.I):
618
+ head = re.split('\\s+[-|—–:]\\s+', c['title'])[0].strip()
619
+ if 2 <= len(head.split()) <= 5 and head[:1].isupper():
620
+ span = {'answer': head, 'score': 0.0, 'kind': 'title'}
621
+ spans = {}
622
+ for j, i in enumerate(order if os.environ.get('MOSS_CONSENSUS') == '1' else []):
623
+ cj = cands[i]
624
+ sp = self.extract(q, [(f"{cj['title'].split(' | ')[0].strip()}. {cj['body']}", 'E1')], answer_type=None)
625
+ if not sp:
626
+ continue
627
+ key = normalize(re.sub('\\b(\\w+)\\1\\b', '\\1', sp['answer']))
628
+ if not key or len(key) > 80:
629
+ continue
630
+ e = spans.setdefault(key, {'answer': sp['answer'], 'sources': set(), 'best_v': -99.0, 'cand': None})
631
+ e['best_v'] = max(e['best_v'], float(s2[j]))
632
+ e['cand'] = e['cand'] or cj
633
+ for key, e in spans.items():
634
+ e['sources'] = {r['href'] for r in res if key in normalize(r['title'] + ' ' + r['body'])}
635
+ cons = max(spans.values(), key=lambda e: (len(e['sources']), e['best_v'])) if spans else None
636
+ pkey = normalize(span['answer']) if span else ''
637
+ 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
638
+ if STRICT and tier == 1 and (support < 2):
639
+ tier = 2
640
+ verified_by = 'verifier' if tier == 1 else None
641
+ if AGREE and tier != 1 and span and (support >= AGREE) and (score2 >= 0.0):
642
+ tier = 1
643
+ verified_by = 'agreement'
644
+ sieve_ev = None
645
+ if SIEVE_RETRY and tier != 1 and re.match('^(?:which|who)\\b', q.strip(), re.I) and (not span or support <= 1):
646
+ try:
647
+ ts = time.time()
648
+ sv = self._sieve()
649
+ out = sv.run(q, provider=rprov if FALLBACK else provider, k_ent=8) or {}
650
+ ent = out.get('sieve')
651
+ 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))
652
+ 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)}
653
+ if ok:
654
+ span = {'answer': ent, 'score': 0.0, 'kind': 'sieve'}
655
+ pkey = normalize(ent)
656
+ if out.get('sent'):
657
+ c = {'sent': out['sent'], 'title': out.get('title') or '', 'url': out.get('url') or '', 'body': out['sent']}
658
+ score2 = float(out.get('v') or -99.0)
659
+ support = len({r.get('href') or r['body'] for r in res if pkey in normalize(r['title'] + ' ' + r['body'])}) + 1
660
+ tier = 1 if score2 >= tau_v else 2
661
+ retry = 'sieve'
662
+ verified_by = 'verifier' if tier == 1 else None
663
+ except Exception as ex:
664
+ sieve_ev = {'stage': 'sieve', 'ms': 0, 'error': type(ex).__name__}
665
+ if sieve_ev:
666
+ yield sieve_ev
667
+ td = time.time()
668
+ yield {'stage': 'extract', 'ms': round(1000 * (td - tc)), 'span': span['answer'] if span else None, 'support': support, 'consensus': cons['answer'] if cons else None, 'consensus_support': len(cons['sources']) if cons else 0}
669
+ hh = None
670
+ if self.hhem is not None and span:
671
+ try:
672
+ hh = float(self.hhem.predict([(c['body'], f"The answer to the question '{q}' is {span['answer']}.")])[0])
673
+ except Exception:
674
+ hh = None
675
+ ld, ld_by = (None, None)
676
+ vmode = verbalize or VERBALIZE
677
+ linfo = {}
678
+ if span and tier == 1 and (vmode != 'none'):
679
+ if vmode in ('own', 'own-strict'):
680
+ ttl = c['title'].split(' | ')[0].split(' - ')[0].strip()
681
+ ld, ld_by = own_lead(q, span['answer'], c['sent'], ttl, natural=vmode == 'own', info=linfo, q_user=q_user, vscore=lambda t, _q=q, _t=ttl: float(self.verify.predict([(_q, f'{_t}. {t}')], batch_size=8, show_progress_bar=False)[0]))
682
+ if not ld:
683
+ ld, ld_by = (lead(q, span['answer']), 'template' if lead(q, span['answer']) else None)
684
+ te = time.time()
685
+ yield {'stage': 'check', 'ms': round(1000 * (te - td)), 'hhem': None if hh is None else round(hh, 3), 'lead_by': ld_by, **linfo}
686
+ 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'], '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, '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, 'consensus': cons['answer'] if cons else None, 'consensus_support': len(cons['sources']) if cons else 0, '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, 'consensus_v': round(cons['best_v'], 2) if cons else None, 'ms_search': round(1000 * (t1 - t0)), 'ms_models': round(1000 * (te - t1)), 'results': res, 'spelled': fixes or None, 'q': q_user}
687
+
688
+ def answer(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None):
689
+ for ev in self.answer_iter(q, tau_v, tau_lo, provider, verbalize):
690
+ if ev['stage'] == 'done':
691
+ return {k: v for k, v in ev.items() if k != 'stage'}
code/tinyqa/server.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse, json, os, sys, threading, urllib.parse
2
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
3
+ from tinyqa import pipeline as webqa
4
+ STACK = None
5
+ LOCK = threading.Lock()
6
+ KEEP = ('tier', 'lead', 'cited', 'span', 'support', 'url', 'title', 'verified_by')
7
+
8
+ class H(BaseHTTPRequestHandler):
9
+
10
+ def log_message(self, *a):
11
+ pass
12
+
13
+ def _json(self, obj, code=200):
14
+ body = json.dumps(obj, ensure_ascii=False).encode()
15
+ self.send_response(code)
16
+ self.send_header('Content-Type', 'application/json')
17
+ self.send_header('Content-Length', str(len(body)))
18
+ self.end_headers()
19
+ self.wfile.write(body)
20
+
21
+ def do_GET(self):
22
+ u = urllib.parse.urlparse(self.path)
23
+ if u.path == '/health':
24
+ return self._json({'ok': True, 'models': STACK is not None})
25
+ if u.path != '/ask':
26
+ return self._json({'error': 'not found'}, 404)
27
+ qs = urllib.parse.parse_qs(u.query)
28
+ q = qs.get('q', [''])[0].strip()
29
+ provider = qs.get('provider', ['ddgs'])[0]
30
+ if not q:
31
+ return self._json({'tier': 3, 'why': 'empty question'})
32
+ with LOCK:
33
+ out = STACK.answer(q, provider=provider)
34
+ webqa.save_caches()
35
+ self._json({k: out.get(k) for k in KEEP})
36
+
37
+ def main():
38
+ global STACK
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument('--port', type=int, default=8091)
41
+ a = ap.parse_args()
42
+ s = webqa.Stack()
43
+ s.rank.predict([('warm up', 'warm up')], show_progress_bar=False)
44
+ s.verify.predict([('warm up', 'warm up')], show_progress_bar=False)
45
+ STACK = s
46
+ print(f'[moss] models loaded on 127.0.0.1:{a.port}', flush=True)
47
+ ThreadingHTTPServer(('127.0.0.1', a.port), H).serve_forever()
48
+ if __name__ == '__main__':
49
+ main()
code/tinyqa/sieve.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections, json, os, re, sys, time
2
+ from concurrent.futures import ThreadPoolExecutor
3
+ from . import pipeline as webqa
4
+ from .pipeline import QWORDS
5
+ _NAME = re.compile("\\b[A-Z][\\w'’.-]+(?:\\s+(?:(?:de|da|van|von|of|the|du|del|di|la|le)\\s+)?[A-Z][\\w'’.-]+){1,3}")
6
+ 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'}
7
+
8
+ def content_words(q):
9
+ return [t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QWORDS and len(t) > 2]
10
+
11
+ def entities_in(texts, exclude):
12
+ c = collections.Counter()
13
+ for t in texts:
14
+ for m in _NAME.findall(t):
15
+ m = m.strip(" .,'’")
16
+ toks = m.split()
17
+ if toks[0] in STOPCAP or len(m) > 40 or m.lower() in exclude:
18
+ continue
19
+ if any((w.lower() in exclude for w in toks)) and len(toks) <= 2:
20
+ continue
21
+ c[m] += 1
22
+ return c
23
+
24
+ def covers(text, w):
25
+ return re.search('(?<![a-z0-9])' + re.escape(w) + '(?![a-z0-9])', text.lower()) is not None
26
+
27
+ class Sieve:
28
+
29
+ def run(self, q, provider=None, k_ent=8):
30
+ t0 = time.time()
31
+ res = webqa.search(q, provider=provider)
32
+ cw = content_words(q)
33
+ qlow = {w for w in cw}
34
+ texts = [r['title'] + '. ' + r['body'] for r in res]
35
+ if webqa.PAGES:
36
+ texts += [c['sent'] for c in webqa.page_candidates(q, res, webqa.PAGES)]
37
+ 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]
38
+ if not ents:
39
+ return {'sieve': None, 'why': 'no candidate entities', 'ms': round(1000 * (time.time() - t0))}
40
+ probe = ' '.join([w for w in cw if not any((w in e.lower() for e in ents))][:6])
41
+ with ThreadPoolExecutor(8) as ex:
42
+ packs = list(ex.map(lambda e: webqa.search(f'{e} {probe}', provider=provider), ents))
43
+ scored = []
44
+ for e, pack in zip(ents, packs):
45
+ hay = ' '.join((r['title'] + ' ' + r['body'] for r in pack))
46
+ cov = [w for w in cw if covers(hay, w)]
47
+ 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()]
48
+ best = None
49
+ if sents:
50
+ sc = self.verify.predict([(q, f"{r['title']}. {s}") for r, s in sents[:16]], batch_size=32, show_progress_bar=False)
51
+ j = max(range(len(sc)), key=lambda i: float(sc[i]))
52
+ best = (float(sc[j]), sents[j][1], sents[j][0])
53
+ 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})
54
+ scored.sort(key=lambda x: (-x['covered'], -x['v']))
55
+ top = scored[0]
56
+ runner = scored[1] if len(scored) > 1 else None
57
+ 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'], '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))}
gguf/{gse-planner-120m-v2-Q8_0.gguf → tinyqa-1-moss-glue-Q8_0.gguf} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:92d4c498657415ea67883dba13d3221123b16fd330930dc1989c94339a87fcb7
3
- size 122229952
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bdb15946920cdac9ea17eaeefa38095dd2fa17516dcf0bf582f781d685554520
3
+ size 122229888
gguf/{gse-sft-120m-Q8_0.gguf → tinyqa-1-moss-planner-Q8_0.gguf} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:cb0196c2904ad648d3397397b6515767c10d13a48764de8b93804a2cbf54b688
3
- size 122229920
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a963495409d2838fcc3136c0d573b1d4d907e5d043c6cc6e4652ddae7d857c5
3
+ size 122229888
gguf/{gse-verbaliser-120m-short-Q8_0.gguf → tinyqa-1-moss-verbaliser-Q8_0.gguf} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e7665ef5997222de701c43360dbd89ca3f62af100cf95badfb56c2ed691347b1
3
- size 122229984
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dbd60b72ec1e5668c2e29e8bb70e393495a3d814e51ea9086fe39ebd649b52e4
3
+ size 122229888
models/gse-ranker/ranker_meta.json DELETED
@@ -1 +0,0 @@
1
- {"gold_at_1": 0.9491945477075588, "n_test": 807, "pairs": 382361, "steps": 5974, "minutes": 2.916218602657318}
 
 
models/gse-verifier-v4-33m/verifier_meta.json DELETED
@@ -1,38 +0,0 @@
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-ranker → ranker}/config.json RENAMED
File without changes
models/{gse-ranker → ranker}/model.safetensors RENAMED
File without changes
models/{gse-ranker → ranker}/tokenizer.json RENAMED
File without changes
models/{gse-ranker → ranker}/tokenizer_config.json RENAMED
File without changes
models/{gse-verifier-v4-33m → verifier}/config.json RENAMED
File without changes
models/{gse-verifier-v4-33m → verifier}/model.safetensors RENAMED
File without changes
models/{gse-verifier-v4-33m → verifier}/special_tokens_map.json RENAMED
File without changes
models/{gse-verifier-v4-33m → verifier}/tokenizer.json RENAMED
File without changes
models/{gse-verifier-v4-33m → verifier}/tokenizer_config.json RENAMED
File without changes
models/{gse-verifier-v4-33m → verifier}/vocab.txt RENAMED
File without changes
moss.sh CHANGED
@@ -10,42 +10,42 @@
10
  # Optional: put SERPER_API_KEY=... in .env next to this script for Google results and verifier-gated retries.
11
  set -uo pipefail
12
  ROOT=$(cd "$(dirname "$0")" && pwd); CODE="$ROOT/code"; PY="$ROOT/.venv/bin/python"; PORT=${MOSS_PORT:-8091}; URL="http://127.0.0.1:$PORT"
13
- LOGS="$CODE/local/data"; mkdir -p "$LOGS"
14
- stop_all() { pkill -f "moss_server.py --port $PORT" 2>/dev/null; pkill -f "llama-server.*--port 80(89|93|95)" 2>/dev/null; true; }
15
  case "${1:-start}" in
16
  setup)
17
  command -v python3.11 >/dev/null || { echo "needs Python 3.11 (macOS: brew install python@3.11)"; exit 1; }
18
  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
19
- 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"
20
  echo "setup done; next: ./moss.sh start";;
21
  start)
22
  [ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
23
  stop_all; sleep 1
24
  [ -f "$ROOT/.env" ] && set -a && . "$ROOT/.env" && set +a
25
- export GSE_BACKUP="$ROOT" GSE_VERIFIER="$ROOT/models/gse-verifier-v4-33m" GSE_RANKER="$ROOT/models/gse-ranker" GSE_TAU_V=1.5
26
- export GSE_SOURCE_PENALTY=1 GSE_QUOTABLE=1 GSE_SEARCH=ddgs
27
- export GSE_BLOCK_DOMAINS="${GSE_BLOCK_DOMAINS:-}" # no sites blocked; the benchmark scripts keep their own list of benchmark-hosting sites
28
  # retries for uncertified answers go to Google; DuckDuckGo retries take 10-40 s, so without a Serper key they stay off
29
- 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
30
  if command -v llama-server >/dev/null; then
31
- export GSE_VERBALIZE=own GSE_VERBALISER=http://127.0.0.1:8095
32
- (nohup llama-server -m "$ROOT/gguf/gse-sft-120m-Q8_0.gguf" -c 2048 --port 8089 -t 4 --special > "$LOGS/decoder.log" 2>&1 &)
33
- (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 &)
34
- (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 &)
35
- else export GSE_VERBALIZE=template; echo "llama-server not found: the answer line comes from a template"; fi
36
- (cd "$CODE" && nohup "$PY" local/moss_server.py --port "$PORT" > "$LOGS/moss.log" 2>&1 &)
37
  for i in $(seq 1 180); do curl -s -m 1 "$URL/health" | grep -q '"models": true' && { echo "ready: ./moss.sh ask \"your question\""; exit 0; }; sleep 1; done
38
  echo "did not start; see $LOGS/moss.log"; exit 1;;
39
  index)
40
  [ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
41
  src=${2:?usage: ./moss.sh index <folder-or-jsonl>}; src=$(cd "$(dirname "$src")" && pwd)/$(basename "$src")
42
- (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)
43
  echo "ready to use: ./moss.sh ask --local \"your question\"";;
44
  stop) stop_all; echo stopped;;
45
  status) curl -s -m 1 "$URL/health" | grep -q '"models": true' && echo running || echo "not running";;
46
  ask)
47
  curl -s -m 1 "$URL/health" | grep -q '"models": true' || { echo "not running: ./moss.sh start first"; exit 1; }
48
  [ -f "$ROOT/.env" ] && set -a && . "$ROOT/.env" && set +a
49
- shift; MOSS_PROVIDER=$([ -n "${SERPER_API_KEY:-}" ] && echo serper || echo ddgs) "$PY" "$CODE/local/moss_cli.py" "$URL" "$@";;
50
  *) sed -n 2,9p "$0";;
51
  esac
 
10
  # Optional: put SERPER_API_KEY=... in .env next to this script for Google results and verifier-gated retries.
11
  set -uo pipefail
12
  ROOT=$(cd "$(dirname "$0")" && pwd); CODE="$ROOT/code"; PY="$ROOT/.venv/bin/python"; PORT=${MOSS_PORT:-8091}; URL="http://127.0.0.1:$PORT"
13
+ LOGS="$ROOT/data"; mkdir -p "$LOGS"
14
+ stop_all() { pkill -f "tinyqa.server --port $PORT" 2>/dev/null; pkill -f "llama-server.*--port 80(89|93|95)" 2>/dev/null; true; }
15
  case "${1:-start}" in
16
  setup)
17
  command -v python3.11 >/dev/null || { echo "needs Python 3.11 (macOS: brew install python@3.11)"; exit 1; }
18
  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
19
+ command -v llama-server >/dev/null || echo "optional: install llama.cpp (macOS: brew install llama.cpp) so the 113M models write the answer line; without it a template writes it"
20
  echo "setup done; next: ./moss.sh start";;
21
  start)
22
  [ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
23
  stop_all; sleep 1
24
  [ -f "$ROOT/.env" ] && set -a && . "$ROOT/.env" && set +a
25
+ export MOSS_HOME="$ROOT" MOSS_VERIFIER="$ROOT/models/verifier" MOSS_RANKER="$ROOT/models/ranker" MOSS_TAU_V=1.5
26
+ export MOSS_SOURCE_PENALTY=1 MOSS_QUOTABLE=1 MOSS_SEARCH=ddgs
27
+ export MOSS_BLOCK_DOMAINS="${MOSS_BLOCK_DOMAINS:-}" # no sites blocked unless you list some
28
  # retries for uncertified answers go to Google; DuckDuckGo retries take 10-40 s, so without a Serper key they stay off
29
+ if [ -n "${SERPER_API_KEY:-}" ]; then export MOSS_FALLBACK=1 MOSS_PLANNER_RETRY=1 MOSS_SIEVE_RETRY=1; else export MOSS_FALLBACK=0 MOSS_PLANNER_RETRY=0 MOSS_SIEVE_RETRY=0; fi
30
  if command -v llama-server >/dev/null; then
31
+ export MOSS_VERBALIZE=own MOSS_VERBALISER=http://127.0.0.1:8095
32
+ (nohup llama-server -m "$ROOT/gguf/tinyqa-1-moss-glue-Q8_0.gguf" -c 2048 --port 8089 -t 4 --special > "$LOGS/decoder.log" 2>&1 &)
33
+ (nohup llama-server -m "$ROOT/gguf/tinyqa-1-moss-planner-Q8_0.gguf" -c 1024 --port 8093 -t 4 --special > "$LOGS/planner.log" 2>&1 &)
34
+ (nohup llama-server -m "$ROOT/gguf/tinyqa-1-moss-verbaliser-Q8_0.gguf" -c 1024 --port 8095 -t 4 --special > "$LOGS/verbaliser.log" 2>&1 &)
35
+ else export MOSS_VERBALIZE=template; echo "llama-server not found: the answer line comes from a template"; fi
36
+ (cd "$CODE" && nohup "$PY" -m tinyqa.server --port "$PORT" > "$LOGS/moss.log" 2>&1 &)
37
  for i in $(seq 1 180); do curl -s -m 1 "$URL/health" | grep -q '"models": true' && { echo "ready: ./moss.sh ask \"your question\""; exit 0; }; sleep 1; done
38
  echo "did not start; see $LOGS/moss.log"; exit 1;;
39
  index)
40
  [ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
41
  src=${2:?usage: ./moss.sh index <folder-or-jsonl>}; src=$(cd "$(dirname "$src")" && pwd)/$(basename "$src")
42
+ (cd "$CODE" && MOSS_HOME="$ROOT" "$PY" -c 'import sys; from tinyqa import pipeline; print(f"indexed {pipeline.index_corpus(sys.argv[1]):,} passages from {sys.argv[1]}")' "$src" 2>&1 | grep -v -i warning)
43
  echo "ready to use: ./moss.sh ask --local \"your question\"";;
44
  stop) stop_all; echo stopped;;
45
  status) curl -s -m 1 "$URL/health" | grep -q '"models": true' && echo running || echo "not running";;
46
  ask)
47
  curl -s -m 1 "$URL/health" | grep -q '"models": true' || { echo "not running: ./moss.sh start first"; exit 1; }
48
  [ -f "$ROOT/.env" ] && set -a && . "$ROOT/.env" && set +a
49
+ shift; cd "$CODE" && MOSS_PROVIDER=$([ -n "${SERPER_API_KEY:-}" ] && echo serper || echo ddgs) "$PY" -m tinyqa.cli "$URL" "$@";;
50
  *) sed -n 2,9p "$0";;
51
  esac
requirements.txt CHANGED
@@ -1,9 +1,7 @@
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
 
1
+ # RysoAI TinyQA-1 Moss, tested on Python 3.11, CPU only.
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
  trafilatura==2.3.1