Question Answering
sentence-transformers
Safetensors
GGUF
English
retrieval
cross-encoder
verification
citations
edge
cpu
offline
Eval Results (legacy)
Instructions to use RysoAI/tinyqa-1-moss with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use RysoAI/tinyqa-1-moss with sentence-transformers:
from sentence_transformers import CrossEncoder model = CrossEncoder("RysoAI/tinyqa-1-moss") query = "Which planet is known as the Red Planet?" passages = [ "Venus is often called Earth's twin because of its similar size and proximity.", "Mars, known for its reddish appearance, is often referred to as the Red Planet.", "Jupiter, the largest planet in our solar system, has a prominent red spot.", "Saturn, famous for its rings, is sometimes mistaken for the Red Planet." ] scores = model.predict([(query, passage) for passage in passages]) print(scores) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use RysoAI/tinyqa-1-moss with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf RysoAI/tinyqa-1-moss:Q8_0 # Run inference directly in the terminal: llama cli -hf RysoAI/tinyqa-1-moss:Q8_0
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf RysoAI/tinyqa-1-moss:Q8_0 # Run inference directly in the terminal: llama cli -hf RysoAI/tinyqa-1-moss:Q8_0
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf RysoAI/tinyqa-1-moss:Q8_0 # Run inference directly in the terminal: ./build/bin/llama cli -hf RysoAI/tinyqa-1-moss:Q8_0
Use Docker
docker model run hf.co/RysoAI/tinyqa-1-moss:Q8_0
- Llama new
- LM Studio
- Jan
- Ollama
How to use RysoAI/tinyqa-1-moss with Ollama:
ollama run hf.co/RysoAI/tinyqa-1-moss:Q8_0
- Unsloth Desktop
- Docker Model Runner
How to use RysoAI/tinyqa-1-moss with Docker Model Runner:
docker model run hf.co/RysoAI/tinyqa-1-moss:Q8_0
- Lemonade
How to use RysoAI/tinyqa-1-moss with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull RysoAI/tinyqa-1-moss:Q8_0
Run and chat with the model
lemonade run user.tinyqa-1-moss-Q8_0
List all available models
lemonade list
- Atomic Chat
Terminal interface only: remove the web page and paragraph mode
Browse files- NOTICE.md +0 -1
- README.md +1 -1
- SHA256SUMS +5 -6
- code/local/experiments/doors.py +0 -268
- code/local/moss_cli.py +30 -0
- code/local/moss_server.py +37 -0
- code/local/webqa_server.py +0 -54
- code/local/webui/index.html +0 -177
- moss.sh +13 -19
NOTICE.md
CHANGED
|
@@ -10,7 +10,6 @@ RysoAI TinyQA-1 Moss code and the weights in `models/` and `gguf/` are released
|
|
| 10 |
| Verifier, 33M | `models/gse-verifier-v4-33m` | Apache-2.0; fine-tuned from `cross-encoder/ms-marco-MiniLM-L12-v2` (Apache-2.0) |
|
| 11 |
| Verbaliser, glue decoder, planner, 113M each | `gguf/` | Apache-2.0 |
|
| 12 |
| Reader, 33M | not included; downloaded at run time | `deepset/minilm-uncased-squad2`, CC-BY-4.0 |
|
| 13 |
-
| Entailment scorer, 22M (paragraph mode only) | not included; downloaded on first use | `cross-encoder/nli-deberta-v3-xsmall`, Apache-2.0 |
|
| 14 |
|
| 15 |
## Attributions
|
| 16 |
|
|
|
|
| 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 |
|
| 14 |
## Attributions
|
| 15 |
|
README.md
CHANGED
|
@@ -60,7 +60,7 @@ sourced results can be passed to a large language model to reason over.
|
|
| 60 |
|
| 61 |
```bash
|
| 62 |
./moss.sh setup # Python 3.11 environment with pinned dependencies
|
| 63 |
-
./moss.sh start #
|
| 64 |
./moss.sh ask "Who designed the Missouri Centennial half dollar?"
|
| 65 |
```
|
| 66 |
|
|
|
|
| 60 |
|
| 61 |
```bash
|
| 62 |
./moss.sh setup # Python 3.11 environment with pinned dependencies
|
| 63 |
+
./moss.sh start # loads the models in the background
|
| 64 |
./moss.sh ask "Who designed the Missouri Centennial half dollar?"
|
| 65 |
```
|
| 66 |
|
SHA256SUMS
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./LICENSE
|
| 2 |
-
|
| 3 |
-
|
| 4 |
24803f77e64d9450d9fb9908e93b729a4e0b3846271c7b3b0a003eb14ad20663 ./code/gse_mini/__init__.py
|
| 5 |
fa7fd1f30076205c9ed9d6cc959a6e0b661d1bd8f8f85876663d027fa78cb6c5 ./code/gse_mini/answer.py
|
| 6 |
3acb6af87f7357c6d606cbcefeca6d84f125270e274aa994ccbb22eeaee2342f ./code/gse_mini/dense.py
|
|
@@ -18,12 +18,11 @@ b735dd50e07f0af716d085a7c954be62311cbc2201e0162d0b5f7301cbe4021c ./code/gse_min
|
|
| 18 |
623dee5b1fa5ce91b6ad33d2b7a1773fec08fed1079b22b54c7a03872e7e2752 ./code/gse_mini/store.py
|
| 19 |
f07558ebcc0f3b1a55fe82810cb651b6ef3dd93043160a377a18984b8bc3bcec ./code/gse_mini/verify.py
|
| 20 |
a29678791b6b45f2a0fb6c81bb185cfa17292de1c434360b936bb76ad5e8d194 ./code/local/bench_web.py
|
| 21 |
-
40645317b8164be7cfde131a578cf52dfb7e449106417d77aae23bc5f19dfc2e ./code/local/experiments/doors.py
|
| 22 |
c831fcf7c72aeb837a2d8d0a5958a2068c115b76c973a0876e12eee70ba9bb07 ./code/local/experiments/sieve.py
|
|
|
|
|
|
|
| 23 |
ad1fd84941ed0f772077a450e548741da4837449c3000fd48d8fcdaab93582cd ./code/local/regrade.py
|
| 24 |
7e2de6af191529298c3907703e36176f9773c65559a0ecbc5a81d5baf5ce0857 ./code/local/webqa.py
|
| 25 |
-
1e202a8f9750e3387eaf2524e0cd78081fdd97cdbcd5cdf882d68625c209470a ./code/local/webqa_server.py
|
| 26 |
-
6c78d4fc99b0788470f4f9d56c6eedb16a69ce393eeb525b5b04050328fda8a6 ./code/local/webui/index.html
|
| 27 |
92d4c498657415ea67883dba13d3221123b16fd330930dc1989c94339a87fcb7 ./gguf/gse-planner-120m-v2-Q8_0.gguf
|
| 28 |
cb0196c2904ad648d3397397b6515767c10d13a48764de8b93804a2cbf54b688 ./gguf/gse-sft-120m-Q8_0.gguf
|
| 29 |
e7665ef5997222de701c43360dbd89ca3f62af100cf95badfb56c2ed691347b1 ./gguf/gse-verbaliser-120m-short-Q8_0.gguf
|
|
@@ -39,7 +38,7 @@ e4288df3d671124dd6d41ee93e147b4fb268cdd2b72df1a6e369239488edd2ec ./models/gse-v
|
|
| 39 |
7b082b48a08a0b5c5939d99472e33addce3d96202155e33f7928cecd171186a0 ./models/gse-verifier-v4-33m/tokenizer_config.json
|
| 40 |
060042f8f498f6039fc05a5771607a91d9d959dc7874f1a37cec806fb4ea21be ./models/gse-verifier-v4-33m/verifier_meta.json
|
| 41 |
07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3 ./models/gse-verifier-v4-33m/vocab.txt
|
| 42 |
-
|
| 43 |
d02efcc9918800b351ab5a719ebe0d045688c24e5ffa2ff2731c8ce8f1ab63ce ./requirements.txt
|
| 44 |
16095ae79e1a75787c2e673a9c4f39a76a77aba0eb7af9faad3252a7aefb8f8f ./results/freshqa_600_serper_summary.json
|
| 45 |
74a4fefd1e361e24f32c84e1f47e9ba429b18248b42402fa39e6f16647655ba7 ./results/popqa_1000_serper_summary.json
|
|
|
|
| 1 |
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./LICENSE
|
| 2 |
+
d1f106ed157597e0420995633b499c9c60211a3769491cff3a7802c8b9b8e036 ./NOTICE.md
|
| 3 |
+
e322ec22435ecc70205ee8862861f34b9d65db85879f1f726dec8e5c98ac8322 ./README.md
|
| 4 |
24803f77e64d9450d9fb9908e93b729a4e0b3846271c7b3b0a003eb14ad20663 ./code/gse_mini/__init__.py
|
| 5 |
fa7fd1f30076205c9ed9d6cc959a6e0b661d1bd8f8f85876663d027fa78cb6c5 ./code/gse_mini/answer.py
|
| 6 |
3acb6af87f7357c6d606cbcefeca6d84f125270e274aa994ccbb22eeaee2342f ./code/gse_mini/dense.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
|
|
|
|
| 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 |
+
d5ffc49aa5988a6eb337aa976f27720ea5700ba459f5e38a1b7a23d57b7d05f6 ./moss.sh
|
| 42 |
d02efcc9918800b351ab5a719ebe0d045688c24e5ffa2ff2731c8ce8f1ab63ce ./requirements.txt
|
| 43 |
16095ae79e1a75787c2e673a9c4f39a76a77aba0eb7af9faad3252a7aefb8f8f ./results/freshqa_600_serper_summary.json
|
| 44 |
74a4fefd1e361e24f32c84e1f47e9ba429b18248b42402fa39e6f16647655ba7 ./results/popqa_1000_serper_summary.json
|
code/local/experiments/doors.py
DELETED
|
@@ -1,268 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""Doors: mini-tools that make the retrieval machine do things that are not single-sentence Q&A, each tried on a few examples.
|
| 3 |
-
Nothing is generated anywhere; every word shown is copied from a source (footnoted) or from the question. Google via Serper
|
| 4 |
-
by default (GSE_SEARCH overrides): a demo costs a handful of calls, and speed matters more than cents.
|
| 5 |
-
paragraph "Who won the Chinese Civil War?" context + actors + outcome, each a verified quote, arranged
|
| 6 |
-
analogy "Paris:France:Tokyo" A is to B as C is to ? (relation sentence -> template -> completion)
|
| 7 |
-
chain "Greenland ice sheet melts->Netherlands" cause -> quoted effect -> quoted effect on the target
|
| 8 |
-
induct "marsupials|have pouches" instances from the web, each checked, proportion reported
|
| 9 |
-
dialectic "cracking your knuckles causes arthritis" strongest support, strongest denial, an adjudicating source
|
| 10 |
-
judge tiny NLI judge vs the GPT-4.1 verdicts already on disk (no search)
|
| 11 |
-
.venv-local/bin/python local/experiments/doors.py paragraph "Who won the Chinese Civil War?" --pages 2"""
|
| 12 |
-
import argparse, collections, json, os, re, sys, time, glob
|
| 13 |
-
HERE = os.path.dirname(os.path.abspath(__file__)); LOCAL = os.path.dirname(HERE); ROOT = os.path.dirname(LOCAL)
|
| 14 |
-
sys.path.insert(0, LOCAL); sys.path.insert(0, ROOT)
|
| 15 |
-
import webqa
|
| 16 |
-
from webqa import search, candidates, normalize
|
| 17 |
-
PROV = os.environ.get("GSE_SEARCH") or "serper"
|
| 18 |
-
STOP = {"the", "a", "an", "of", "in", "on", "at", "to", "for", "and", "or", "is", "was", "are", "were", "by", "with", "as", "its", "it", "that", "this", "which"}
|
| 19 |
-
|
| 20 |
-
class Models:
|
| 21 |
-
def __init__(self, stack=None):
|
| 22 |
-
t = time.time(); self.stack = stack or webqa.Stack()
|
| 23 |
-
from sentence_transformers import CrossEncoder
|
| 24 |
-
self.nli = CrossEncoder("cross-encoder/nli-deberta-v3-xsmall", device="cpu")
|
| 25 |
-
lab = {v.lower()[:3]: k for k, v in self.nli.config.id2label.items()}; self.ENT, self.CON = lab["ent"], lab["con"]
|
| 26 |
-
print(f"[doors] models loaded in {time.time()-t:.1f} s", flush=True)
|
| 27 |
-
def nli_scores(self, pairs):
|
| 28 |
-
if not pairs: return []
|
| 29 |
-
p = self.nli.predict(pairs, batch_size=32, show_progress_bar=False, apply_softmax=True)
|
| 30 |
-
return [(float(x[self.ENT]), float(x[self.CON])) for x in p]
|
| 31 |
-
def best(self, q, cands, k=8, penalty=None):
|
| 32 |
-
"""Rank, then verify, exactly as the question page does. Returns (candidate, verifier score). `penalty(c)` is subtracted
|
| 33 |
-
from the verifier score before the pick (source quality), never shown as the score."""
|
| 34 |
-
if not cands: return None, -99.0
|
| 35 |
-
s1 = self.stack.rank.predict([(q, f"{c['title']}. {c['sent']}") for c in cands], batch_size=32, show_progress_bar=False)
|
| 36 |
-
order = sorted(range(len(cands)), key=lambda i: -float(s1[i]))[:k]
|
| 37 |
-
s2 = self.stack.verify.predict([(q, f"{cands[i]['title']}. {cands[i]['sent']}") for i in order], batch_size=32, show_progress_bar=False)
|
| 38 |
-
adj = [float(s2[j]) - (penalty(cands[order[j]]) if penalty else 0.0) for j in range(len(order))]
|
| 39 |
-
j = max(range(len(order)), key=lambda j: adj[j]); return cands[order[j]], float(s2[j])
|
| 40 |
-
def span(self, q, c):
|
| 41 |
-
sp = self.stack.extract(q, [(f"{c['title'].split(' | ')[0].strip()}. {c['body']}", "E1")], answer_type=None)
|
| 42 |
-
return re.sub(r"\b(\w+)\1\b", r"\1", sp["answer"]).strip() if sp else None
|
| 43 |
-
|
| 44 |
-
class Refs:
|
| 45 |
-
def __init__(self): self.items = []; self.idx = {}
|
| 46 |
-
def n(self, c):
|
| 47 |
-
if c["url"] not in self.idx: self.idx[c["url"]] = len(self.items) + 1; self.items.append((c["title"], c["url"]))
|
| 48 |
-
return self.idx[c["url"]]
|
| 49 |
-
def render(self): return "\n".join(f" [{i+1}] {t} — {u}" for i, (t, u) in enumerate(self.items))
|
| 50 |
-
|
| 51 |
-
def dedupe(cands):
|
| 52 |
-
seen = set(); out = []
|
| 53 |
-
for c in cands:
|
| 54 |
-
k = normalize(c["sent"])[:120]
|
| 55 |
-
if k and k not in seen: seen.add(k); out.append(c)
|
| 56 |
-
return out
|
| 57 |
-
|
| 58 |
-
# ---------------------------------------------------------------- paragraph: a frontier-shaped answer made of quotes
|
| 59 |
-
def subject_of(q):
|
| 60 |
-
s = q.strip().rstrip("?").strip()
|
| 61 |
-
m = re.match(r"^(?:who|what|when|where|why|how)\s+(?:won|lost|is|was|were|are|did|does|do|happened\s+(?:in|at|during)|caused|started|ended|led)\s+(?:the\s+|a\s+|an\s+)?(.+)$", s, re.I)
|
| 62 |
-
return (m.group(1) if m else s).strip()
|
| 63 |
-
|
| 64 |
-
FACETS = [("context", "What was {X}?"), ("when", "When did {X} happen?"), ("who", "Who was involved in {X}?"), ("why", "Why did {X} happen?"), ("outcome", "{Q}"), ("after", "What was the result of {X}?")]
|
| 65 |
-
|
| 66 |
-
FORUMS = ("reddit.com", "quora.com", "answers.com", "stackexchange.com", "facebook.com", "pinterest.", "tiktok.com", "youtube.com", "brainly.", "studocu", "coursehero", "quizlet")
|
| 67 |
-
def source_penalty(c):
|
| 68 |
-
"""Flaw class, not a per-question fix: a forum post that happens to state the fact should not beat a reference page that
|
| 69 |
-
states it as well. The penalty only breaks near-ties; a forum sentence still wins when it is the only verified one."""
|
| 70 |
-
u = c["url"].lower(); return 2.5 if any(f in u for f in FORUMS) else (0.5 if u.endswith(".pdf") else 0.0)
|
| 71 |
-
def readable(c):
|
| 72 |
-
s = c["sent"]; letters = [ch for ch in s if ch.isalpha()]
|
| 73 |
-
if letters and sum(ch.isupper() for ch in letters) / len(letters) > 0.6: return False # shouting PDFs and headings
|
| 74 |
-
if len(s) < 30 or s.count("...") > 1: return False
|
| 75 |
-
return True
|
| 76 |
-
def paragraph_iter(M, q, pages=0, tau=3.0, extra=3, provider=None):
|
| 77 |
-
"""Yields stage events like Stack.answer_iter: search, facet (one per facet decided), done (paragraph + references)."""
|
| 78 |
-
prov = provider or PROV
|
| 79 |
-
t0 = time.time(); webqa.PAGES = pages; X = subject_of(q); refs = Refs(); calls = 0
|
| 80 |
-
pool = dedupe(candidates(search(q, provider=prov), q if pages else None) + candidates(search(X, provider=prov), X if pages else None)); calls += 2
|
| 81 |
-
pool = [c for c in pool if readable(c)]
|
| 82 |
-
t1 = time.time(); yield {"stage": "search", "ms": round(1000*(t1-t0)), "n": len(pool), "calls": calls, "subject": X}
|
| 83 |
-
used = set(); picked = {}; log = []; t_extra = [0.0]
|
| 84 |
-
# the asked question ("outcome") is decided first so it has first call on the extra-search budget and on the best sentence
|
| 85 |
-
for name, tpl in sorted(FACETS, key=lambda f: f[0] != "outcome"):
|
| 86 |
-
tf = time.time(); fq = tpl.format(X=X, Q=q)
|
| 87 |
-
cand = [c for c in pool if normalize(c["sent"])[:120] not in used]
|
| 88 |
-
c, v = M.best(fq, cand, penalty=source_penalty)
|
| 89 |
-
if (c is None or v < tau) and extra > 0 and name in ("outcome", "context", "who", "why"): # search more only when the pool is silent
|
| 90 |
-
xq = f"{X} outcome result" if name == "outcome" else fq # the question itself was already searched
|
| 91 |
-
ts = time.time(); more = dedupe(candidates(search(xq, provider=prov))); t_extra[0] += time.time() - ts; calls += 1; extra -= 1
|
| 92 |
-
pool = dedupe(pool + [m for m in more if readable(m)]); cand = [c for c in pool if normalize(c["sent"])[:120] not in used]
|
| 93 |
-
c, v = M.best(fq, cand, penalty=source_penalty)
|
| 94 |
-
log.append((name, fq, round(v, 1), (c["sent"][:70] if c else None)))
|
| 95 |
-
keep = c is not None and not ((v < tau and name != "outcome") or (name == "outcome" and v < -4.0))
|
| 96 |
-
if keep:
|
| 97 |
-
used.add(normalize(c["sent"])[:120]); sent = c["sent"].strip()
|
| 98 |
-
if name == "outcome":
|
| 99 |
-
sp = M.span(q, c)
|
| 100 |
-
if sp and sp in sent and v >= tau: sent = sent.replace(sp, f"**{sp}**", 1)
|
| 101 |
-
if v < tau: sent += " [unverified]" # the asked question is always answered, tagged like the page does
|
| 102 |
-
picked[name] = f"{sent}[{refs.n(c)}]"
|
| 103 |
-
yield {"stage": "facet", "name": name, "question": fq, "score": round(v, 1), "kept": keep, "ms": round(1000*(time.time()-tf)), "sent": (c["sent"][:90] if c else None)}
|
| 104 |
-
parts = [picked[n] for n, _ in FACETS if n in picked]
|
| 105 |
-
ms_models = round(1000 * (time.time() - t1 - t_extra[0])); ms_search = round(1000 * (t1 - t0 + t_extra[0]))
|
| 106 |
-
yield {"stage": "done", "q": q, "subject": X, "paragraph": " ".join(parts), "refs": refs.render(), "ref_list": refs.items, "facets": log, "calls": calls, "ms_search": ms_search, "ms_models": ms_models}
|
| 107 |
-
|
| 108 |
-
def paragraph(M, q, pages=0, tau=3.0, extra=3, provider=None):
|
| 109 |
-
for ev in paragraph_iter(M, q, pages, tau, extra, provider):
|
| 110 |
-
if ev["stage"] == "done": return ev
|
| 111 |
-
|
| 112 |
-
# ---------------------------------------------------------------- analogy: A is to B as C is to ?
|
| 113 |
-
def analogy(M, A, B, C):
|
| 114 |
-
t0 = time.time(); pool = candidates(search(f"{A} {B}", provider=PROV)); calls = 1
|
| 115 |
-
rels = []
|
| 116 |
-
for c in pool:
|
| 117 |
-
s = c["sent"]
|
| 118 |
-
for pat, order in ((re.escape(A) + r"(.{3,60}?)" + re.escape(B), "AB"), (re.escape(B) + r"(.{3,60}?)" + re.escape(A), "BA")):
|
| 119 |
-
m = re.search(pat, s, re.I)
|
| 120 |
-
if m:
|
| 121 |
-
rel = m.group(1).strip(" ,;:")
|
| 122 |
-
if 1 <= len(rel.split()) <= 7 and not re.search(r"[.?!()]", rel): rels.append((rel, order, c))
|
| 123 |
-
if not rels: return {"A": A, "B": B, "C": C, "answer": None, "why": "no sentence relates A and B", "calls": calls}
|
| 124 |
-
qrel = f"What is the relationship between {A} and {B}?"
|
| 125 |
-
s1 = M.stack.rank.predict([(qrel, f"{c['title']}. {c['sent']}") for _, _, c in rels], batch_size=32, show_progress_bar=False)
|
| 126 |
-
rels = [rels[i] for i in sorted(range(len(rels)), key=lambda i: -float(s1[i]))][:3]
|
| 127 |
-
for rel, order, c in rels:
|
| 128 |
-
probe = f"{C} {rel}" if order == "AB" else f"{rel} {C}"
|
| 129 |
-
qc = f"{C} {rel} what?" if order == "AB" else f"What {rel} {C}?"
|
| 130 |
-
pool2 = [x for x in candidates(search(probe, provider=PROV)) if normalize(C) in normalize(x["title"] + " " + x["body"])]; calls += 1
|
| 131 |
-
if not pool2: continue
|
| 132 |
-
s1 = M.stack.rank.predict([(qc, f"{x['title']}. {x['sent']}") for x in pool2], batch_size=32, show_progress_bar=False)
|
| 133 |
-
top = [pool2[i] for i in sorted(range(len(pool2)), key=lambda i: -float(s1[i]))[:6]]
|
| 134 |
-
hits = collections.Counter(); ex = {}
|
| 135 |
-
for x in top:
|
| 136 |
-
a = M.span(qc, x)
|
| 137 |
-
if not a: continue
|
| 138 |
-
a = a.strip(" .,;:\"'")
|
| 139 |
-
if not a or len(a) > 60 or normalize(a) in (normalize(A), normalize(B), normalize(C)) or normalize(a) in normalize(rel) or normalize(rel) in normalize(a): continue
|
| 140 |
-
hits[normalize(a)] += 1; ex.setdefault(normalize(a), (a, x))
|
| 141 |
-
if hits:
|
| 142 |
-
key = hits.most_common(1)[0][0]; a, c2 = ex[key]
|
| 143 |
-
return {"A": A, "B": B, "C": C, "answer": a, "relation": rel, "relation_sentence": c["sent"], "relation_url": c["url"], "answer_sentence": c2["sent"], "answer_url": c2["url"], "sources_agreeing": hits[key], "calls": calls, "ms": round(1000*(time.time()-t0))}
|
| 144 |
-
return {"A": A, "B": B, "C": C, "answer": None, "why": "relation found, no completion found", "relation": rels[0][0], "relation_sentence": rels[0][2]["sent"], "calls": calls}
|
| 145 |
-
|
| 146 |
-
# ---------------------------------------------------------------- chain: cause -> quoted effect -> quoted effect on the target
|
| 147 |
-
CUE = r"(?:causes?|caused|leads? to|led to|results? in|resulted in|raises?|raising|increases?|increasing|reduces?|lowers?|triggers?|contributes? to|drives?|accelerates?|means?)"
|
| 148 |
-
def chain(M, cause, target):
|
| 149 |
-
t0 = time.time(); pool = []
|
| 150 |
-
for q in (f"{cause} causes", f"effects of {cause}"): pool += candidates(search(q, provider=PROV))
|
| 151 |
-
calls = 2; pool = dedupe(pool); hop1 = []
|
| 152 |
-
cw = [w for w in re.findall(r"[a-z0-9]+", cause.lower()) if w not in STOP and len(w) > 2]
|
| 153 |
-
for c in pool:
|
| 154 |
-
m = re.search(r"\b" + CUE + r"\s+(.{8,90}?)(?:[.;,]|$| which| that| and )", c["sent"], re.I)
|
| 155 |
-
if not m: continue
|
| 156 |
-
before, effect = c["sent"][:m.start()].lower(), m.group(1).strip()
|
| 157 |
-
if not any(w in before for w in cw): continue # the cause is the subject side of the cue
|
| 158 |
-
if any(w in effect.lower() for w in cw): continue # the effect must not restate the cause
|
| 159 |
-
if effect.split()[0].lower() in ("by", "of", "from", "in", "for", "to", "when", "if"): continue # "caused by ..." runs backwards
|
| 160 |
-
hop1.append((effect, c))
|
| 161 |
-
if not hop1: return {"cause": cause, "target": target, "chain": None, "why": "no causal sentence found", "calls": calls}
|
| 162 |
-
q1 = f"What does {cause} cause?"
|
| 163 |
-
s1 = M.stack.rank.predict([(q1, f"{c['title']}. {c['sent']}") for _, c in hop1], batch_size=32, show_progress_bar=False)
|
| 164 |
-
hop1 = [hop1[i] for i in sorted(range(len(hop1)), key=lambda i: -float(s1[i]))]
|
| 165 |
-
seen = set(); tried = []; best = None
|
| 166 |
-
for effect, c in hop1:
|
| 167 |
-
k = normalize(effect)[:40]
|
| 168 |
-
if k in seen or len(tried) >= 3: continue
|
| 169 |
-
seen.add(k); tried.append(effect)
|
| 170 |
-
q2 = f"How does {effect} affect {target}?"
|
| 171 |
-
tw = [w for w in re.findall(r"[a-z0-9]+", target.lower()) if w not in STOP]
|
| 172 |
-
pool2 = [x for x in candidates(search(f"{effect} {target}", provider=PROV)) if any(w in normalize(x["sent"]) for w in tw)]; calls += 1
|
| 173 |
-
c2, v = M.best(q2, pool2)
|
| 174 |
-
if c2 is not None and (best is None or v > best["v"]): best = {"effect": effect, "hop1": c["sent"], "hop1_url": c["url"], "hop2": c2["sent"], "hop2_url": c2["url"], "v": round(v, 1)}
|
| 175 |
-
return {"cause": cause, "target": target, "chain": best, "effects_tried": tried, "calls": calls, "ms": round(1000*(time.time()-t0))}
|
| 176 |
-
|
| 177 |
-
# ---------------------------------------------------------------- induct: do all X have P? instances from the web, each checked
|
| 178 |
-
def instances(cls):
|
| 179 |
-
pool = candidates(search(f"{cls} such as", provider=PROV)) + candidates(search(f"examples of {cls}", provider=PROV))
|
| 180 |
-
cnt = collections.Counter()
|
| 181 |
-
for c in pool:
|
| 182 |
-
for m in re.finditer(r"(?:such as|including|includes?|like|e\.g\.,?|for example,?)\s+([^.;:()]{5,160})", c["sent"], re.I):
|
| 183 |
-
for p in re.split(r",|\band\b|\bor\b|/", m.group(1)):
|
| 184 |
-
p = re.sub(r"^(?:the|a|an|some|many|most)\s+", "", p.strip(" ."), flags=re.I).strip()
|
| 185 |
-
if 1 <= len(p.split()) <= 3 and p and p.lower() not in cls.lower() and cls.lower() not in p.lower(): cnt[p.lower()] += 1
|
| 186 |
-
return [p for p, _ in cnt.most_common(6)]
|
| 187 |
-
|
| 188 |
-
def induct(M, cls, prop):
|
| 189 |
-
t0 = time.time(); inst = instances(cls); calls = 2; rows = []
|
| 190 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 191 |
-
with ThreadPoolExecutor(6) as ex: pools = list(ex.map(lambda i: candidates(search(f"{i} {prop}", provider=PROV)), inst))
|
| 192 |
-
for i, pool in zip(inst, pools):
|
| 193 |
-
calls += 1
|
| 194 |
-
if not pool: rows.append((i, "no text", None, None)); continue
|
| 195 |
-
hyp = f"{i} {prop}"; sc = M.nli_scores([(c["sent"], hyp) for c in pool[:40]])
|
| 196 |
-
je = max(range(len(sc)), key=lambda k: sc[k][0]); jc = max(range(len(sc)), key=lambda k: sc[k][1])
|
| 197 |
-
ent, con = sc[je][0], sc[jc][1]
|
| 198 |
-
label = "supports" if ent > 0.5 and ent >= con else ("contradicts" if con > 0.5 and con > ent else "unclear")
|
| 199 |
-
c = pool[je] if label == "supports" else pool[jc]
|
| 200 |
-
rows.append((i, label, round(max(ent, con), 2), c["sent"], c["url"]))
|
| 201 |
-
n_s = sum(1 for r in rows if r[1] == "supports"); n_c = sum(1 for r in rows if r[1] == "contradicts")
|
| 202 |
-
return {"class": cls, "property": prop, "instances": inst, "rows": rows, "supports": n_s, "contradicts": n_c, "unclear": len(rows) - n_s - n_c, "calls": calls, "ms": round(1000*(time.time()-t0))}
|
| 203 |
-
|
| 204 |
-
# ---------------------------------------------------------------- dialectic: strongest support, strongest denial, who adjudicates
|
| 205 |
-
def dialectic(M, claim):
|
| 206 |
-
t0 = time.time(); pool = dedupe(candidates(search(claim, provider=PROV)) + candidates(search(f"is it true that {claim}", provider=PROV))); calls = 2
|
| 207 |
-
sc = M.nli_scores([(c["sent"], claim) for c in pool])
|
| 208 |
-
if not sc: return {"claim": claim, "why": "no text", "calls": calls}
|
| 209 |
-
je = max(range(len(sc)), key=lambda k: sc[k][0]); jc = max(range(len(sc)), key=lambda k: sc[k][1])
|
| 210 |
-
dom = lambda c: re.sub(r"^www\.", "", re.match(r"https?://([^/]+)", c["url"]).group(1)) if re.match(r"https?://([^/]+)", c["url"]) else c["url"]
|
| 211 |
-
others = [k for k in range(len(pool)) if dom(pool[k]) not in (dom(pool[je]), dom(pool[jc])) and readable(pool[k]) and "..." not in pool[k]["sent"]]
|
| 212 |
-
ja = max(others, key=lambda k: abs(sc[k][0] - sc[k][1])) if others else None
|
| 213 |
-
out = {"claim": claim, "thesis": (pool[je]["sent"], pool[je]["url"], round(sc[je][0], 2)), "antithesis": (pool[jc]["sent"], pool[jc]["url"], round(sc[jc][1], 2)), "calls": calls, "ms": round(1000*(time.time()-t0))}
|
| 214 |
-
if ja is not None: out["adjudicator"] = (pool[ja]["sent"], pool[ja]["url"], "supports" if sc[ja][0] > sc[ja][1] else "refutes", round(abs(sc[ja][0] - sc[ja][1]), 2))
|
| 215 |
-
n_sup = sum(1 for e, c in sc if e > 0.5 and e > c); n_ref = sum(1 for e, c in sc if c > 0.5 and c > e); out["sentences"] = (len(sc), n_sup, n_ref)
|
| 216 |
-
d_sup = {dom(pool[k]) for k, (e, c) in enumerate(sc) if e > 0.5 and e > c}; d_ref = {dom(pool[k]) for k, (e, c) in enumerate(sc) if c > 0.5 and c > e}
|
| 217 |
-
out["domains"] = (sorted(d_sup), sorted(d_ref))
|
| 218 |
-
return out
|
| 219 |
-
|
| 220 |
-
# ---------------------------------------------------------------- judge: tiny NLI judge vs GPT-4.1 verdicts on disk
|
| 221 |
-
def judge(M, fn):
|
| 222 |
-
rows = [json.loads(l) for l in open(fn)]
|
| 223 |
-
def pred(r): return (f"{r['span']}. " if r.get("span") else "") + (r.get("cited") or "")
|
| 224 |
-
att = [r for r in rows if r.get("cited") and str(r.get("grade_all", "")).upper() in ("CORRECT", "INCORRECT", "A", "B")]
|
| 225 |
-
t0 = time.time(); sc = M.nli_scores([(f"The answer is {pred(r)[:300]}", f"The answer is {r['answers'][0]}") for r in att]); ms = time.time() - t0
|
| 226 |
-
agree = tp = fp = fn_ = 0; cont_agree = 0
|
| 227 |
-
for r, (e, c) in zip(att, sc):
|
| 228 |
-
contain = bool(normalize(r["answers"][0])) and normalize(r["answers"][0]) in normalize(pred(r))
|
| 229 |
-
t = "CORRECT" if (contain or e > 0.5) else "INCORRECT"; g = "CORRECT" if str(r["grade_all"]).upper() in ("CORRECT", "A") else "INCORRECT"
|
| 230 |
-
agree += t == g; tp += (t == g == "CORRECT"); fp += (t == "CORRECT" and g != "CORRECT"); fn_ += (t != "CORRECT" and g == "CORRECT")
|
| 231 |
-
cont_agree += ("CORRECT" if contain else "INCORRECT") == g
|
| 232 |
-
return {"file": os.path.basename(fn), "attempted_rows": len(att), "agreement_with_gpt41": round(agree / len(att), 3), "containment_only_agreement": round(cont_agree / len(att), 3),
|
| 233 |
-
"tiny_correct_precision": round(tp / max(1, tp + fp), 3), "tiny_correct_recall": round(tp / max(1, tp + fn_), 3), "seconds": round(ms, 1)}
|
| 234 |
-
|
| 235 |
-
def main():
|
| 236 |
-
ap = argparse.ArgumentParser(); ap.add_argument("door", choices=["paragraph", "analogy", "chain", "induct", "dialectic", "judge"]); ap.add_argument("items", nargs="*")
|
| 237 |
-
ap.add_argument("--pages", type=int, default=0); ap.add_argument("--file", default=os.path.join(LOCAL, "data", "bench", "simpleqa_1000_ddgs_gpt-4.1-2025-04-14.jsonl"))
|
| 238 |
-
a = ap.parse_args(); M = Models(); led0 = json.load(open(webqa.SERPER_LEDGER)).get("calls", 0) if os.path.exists(webqa.SERPER_LEDGER) else 0
|
| 239 |
-
for it in (a.items or [None]):
|
| 240 |
-
print("\n" + "=" * 100)
|
| 241 |
-
if a.door == "paragraph":
|
| 242 |
-
r = paragraph(M, it, pages=a.pages); print(f"Q: {r['q']} (subject: {r['subject']})\n"); print(r["paragraph"] or "(no verified sentences)"); print("\nReferences\n" + r["refs"])
|
| 243 |
-
print(f"\nfacets: " + "; ".join(f"{n} {v}" for n, fq, v, s in r["facets"])); print(f"calls {r['calls']}, search {r['ms_search']} ms, models {r['ms_models']} ms")
|
| 244 |
-
elif a.door == "analogy":
|
| 245 |
-
A, B, C = [x.strip() for x in it.split(":")]; r = analogy(M, A, B, C)
|
| 246 |
-
print(f"{A} : {B} :: {C} : {r['answer']!r} relation {r.get('relation')!r} ({r.get('sources_agreeing', 0)} sources agree, {r['calls']} calls, {r.get('ms')} ms)")
|
| 247 |
-
print(f" relation sentence: {r.get('relation_sentence')}\n completion: {r.get('answer_sentence')}\n {r.get('why', '')}")
|
| 248 |
-
elif a.door == "chain":
|
| 249 |
-
cause, target = [x.strip() for x in it.split("->")]; r = chain(M, cause, target); ch = r["chain"]
|
| 250 |
-
print(f"{cause} -> ... -> {target} (effects tried: {r.get('effects_tried')}; {r['calls']} calls, {r.get('ms')} ms)")
|
| 251 |
-
if ch: print(f" 1. {ch['hop1']}\n {ch['hop1_url']}\n 2. {ch['hop2']}\n {ch['hop2_url']}\n verifier on hop 2: {ch['v']}")
|
| 252 |
-
else: print(" " + str(r.get("why")))
|
| 253 |
-
elif a.door == "induct":
|
| 254 |
-
cls, prop = [x.strip() for x in it.split("|")]; r = induct(M, cls, prop)
|
| 255 |
-
print(f"Do all {cls} {prop}? instances found: {r['instances']} -> supports {r['supports']}, contradicts {r['contradicts']}, unclear {r['unclear']} ({r['calls']} calls, {r['ms']} ms)")
|
| 256 |
-
for row in r["rows"]: print(f" {row[0]:22s} {row[1]:12s} {row[2]} {str(row[3])[:110]}")
|
| 257 |
-
elif a.door == "dialectic":
|
| 258 |
-
r = dialectic(M, it); print(f"Claim: {it} ({r.get('sentences')} = sentences, supporting, refuting; {r['calls']} calls, {r.get('ms')} ms)")
|
| 259 |
-
for k in ("thesis", "antithesis", "adjudicator"):
|
| 260 |
-
if k in r: print(f" {k:12s} {r[k][2:]} {r[k][0][:160]}\n {r[k][1]}")
|
| 261 |
-
if "domains" in r: print(f" sites stating it: {r['domains'][0]}\n sites denying it: {r['domains'][1]}")
|
| 262 |
-
elif a.door == "judge":
|
| 263 |
-
print(json.dumps(judge(M, a.file), indent=1))
|
| 264 |
-
led1 = json.load(open(webqa.SERPER_LEDGER)).get("calls", 0) if os.path.exists(webqa.SERPER_LEDGER) else 0
|
| 265 |
-
webqa.save_caches(); print(f"\n[doors] paid calls this run: {led1 - led0} (ledger total {led1})", flush=True)
|
| 266 |
-
|
| 267 |
-
if __name__ == "__main__":
|
| 268 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/local/moss_cli.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/webqa_server.py
DELETED
|
@@ -1,54 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""Persistent local server for the tiny-model web Q&A: models load once; /ask streams each stage with its timing (SSE).
|
| 3 |
-
.venv-local/bin/python local/webqa_server.py --port 8091"""
|
| 4 |
-
import argparse, json, os, sys, threading, urllib.parse
|
| 5 |
-
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 6 |
-
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
|
| 7 |
-
import webqa
|
| 8 |
-
sys.path.insert(0, os.path.join(HERE, "experiments")); import doors
|
| 9 |
-
STACK = None; DOORS = None; LOCK = threading.Lock()
|
| 10 |
-
|
| 11 |
-
class H(BaseHTTPRequestHandler):
|
| 12 |
-
def log_message(self, *a): pass
|
| 13 |
-
def _send(self, code, body, ctype="text/html; charset=utf-8"):
|
| 14 |
-
self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
|
| 15 |
-
def do_GET(self):
|
| 16 |
-
u = urllib.parse.urlparse(self.path)
|
| 17 |
-
if u.path == "/":
|
| 18 |
-
return self._send(200, open(os.path.join(HERE, "webui", "index.html"), "rb").read())
|
| 19 |
-
if u.path == "/card":
|
| 20 |
-
p = os.path.join(HERE, "webui", "card.html")
|
| 21 |
-
return self._send(200, open(p, "rb").read()) if os.path.exists(p) else self._send(404, b"no card yet: run local/make_card.py", "text/plain")
|
| 22 |
-
if u.path == "/health":
|
| 23 |
-
return self._send(200, json.dumps({"ok": True, "models": STACK is not None}).encode(), "application/json")
|
| 24 |
-
if u.path == "/ask":
|
| 25 |
-
qs = urllib.parse.parse_qs(u.query); q = qs.get("q", [""])[0].strip(); provider = qs.get("provider", [None])[0]; mode = qs.get("mode", ["sentence"])[0]
|
| 26 |
-
verbalize = qs.get("verbalize", [None])[0] # own | own-strict | template | none; the page's "Answer line" switch
|
| 27 |
-
self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.send_header("Cache-Control", "no-cache"); self.end_headers()
|
| 28 |
-
if not q:
|
| 29 |
-
self.wfile.write(b"data: {\"stage\": \"done\", \"tier\": 3, \"why\": \"empty\"}\n\n"); return
|
| 30 |
-
with LOCK: # one question at a time: the models are not thread-safe and this is a one-person tool
|
| 31 |
-
if mode == "paragraph" and DOORS is None: _load_doors()
|
| 32 |
-
it = doors.paragraph_iter(DOORS, q, pages=int(os.environ.get("GSE_PAGES", "0")), provider=provider) if mode == "paragraph" else STACK.answer_iter(q, provider=provider, verbalize=verbalize)
|
| 33 |
-
for ev in it:
|
| 34 |
-
if ev["stage"] == "done": ev = {k: v for k, v in ev.items() if k != "results"}
|
| 35 |
-
self.wfile.write(("data: " + json.dumps(ev, ensure_ascii=False) + "\n\n").encode()); self.wfile.flush()
|
| 36 |
-
webqa.save_caches()
|
| 37 |
-
return
|
| 38 |
-
self._send(404, b"not found", "text/plain")
|
| 39 |
-
|
| 40 |
-
def _load_doors():
|
| 41 |
-
"""Paragraph mode needs a borrowed 22M NLI cross-encoder (cross-encoder/nli-deberta-v3-xsmall); load it on the first paragraph
|
| 42 |
-
request only, so the one-sentence answer runs on the ranker, the verifier and the reader alone."""
|
| 43 |
-
global DOORS
|
| 44 |
-
DOORS = doors.Models(stack=STACK)
|
| 45 |
-
|
| 46 |
-
def main():
|
| 47 |
-
global STACK
|
| 48 |
-
ap = argparse.ArgumentParser(); ap.add_argument("--port", type=int, default=8091); a = ap.parse_args()
|
| 49 |
-
STACK = webqa.Stack(); STACK.answer("warm-up question about the speed of light") # warm the models so the first real question is fast
|
| 50 |
-
print(f"[webqa-server] models loaded; http://127.0.0.1:{a.port}/", flush=True)
|
| 51 |
-
ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
|
| 52 |
-
|
| 53 |
-
if __name__ == "__main__":
|
| 54 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/local/webui/index.html
DELETED
|
@@ -1,177 +0,0 @@
|
|
| 1 |
-
<!doctype html>
|
| 2 |
-
<html lang="en">
|
| 3 |
-
<head>
|
| 4 |
-
<meta charset="utf-8">
|
| 5 |
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
-
<title>Ask the web</title>
|
| 7 |
-
<style>
|
| 8 |
-
:root{
|
| 9 |
-
--text:#202122; --muted:#54595d; --link:#3366cc; --visited:#795cb2; --rule:#a2a9b1; --hair:#c8ccd1;
|
| 10 |
-
--panel:#f8f9fa; --head:#eaecf0; --bg:#ffffff; --tag:#d33; --ok:#14866d;
|
| 11 |
-
}
|
| 12 |
-
@media (prefers-color-scheme: dark){ :root:not([data-theme="light"]){
|
| 13 |
-
--text:#eaecf0; --muted:#a2a9b1; --link:#88a3e2; --visited:#b58fe0; --rule:#54595d; --hair:#3a3f44; --panel:#1b1c1e; --head:#27292d; --bg:#101418; --tag:#f08080; --ok:#4fb39a; } }
|
| 14 |
-
*{box-sizing:border-box}
|
| 15 |
-
html,body{margin:0;background:var(--bg);color:var(--text)}
|
| 16 |
-
body{font-family:serif;font-size:16px;line-height:1.55}
|
| 17 |
-
a{color:var(--link);text-decoration:underline} a:visited{color:var(--visited)}
|
| 18 |
-
.page{max-width:760px;margin:0 auto;padding:16px 16px 140px}
|
| 19 |
-
h1{font-family:serif;font-weight:400;font-size:1.9em;line-height:1.25;margin:.4em 0 .2em;border-bottom:1px solid var(--rule);padding-bottom:3px}
|
| 20 |
-
.lede{color:var(--muted);margin:0 0 1.4em}
|
| 21 |
-
.lede code{font-family:inherit;color:var(--text)}
|
| 22 |
-
article{margin:0 0 2.2em}
|
| 23 |
-
h2{font-family:serif;font-weight:400;font-size:1.45em;line-height:1.3;margin:1.1em 0 .35em;border-bottom:1px solid var(--rule);padding-bottom:2px}
|
| 24 |
-
p{margin:.5em 0}
|
| 25 |
-
.answer b{font-weight:700}
|
| 26 |
-
sup.ref{font-size:.78em;line-height:0;vertical-align:super} sup.ref a{white-space:nowrap}
|
| 27 |
-
.tag{font-size:.86em;color:var(--tag);white-space:nowrap} .tag a{color:var(--tag)}
|
| 28 |
-
.none{font-style:italic;color:var(--muted)}
|
| 29 |
-
.muted{color:var(--muted);font-size:.92em}
|
| 30 |
-
h3{font-family:serif;font-weight:700;font-size:1.05em;margin:1.1em 0 .3em}
|
| 31 |
-
ol.refs{margin:0 0 0 1.6em;padding:0;font-size:.92em} ol.refs li{margin:.15em 0;word-break:break-all}
|
| 32 |
-
ol.refs .url{color:var(--muted)}
|
| 33 |
-
table.info{border-collapse:collapse;border:1px solid var(--rule);background:var(--bg);font-size:.92em;margin:.7em 0}
|
| 34 |
-
table.info th,table.info td{border:1px solid var(--hair);padding:.25em .6em;text-align:left;vertical-align:top}
|
| 35 |
-
table.info th{background:var(--panel);font-weight:400;width:9.5em}
|
| 36 |
-
table.info td.num{text-align:right;width:6.5em;font-variant-numeric:tabular-nums}
|
| 37 |
-
table.info tr.pending td{color:var(--muted)}
|
| 38 |
-
table.info caption{caption-side:top;text-align:left;font-weight:700;padding:.2em .1em}
|
| 39 |
-
.total{color:var(--muted);font-size:.9em}
|
| 40 |
-
form.ask{position:fixed;left:0;right:0;bottom:0;background:var(--bg);border-top:1px solid var(--text);padding:12px 16px}
|
| 41 |
-
form.ask .row{max-width:760px;margin:0 auto;display:flex;gap:8px}
|
| 42 |
-
input[type=text]{flex:1;font:inherit;font-size:16px;color:var(--text);background:var(--bg);border:1px solid var(--text);border-radius:0;padding:7px 9px;min-width:0}
|
| 43 |
-
input[type=text]:focus{outline:2px solid var(--link);outline-offset:-1px;border-color:var(--link)}
|
| 44 |
-
button{font:inherit;font-size:16px;color:var(--text);background:var(--panel);border:1px solid var(--text);border-radius:0;padding:7px 14px;cursor:pointer}
|
| 45 |
-
button:focus-visible{outline:2px solid var(--text);outline-offset:1px}
|
| 46 |
-
button[disabled]{opacity:.55;cursor:default}
|
| 47 |
-
.hint{max-width:760px;margin:6px auto 0;font-size:.85em;color:var(--muted)}
|
| 48 |
-
.stage-live td{color:var(--muted)}
|
| 49 |
-
.answer .evidence{color:var(--muted);font-size:.95em}
|
| 50 |
-
.hint label{margin-right:.4em}
|
| 51 |
-
.cols{display:grid;grid-template-columns:1fr 1fr;gap:24px} .cols>div{min-width:0}
|
| 52 |
-
.cols h3.prov{margin:.2em 0 .4em;font-weight:400;font-style:italic;border-bottom:1px solid var(--hair);padding-bottom:2px}
|
| 53 |
-
@media (max-width:700px){ .cols{grid-template-columns:1fr} }
|
| 54 |
-
details.how{margin:.6em 0} details.how summary{cursor:pointer;color:var(--muted);font-size:.92em}
|
| 55 |
-
@media (prefers-reduced-motion:no-preference){ article{animation:in .18s ease-out} @keyframes in{from{opacity:0}to{opacity:1}} }
|
| 56 |
-
</style>
|
| 57 |
-
</head>
|
| 58 |
-
<body>
|
| 59 |
-
<main class="page">
|
| 60 |
-
<h1>Ask the web</h1>
|
| 61 |
-
<p class="lede">RysoAI TinyQA-1 Moss, 89 million parameters.</p>
|
| 62 |
-
<div id="log"></div>
|
| 63 |
-
</main>
|
| 64 |
-
<form class="ask" id="form" autocomplete="off">
|
| 65 |
-
<div class="row">
|
| 66 |
-
<input type="text" id="q" placeholder="Ask a question" aria-label="Question" autofocus>
|
| 67 |
-
<button type="submit" id="go">Ask</button>
|
| 68 |
-
</div>
|
| 69 |
-
<div class="hint"><label><input type="radio" name="mode" value="sentence" checked> One sentence</label> <label><input type="radio" name="mode" value="paragraph"> Paragraph</label> <label><input type="radio" name="engine" value="ddgs" checked> DuckDuckGo</label> <label><input type="radio" name="engine" value="serper"> Google</label> <label><input type="radio" name="engine" value="local"> Local files</label></div>
|
| 70 |
-
<div class="hint">Answer line: <label><input type="radio" name="answer" value="own" checked> our 113M model</label> <label><input type="radio" name="answer" value="template"> template</label> <label><input type="radio" name="answer" value="none"> quote only</label> Compare: <label><input type="radio" name="compare" value="off" checked> off</label> <label><input type="radio" name="compare" value="answer"> model vs quote only</label> <label><input type="radio" name="compare" value="engines"> DuckDuckGo vs Google</label></div>
|
| 71 |
-
</form>
|
| 72 |
-
<script>
|
| 73 |
-
(function(){
|
| 74 |
-
const log = document.getElementById('log'), form = document.getElementById('form'), q = document.getElementById('q'), go = document.getElementById('go');
|
| 75 |
-
const STAGES = [['search','Search'],['rank','Rank sentences'],['verify','Verify'],['extract','Extract answer'],['check','Check support']];
|
| 76 |
-
let n = 0;
|
| 77 |
-
function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c])); }
|
| 78 |
-
function block(id, prov){
|
| 79 |
-
return `<div>
|
| 80 |
-
<p class="answer" id="a${id}"><span class="none">Searching…</span></p>
|
| 81 |
-
<details class="how"><summary>How this answer was made</summary>
|
| 82 |
-
<table class="info" id="t${id}">
|
| 83 |
-
${STAGES.map(([k,l]) => `<tr class="pending" id="r${id}-${k}"><th>${l}</th><td id="d${id}-${k}">—</td><td class="num" id="m${id}-${k}"></td></tr>`).join('')}
|
| 84 |
-
<tr><th>Total</th><td id="dt${id}" class="total"></td><td class="num" id="mt${id}"></td></tr>
|
| 85 |
-
</table></details>
|
| 86 |
-
<div id="refs${id}"></div></div>`;
|
| 87 |
-
}
|
| 88 |
-
const NAMES = {ddgs: 'DuckDuckGo', serper: 'Google (via Serper)'};
|
| 89 |
-
function picked(name){ const m = document.querySelector(`input[name=${name}]:checked`); return m ? m.value : null; }
|
| 90 |
-
function md(s, id){ // a paragraph is quotes with [n] footnotes and **bold** on the extracted answer; nothing else is markup
|
| 91 |
-
return esc(s).replace(/\*\*(.+?)\*\*/g, '<b>$1</b>').replace(/\[unverified\]/g, '<span class="tag">[unverified]</span>').replace(/\[(\d+)\]/g, (m, n) => `<sup class="ref"><a href="#ref${id}-${n}">[${n}]</a></sup>`);
|
| 92 |
-
}
|
| 93 |
-
function runParagraph(id, text, prov, done){
|
| 94 |
-
const t0 = performance.now();
|
| 95 |
-
const es = new EventSource('/ask?q=' + encodeURIComponent(text) + '&provider=' + prov + '&mode=paragraph');
|
| 96 |
-
const tbl = document.getElementById(`t${id}`); tbl.innerHTML = '<tr class="pending" id="r' + id + '-search"><th>Search</th><td id="d' + id + '-search">working…</td><td class="num" id="m' + id + '-search"></td></tr>';
|
| 97 |
-
es.onmessage = (e) => {
|
| 98 |
-
const ev = JSON.parse(e.data);
|
| 99 |
-
if (ev.stage === 'search'){ const r = document.getElementById(`r${id}-search`); r.classList.remove('pending'); document.getElementById(`d${id}-search`).textContent = `${ev.n} candidate sentences from ${ev.calls} searches (subject: ${ev.subject})`; document.getElementById(`m${id}-search`).textContent = ev.ms + ' ms'; }
|
| 100 |
-
else if (ev.stage === 'facet'){ const tr = document.createElement('tr'); if(!ev.kept) tr.className = 'stage-live'; tr.innerHTML = `<th>${esc(ev.name)}</th><td>${esc(ev.question)} — score ${ev.score}${ev.kept ? '' : ', not used'}</td><td class="num">${ev.ms} ms</td>`; tbl.appendChild(tr); }
|
| 101 |
-
else if (ev.stage === 'done'){
|
| 102 |
-
es.close(); done();
|
| 103 |
-
const total = Math.round(performance.now() - t0); const tr = document.createElement('tr'); tr.innerHTML = `<th>Total</th><td class="total">${ev.ms_models} ms of model time, ${ev.ms_search} ms of search</td><td class="num">${total} ms</td>`; tbl.appendChild(tr);
|
| 104 |
-
const a = document.getElementById(`a${id}`), refs = document.getElementById(`refs${id}`);
|
| 105 |
-
a.innerHTML = ev.paragraph ? md(ev.paragraph, id) : '<span class="none">No verified sentences for this question.</span>';
|
| 106 |
-
refs.innerHTML = ev.ref_list && ev.ref_list.length ? '<h3>References</h3><ol class="refs">' + ev.ref_list.map((r, i) => `<li id="ref${id}-${i+1}"><a href="${esc(r[1])}" target="_blank" rel="noopener">${esc(r[0] || r[1])}</a> <span class="url">${esc(r[1])}</span></li>`).join('') + '</ol>' : '';
|
| 107 |
-
}
|
| 108 |
-
};
|
| 109 |
-
es.onerror = () => { es.close(); done(); const a = document.getElementById(`a${id}`); if (a && a.querySelector('.none')) a.innerHTML = '<span class="none">The local server stopped answering. Start it again with local/webui.sh start.</span>'; };
|
| 110 |
-
}
|
| 111 |
-
function run(id, text, prov, done, vb){
|
| 112 |
-
if (picked('mode') === 'paragraph') return runParagraph(id, text, prov, done);
|
| 113 |
-
const t0 = performance.now();
|
| 114 |
-
const es = new EventSource('/ask?q=' + encodeURIComponent(text) + '&provider=' + prov + '&verbalize=' + (vb || picked('answer') || 'own'));
|
| 115 |
-
const set = (k, detail, ms) => { const r = document.getElementById(`r${id}-${k}`); if(!r) return; r.classList.remove('pending');
|
| 116 |
-
document.getElementById(`d${id}-${k}`).textContent = detail; document.getElementById(`m${id}-${k}`).textContent = ms==null?'':(ms + ' ms'); };
|
| 117 |
-
const live = (k) => { const r = document.getElementById(`r${id}-${k}`); if(r){ document.getElementById(`d${id}-${k}`).textContent = 'working…'; } };
|
| 118 |
-
live('search');
|
| 119 |
-
es.onmessage = (e) => {
|
| 120 |
-
const ev = JSON.parse(e.data);
|
| 121 |
-
if (ev.stage === 'search'){ const sp = ev.spelled ? `; read as ${Object.entries(ev.spelled).map(([a,b]) => `“${b}” for “${a}”`).join(', ')}` : ''; set('search', `${ev.n} result${ev.n===1?'':'s'}${ev.cached?' (cached)':''}${sp}`, ev.ms); live('rank'); }
|
| 122 |
-
else if (ev.stage === 'rank'){ set('rank', `${ev.n} candidate sentences, top 8 kept`, ev.ms); live('verify'); }
|
| 123 |
-
else if (ev.stage === 'verify'){ set('verify', `score ${ev.score} (${ev.tier===1?'verified':ev.tier===2?'best match, unverified':'below threshold'})`, ev.ms); live('extract'); }
|
| 124 |
-
else if (ev.stage === 'extract'){ set('extract', (ev.span ? `“${ev.span}”` : 'no short answer') + (ev.span && ev.support ? `, stated by ${ev.support} of the sources` : ''), ev.ms); live('check'); }
|
| 125 |
-
else if (ev.stage === 'retry'){ const tr = document.createElement('tr'); tr.className = ev.taken ? '' : 'stage-live'; tr.innerHTML = `<th>Search again</th><td>${esc(ev.query)} — ${ev.n} new sentences, score ${ev.score}${ev.taken ? ', verified' : ', not certified'}</td><td class="num">${ev.ms} ms</td>`; const chk = document.getElementById(`r${id}-check`); chk.parentNode.insertBefore(tr, chk); }
|
| 126 |
-
else if (ev.stage === 'sieve'){ const tr = document.createElement('tr'); tr.className = ev.taken ? '' : 'stage-live'; tr.innerHTML = `<th>Sieve</th><td>${ev.error ? 'failed' : `candidates named in the results: “${esc(ev.entity)}” covers ${ev.covered} of ${ev.of} constraint words${ev.runner ? `, next “${esc(ev.runner)}”` : ''}${ev.taken ? '' : '; not decisive'}`}</td><td class="num">${ev.ms} ms</td>`; const chk = document.getElementById(`r${id}-check`); chk.parentNode.insertBefore(tr, chk); }
|
| 127 |
-
else if (ev.stage === 'check'){ const by = {verbaliser: 'answer line written by our 113M verbaliser' + (ev.verbaliser_v==null ? '' : ` (verifier ${ev.verbaliser_v})`), decoder: 'lead line written by our 113M decoder', planner: 'lead line from our 113M planner\'s frame', template: 'lead line from a template'}[ev.lead_by]; const rej = ev.verbaliser && ev.lead_by !== 'verbaliser' ? ` (verbaliser line rejected: “${ev.verbaliser}”)` : ''; set('check', (by || (ev.hhem==null ? 'no lead line' : `support ${ev.hhem}`)) + rej, ev.ms); }
|
| 128 |
-
else if (ev.stage === 'done'){
|
| 129 |
-
es.close(); done();
|
| 130 |
-
const total = Math.round(performance.now() - t0);
|
| 131 |
-
document.getElementById(`mt${id}`).textContent = total + ' ms';
|
| 132 |
-
document.getElementById(`dt${id}`).textContent = ev.ms_models!=null ? `${ev.ms_models} ms of model time, the rest is the search` : '';
|
| 133 |
-
const a = document.getElementById(`a${id}`), refs = document.getElementById(`refs${id}`);
|
| 134 |
-
if (ev.tier === 3 && !ev.cited){
|
| 135 |
-
a.innerHTML = `<span class="none">There were no results matching the query.</span>`;
|
| 136 |
-
['rank','verify','extract','check'].forEach(k => set(k, 'skipped', null)); return;
|
| 137 |
-
}
|
| 138 |
-
const tag = ev.tier === 1 ? '' : ' <span class="tag">[unverified]</span>'; // the models found a best match but would not certify it
|
| 139 |
-
const quote = esc(ev.cited);
|
| 140 |
-
let lead;
|
| 141 |
-
if (ev.span && ev.tier === 1){
|
| 142 |
-
const i = ev.cited.indexOf(ev.span);
|
| 143 |
-
lead = i >= 0 ? esc(ev.cited.slice(0,i)) + '<b>' + esc(ev.span) + '</b>' + esc(ev.cited.slice(i + ev.span.length)) : '<b>' + esc(ev.span) + '</b> — ' + quote;
|
| 144 |
-
} else { lead = quote; }
|
| 145 |
-
const witness = (ev.span && ev.support >= 2) ? ` <span class="muted">(stated by ${ev.support} sources${ev.verified_by === 'agreement' ? ', verified by their agreement' : ''})</span>` : '';
|
| 146 |
-
// the statement comes first when our own models wrote it (or when the quote is not a clean answer by itself); the quote is the evidence beneath it
|
| 147 |
-
const showLead = ev.lead && ev.tier === 1 && (ev.lead_by === 'verbaliser' || ev.lead_by === 'decoder' || ev.lead_by === 'planner' || !ev.quote_clean);
|
| 148 |
-
if (showLead){
|
| 149 |
-
a.innerHTML = `${md(ev.lead, id)}<br><span class="evidence">${quote}<sup class="ref"><a href="#ref${id}-1">[1]</a></sup>${witness}</span>`;
|
| 150 |
-
} else {
|
| 151 |
-
a.innerHTML = `${lead}<sup class="ref"><a href="#ref${id}-1">[1]</a></sup>${tag}${witness}`;
|
| 152 |
-
}
|
| 153 |
-
refs.innerHTML = `<h3>References</h3><ol class="refs"><li id="ref${id}-1"><a href="${esc(ev.url)}" target="_blank" rel="noopener">${esc(ev.title || ev.url)}</a> <span class="url">${esc(ev.url)}</span></li></ol>`;
|
| 154 |
-
}
|
| 155 |
-
};
|
| 156 |
-
es.onerror = () => { es.close(); done(); const a = document.getElementById(`a${id}`); if (a && a.querySelector('.none')) a.innerHTML = '<span class="none">The local server stopped answering. Start it again with local/webui.sh start.</span>'; };
|
| 157 |
-
}
|
| 158 |
-
function ask(text){
|
| 159 |
-
n += 1; const base = n;
|
| 160 |
-
const eng = picked('engine') || 'ddgs', vb = picked('answer') || 'own', cmp = picked('compare') || 'off';
|
| 161 |
-
const LEADNAME = {own: 'our 113M model writes the answer line', template: 'template answer line', none: 'quote only'};
|
| 162 |
-
let cols = [{prov: eng, vb, label: ''}];
|
| 163 |
-
if (cmp === 'engines') cols = [{prov: 'ddgs', vb, label: NAMES.ddgs}, {prov: 'serper', vb, label: NAMES.serper}];
|
| 164 |
-
if (cmp === 'answer') cols = [{prov: eng, vb: 'own', label: LEADNAME.own}, {prov: eng, vb: 'none', label: LEADNAME.none}];
|
| 165 |
-
const art = document.createElement('article');
|
| 166 |
-
art.innerHTML = `<h2>${esc(text)}</h2>` + (cols.length > 1 ? `<div class="cols">${cols.map((c, i) => `<div><h3 class="prov">${esc(c.label)}</h3>` + block(`${base}-${i}`, c.prov) + `</div>`).join('')}</div>` : block(`${base}-0`, cols[0].prov));
|
| 167 |
-
log.appendChild(art); art.scrollIntoView({block:'end'});
|
| 168 |
-
go.disabled = true; let pending = cols.length;
|
| 169 |
-
const done = () => { pending -= 1; if (pending <= 0){ go.disabled = false; q.focus(); } };
|
| 170 |
-
// the server answers one question at a time, so the second column's stages start when the first finishes
|
| 171 |
-
cols.forEach((c, i) => run(`${base}-${i}`, text, c.prov, done, c.vb));
|
| 172 |
-
}
|
| 173 |
-
form.addEventListener('submit', (e) => { e.preventDefault(); const t = q.value.trim(); if (!t || go.disabled) return; q.value = ''; ask(t); });
|
| 174 |
-
})();
|
| 175 |
-
</script>
|
| 176 |
-
</body>
|
| 177 |
-
</html>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
moss.sh
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
#!/usr/bin/env bash
|
| 2 |
-
# RysoAI TinyQA-1 Moss:
|
| 3 |
# ./moss.sh setup one-off: Python 3.11 venv with CPU torch and the pinned packages (~1 GB download)
|
| 4 |
-
# ./moss.sh start
|
| 5 |
-
# ./moss.sh ask "Who painted the Night Watch?" one answer
|
|
|
|
| 6 |
# ./moss.sh index ~/Documents/notes index a folder of .txt/.md files (or a .jsonl of {"title","text"}) for offline use
|
| 7 |
# ./moss.sh ask --local "What is the boiling point of water at altitude?" answer from the indexed files, no network
|
| 8 |
# ./moss.sh stop | status
|
|
@@ -10,7 +11,7 @@
|
|
| 10 |
set -uo pipefail
|
| 11 |
ROOT=$(cd "$(dirname "$0")" && pwd); CODE="$ROOT/code"; PY="$ROOT/.venv/bin/python"; PORT=${MOSS_PORT:-8091}; URL="http://127.0.0.1:$PORT"
|
| 12 |
LOGS="$CODE/local/data"; mkdir -p "$LOGS"
|
| 13 |
-
stop_all() { pkill -f "
|
| 14 |
case "${1:-start}" in
|
| 15 |
setup)
|
| 16 |
command -v python3.11 >/dev/null || { echo "needs Python 3.11 (macOS: brew install python@3.11)"; exit 1; }
|
|
@@ -31,26 +32,19 @@ case "${1:-start}" in
|
|
| 31 |
(nohup llama-server -m "$ROOT/gguf/gse-planner-120m-v2-Q8_0.gguf" -c 1024 --port 8093 -t 4 --special > "$LOGS/planner.log" 2>&1 &)
|
| 32 |
(nohup llama-server -m "$ROOT/gguf/gse-verbaliser-120m-short-Q8_0.gguf" -c 1024 --port 8095 -t 4 --special > "$LOGS/verbaliser.log" 2>&1 &)
|
| 33 |
else export GSE_VERBALIZE=template; echo "llama-server not found: the answer line comes from a template"; fi
|
| 34 |
-
(cd "$CODE" && nohup "$PY" local/
|
| 35 |
-
for i in $(seq 1 180); do curl -s -m 1 "$URL/health" | grep -q '"models": true' && { echo "ready:
|
| 36 |
-
echo "did not start; see $LOGS/
|
| 37 |
index)
|
| 38 |
[ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
|
| 39 |
src=${2:?usage: ./moss.sh index <folder-or-jsonl>}; src=$(cd "$(dirname "$src")" && pwd)/$(basename "$src")
|
| 40 |
(cd "$CODE/local" && "$PY" -c 'import sys, webqa; print(f"indexed {webqa.index_corpus(sys.argv[1]):,} passages from {sys.argv[1]}")' "$src" 2>&1 | grep -v -i warning)
|
| 41 |
-
echo "
|
| 42 |
stop) stop_all; echo stopped;;
|
| 43 |
-
status) curl -s -m 1 "$URL/health" || echo "not running";
|
| 44 |
ask)
|
| 45 |
curl -s -m 1 "$URL/health" | grep -q '"models": true' || { echo "not running: ./moss.sh start first"; exit 1; }
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
import sys, json; d = json.loads(sys.stdin.read()[6:])
|
| 50 |
-
if d.get("tier") == 1:
|
| 51 |
-
if d.get("lead"): print(d["lead"].replace("**", ""))
|
| 52 |
-
print(" \u201c" + d["cited"] + "\u201d" + (" (stated by %d sources)" % d["support"] if (d.get("support") or 0) >= 2 else ""))
|
| 53 |
-
print(" " + str(d.get("url")))
|
| 54 |
-
else: print("No verified answer. The page shows the closest sentences it found, unchecked.")' ;;
|
| 55 |
-
*) sed -n 2,8p "$0";;
|
| 56 |
esac
|
|
|
|
| 1 |
#!/usr/bin/env bash
|
| 2 |
+
# RysoAI TinyQA-1 Moss: load the models in the background, then ask questions from the terminal.
|
| 3 |
# ./moss.sh setup one-off: Python 3.11 venv with CPU torch and the pinned packages (~1 GB download)
|
| 4 |
+
# ./moss.sh start load the models in the background (DuckDuckGo search, no keys needed)
|
| 5 |
+
# ./moss.sh ask "Who painted the Night Watch?" one answer (needs ./moss.sh start)
|
| 6 |
+
# ./moss.sh ask type questions one after another; add --local to answer from the index
|
| 7 |
# ./moss.sh index ~/Documents/notes index a folder of .txt/.md files (or a .jsonl of {"title","text"}) for offline use
|
| 8 |
# ./moss.sh ask --local "What is the boiling point of water at altitude?" answer from the indexed files, no network
|
| 9 |
# ./moss.sh stop | status
|
|
|
|
| 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; }
|
|
|
|
| 32 |
(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 &)
|
| 33 |
(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 &)
|
| 34 |
else export GSE_VERBALIZE=template; echo "llama-server not found: the answer line comes from a template"; fi
|
| 35 |
+
(cd "$CODE" && nohup "$PY" local/moss_server.py --port "$PORT" > "$LOGS/moss.log" 2>&1 &)
|
| 36 |
+
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
|
| 37 |
+
echo "did not start; see $LOGS/moss.log"; exit 1;;
|
| 38 |
index)
|
| 39 |
[ -x "$PY" ] || { echo "run ./moss.sh setup first"; exit 1; }
|
| 40 |
src=${2:?usage: ./moss.sh index <folder-or-jsonl>}; src=$(cd "$(dirname "$src")" && pwd)/$(basename "$src")
|
| 41 |
(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)
|
| 42 |
+
echo "ready to use: ./moss.sh ask --local \"your question\"";;
|
| 43 |
stop) stop_all; echo stopped;;
|
| 44 |
+
status) curl -s -m 1 "$URL/health" | grep -q '"models": true' && echo running || echo "not running";;
|
| 45 |
ask)
|
| 46 |
curl -s -m 1 "$URL/health" | grep -q '"models": true' || { echo "not running: ./moss.sh start first"; exit 1; }
|
| 47 |
+
[ -f "$ROOT/.env" ] && set -a && . "$ROOT/.env" && set +a
|
| 48 |
+
shift; MOSS_PROVIDER=$([ -n "${SERPER_API_KEY:-}" ] && echo serper || echo ddgs) "$PY" "$CODE/local/moss_cli.py" "$URL" "$@";;
|
| 49 |
+
*) sed -n 2,9p "$0";;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
esac
|