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
Download code/tinyqa/pipeline.py from RysoAI/tinyqa-1-moss: direct link, hf CLI and curl.
- Browser
- Download file 36.6 kB
-
https://huggingface.co/RysoAI/tinyqa-1-moss/resolve/main/code/tinyqa/pipeline.py
- Command line
-
hf download hf://RysoAI/tinyqa-1-moss/code/tinyqa/pipeline.py
-
curl -L -o pipeline.py https://huggingface.co/RysoAI/tinyqa-1-moss/resolve/main/code/tinyqa/pipeline.py
36.6 kB
| import collections, json, os, random, re, string, sys, time | |
| from concurrent.futures import ThreadPoolExecutor | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| BK = os.environ.get('MOSS_HOME', os.path.dirname(os.path.dirname(HERE))) | |
| DATA = os.environ.get('MOSS_DATA', os.path.join(BK, 'data')) | |
| os.makedirs(DATA, exist_ok=True) | |
| CACHE = os.environ.get('MOSS_WEBQA_CACHE', os.path.join(DATA, 'webqa_cache.json')) | |
| def normalize(s): | |
| s = s.lower() | |
| s = ''.join((ch for ch in s if ch not in set(string.punctuation))) | |
| s = re.sub('\\b(a|an|the)\\b', ' ', s) | |
| return ' '.join(s.split()) | |
| def contains(text, answers): | |
| t = normalize(text) | |
| return any((normalize(a) and normalize(a) in t for a in answers)) | |
| CACHE_DDGS = os.path.join(DATA, 'webqa_cache.json') | |
| CACHE_SERPER = os.path.join(DATA, 'webqa_cache_serper.json') | |
| _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 {}} | |
| def default_provider(): | |
| return os.environ.get('MOSS_SEARCH') or 'ddgs' | |
| def _merge_save(path, mem): | |
| import fcntl | |
| with open(path, 'a+') as f: | |
| fcntl.flock(f, fcntl.LOCK_EX) | |
| f.seek(0) | |
| try: | |
| disk = json.load(f) | |
| except Exception: | |
| disk = {} | |
| disk.update(mem) | |
| mem.update(disk) | |
| f.seek(0) | |
| f.truncate() | |
| json.dump(disk, f) | |
| fcntl.flock(f, fcntl.LOCK_UN) | |
| def save_caches(): | |
| _merge_save(CACHE_DDGS, _caches['ddgs']) | |
| _merge_save(CACHE_SERPER, _caches['serper']) | |
| if 'searxng' in _caches: | |
| _merge_save(os.path.join(DATA, 'webqa_cache_searxng.json'), _caches['searxng']) | |
| _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 {} | |
| _cache = _caches[default_provider()] | |
| SERPER_LEDGER = os.path.join(DATA, 'serper_calls.json') | |
| import threading | |
| _LEDGER_LOCK = threading.Lock() | |
| def _count_serper(): | |
| import fcntl | |
| with _LEDGER_LOCK, open(SERPER_LEDGER, 'a+') as f: | |
| fcntl.flock(f, fcntl.LOCK_EX) | |
| f.seek(0) | |
| try: | |
| d = json.load(f) | |
| except Exception: | |
| d = {'calls': 0} | |
| 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) | |
| def search_serper(q, k=10): | |
| import urllib.request | |
| for attempt in range(3): | |
| try: | |
| return _search_serper_once(q, k) | |
| except Exception as ex: | |
| if '429' not in str(ex) or attempt == 2: | |
| raise | |
| time.sleep(3 + 4 * attempt) | |
| def _search_serper_once(q, k=10): | |
| import urllib.request | |
| _count_serper() | |
| 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'}) | |
| with urllib.request.urlopen(req, timeout=20) as r: | |
| d = json.load(r) | |
| out = [] | |
| ab = d.get('answerBox') or {} | |
| if ab.get('answer') or ab.get('snippet'): | |
| 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', '')}) | |
| kg = d.get('knowledgeGraph') or {} | |
| if kg.get('description'): | |
| 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', '')}) | |
| for x in d.get('organic', [])[:k]: | |
| out.append({'title': x.get('title', ''), 'body': x.get('snippet', ''), 'href': x.get('link', '')}) | |
| return out | |
| def search_searxng(q, k=10): | |
| import urllib.request, urllib.parse | |
| url = os.environ['SEARXNG_URL'].rstrip('/') + '/search?' + urllib.parse.urlencode({'q': q, 'format': 'json', 'language': 'en', 'safesearch': 0}) | |
| with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'moss/0.1'}), timeout=25) as r: | |
| d = json.load(r) | |
| out = [] | |
| for a in d.get('answers', [])[:2]: | |
| out.append({'title': 'Answer', 'body': a if isinstance(a, str) else str(a.get('answer', a)), 'href': ''}) | |
| for x in d.get('results', [])[:k]: | |
| out.append({'title': x.get('title', ''), 'body': x.get('content', ''), 'href': x.get('url', '')}) | |
| return out | |
| LOCAL_DB = os.environ.get('MOSS_CORPUS_DB', os.path.join(DATA, 'corpus.sqlite')) | |
| def _passages(text, size=420): | |
| for para in re.split('\\n\\s*\\n', text): | |
| para = ' '.join(para.split()) | |
| if not para or para.startswith('#'): | |
| continue | |
| cur = '' | |
| for sent in _SENT.split(para): | |
| if cur and len(cur) + len(sent) > size: | |
| yield cur | |
| cur = '' | |
| cur = (cur + ' ' + sent).strip() | |
| if cur: | |
| yield cur | |
| def index_corpus(src, db=LOCAL_DB): | |
| import sqlite3 | |
| os.makedirs(os.path.dirname(os.path.abspath(db)), exist_ok=True) | |
| if os.path.exists(db): | |
| os.remove(db) | |
| con = sqlite3.connect(db) | |
| con.execute("CREATE VIRTUAL TABLE p USING fts5(title, body, href UNINDEXED, tokenize='porter unicode61')") | |
| def docs(): | |
| if os.path.isfile(src) and src.endswith('.jsonl'): | |
| for i, line in enumerate(open(src, encoding='utf-8', errors='ignore')): | |
| 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}') | |
| return | |
| for root, _, files in os.walk(src): | |
| for fn in sorted(files): | |
| if not fn.lower().endswith(('.txt', '.md', '.markdown')): | |
| continue | |
| path = os.path.join(root, fn) | |
| text = open(path, encoding='utf-8', errors='ignore').read() | |
| m = re.search('^#\\s+(.+)$', text, re.M) | |
| title = m.group(1).strip() if m else os.path.splitext(fn)[0].replace('_', ' ').replace('-', ' ') | |
| yield (title, text, 'file://' + os.path.abspath(path)) | |
| n = 0 | |
| for title, text, href in docs(): | |
| rows = [(title, ps, href) for ps in _passages(text)] | |
| con.executemany('INSERT INTO p VALUES (?, ?, ?)', rows) | |
| n += len(rows) | |
| con.commit() | |
| con.close() | |
| return n | |
| def search_local(q, k=10, db=LOCAL_DB): | |
| import sqlite3 | |
| if not os.path.exists(db): | |
| return [] | |
| terms = [t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QSTOP and len(t) > 1] | |
| if not terms: | |
| return [] | |
| con = sqlite3.connect(db) | |
| 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() | |
| finally: | |
| con.close() | |
| return [{'title': t, 'body': b, 'href': h} for t, b, h in rows] | |
| def search(q, k=10, provider=None): | |
| provider = provider or default_provider() | |
| if provider == 'local': | |
| return search_local(q, k) | |
| if provider == 'serper' and (not os.environ.get('SERPER_API_KEY')): | |
| provider = 'ddgs' | |
| if provider == 'searxng' and (not os.environ.get('SEARXNG_URL')): | |
| provider = 'ddgs' | |
| c = _caches[provider] | |
| if provider == 'searxng': | |
| if q in c: | |
| return c[q] | |
| try: | |
| r = search_searxng(q, k) | |
| res = [{'title': clean_title(x['title']), 'body': clean_body(x['body']), 'href': x['href']} for x in r] | |
| if res: | |
| c[q] = res | |
| return res | |
| except Exception as ex: | |
| print(f'[webqa] searxng failed ({type(ex).__name__}); falling back to DuckDuckGo', flush=True) | |
| c = _caches['ddgs'] | |
| if q in c: | |
| return c[q] | |
| if q in c: | |
| return c[q] | |
| if provider == 'serper': | |
| try: | |
| r = search_serper(q, k) | |
| res = [{'title': clean_title(x['title']), 'body': clean_body(x['body']), 'href': x['href']} for x in r] | |
| if res: | |
| c[q] = res | |
| return res | |
| except Exception as ex: | |
| print(f'[webqa] serper failed ({type(ex).__name__}); falling back to DuckDuckGo', flush=True) | |
| c = _caches['ddgs'] | |
| if q in c: | |
| return c[q] | |
| from ddgs import DDGS | |
| r = [] | |
| for attempt, backend in enumerate(('auto', 'google', 'bing', 'auto')): | |
| try: | |
| r = DDGS().text(q, max_results=k, backend=backend) or [] | |
| if r: | |
| break | |
| except Exception as ex: | |
| r = [] | |
| time.sleep(1.5 + 2 * attempt) | |
| res = [{'title': clean_title(x.get('title', '')), 'body': clean_body(x.get('body', '')), 'href': x.get('href', '')} for x in r] | |
| if res: | |
| c[q] = res | |
| return res | |
| _SENT = re.compile('(?<=[.!?])\\s+(?=[A-Z0-9\\"\'(])') | |
| _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*') | |
| def clean_title(t): | |
| t = re.sub('([a-z]{4,})([A-Z][a-z]{2,})', '\\1 | \\2', t.strip()) | |
| t = re.split('\\s+\\|\\s+', t.strip())[0] | |
| return t[:110].rstrip() | |
| def clean_body(b): | |
| return _DATE.sub('', b.strip()) | |
| STRICT = os.environ.get('MOSS_STRICT') == '1' | |
| 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] | |
| PAGES = int(os.environ.get('MOSS_PAGES', '0')) | |
| PAGE_DIR = os.path.join(DATA, 'pages') | |
| os.makedirs(PAGE_DIR, exist_ok=True) | |
| _UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36' | |
| def fetch_text(url, timeout=12): | |
| import hashlib, urllib.request, socket | |
| socket.setdefaulttimeout(timeout) | |
| p = os.path.join(PAGE_DIR, hashlib.sha1(url.encode()).hexdigest() + '.txt') | |
| if os.path.exists(p): | |
| return open(p).read() | |
| txt = '' | |
| try: | |
| import trafilatura | |
| req = urllib.request.Request(url, headers={'User-Agent': _UA, 'Accept-Language': 'en'}) | |
| html = urllib.request.urlopen(req, timeout=timeout).read(2000000).decode('utf-8', 'ignore') | |
| txt = trafilatura.extract(html, include_comments=False, include_tables=True) or '' | |
| except Exception: | |
| txt = '' | |
| open(p, 'w').write(txt) | |
| return txt | |
| def page_candidates(q, results, n_pages, cap=150): | |
| qt = {t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QWORDS and len(t) > 2} | |
| out = [] | |
| for r in results[:n_pages]: | |
| if not r.get('href') or any((b in r['href'].lower() for b in BLOCK)): | |
| continue | |
| txt = fetch_text(r['href']) | |
| for s in _SENT.split(' '.join(txt.split())): | |
| s = s.strip() | |
| if 25 <= len(s) <= 400 and len(qt & set(re.findall('[a-z0-9]+', s.lower()))) >= max(1, min(2, len(qt) // 3)): | |
| out.append({'sent': s, 'title': r['title'], 'url': r['href'], 'body': s, 'from_page': True}) | |
| if len(out) > cap: | |
| out.sort(key=lambda c: -len(qt & set(re.findall('[a-z0-9]+', c['sent'].lower())))) | |
| out = out[:cap] | |
| return out | |
| PROSE = os.environ.get('MOSS_PROSE', '1') == '1' | |
| SOURCE_PENALTY = os.environ.get('MOSS_SOURCE_PENALTY', '0') == '1' | |
| QUOTABLE = os.environ.get('MOSS_QUOTABLE', '0') == '1' | |
| SOCIAL = ('reddit.com', 'quora.com', 'facebook.com', 'instagram.com', 'tiktok.com', 'pinterest.', 'youtube.com', 'answers.com', 'brainly.', 'quizlet', 'x.com/', 'twitter.com') | |
| _ROW = re.compile('^\\s*\\d+[.,)]\\s') | |
| def is_prose(s): | |
| if len(re.findall('[A-Za-z]{3,}', s)) < 4 or _ROW.match(s) or '|' in s or (s.count('·') >= 2): | |
| return False | |
| if ';' in s and len(s.split()) < 10: | |
| return False | |
| words = s.split() | |
| if s.count(' – ') + s.count(' — ') >= 4: | |
| return False | |
| 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 | |
| return sum((1 for ch in s if ch.isdigit() or ch in ',;·|')) / max(1, len(s)) <= 0.25 | |
| CUTS = os.environ.get('MOSS_CUTS', '1') == '1' | |
| _GLUE = re.compile('(?<=[a-z0-9][.!?])(?=[A-Z][a-z])|\\s*(?:\\.\\.\\.|…)\\s*') | |
| def cuts(s): | |
| parts = [p.strip(' ,;:') for p in _GLUE.split(s)] | |
| parts = [p for p in parts if len(p) > 15] | |
| return parts if len(parts) > 1 else [] | |
| _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*)?') | |
| def candidates(results, q=None): | |
| out = [] | |
| if PAGES and q: | |
| out += page_candidates(q, results, PAGES) | |
| for r in results: | |
| if any((b in (r.get('href', '') + ' ' + r.get('title', '')).lower() for b in BLOCK)): | |
| continue | |
| for s in _SENT.split(re.sub('\\s*\\[\\d{1,3}\\]', '', r['body']).strip()): | |
| s = _BOILER.sub('', s.strip()).strip() | |
| for t in [s] + (cuts(s) if CUTS else []): | |
| 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']}) | |
| return out | |
| def _cap(t): | |
| return t[:1].upper() + t[1:] | |
| _PAST = {'end': 'ended', 'begin': 'began', 'start': 'started', 'happen': 'happened', 'die': 'died', 'occur': 'occurred', 'open': 'opened', 'close': 'closed', 'finish': 'finished', 'take place': 'took place'} | |
| def lead(q, span): | |
| s = re.sub('\\s+', ' ', q.strip().rstrip('?').strip()) | |
| b = f'**{span}**' | |
| prep = '' if re.match('^(?:between|from|in|on|at|during|around|about|circa|since|after|before)\\b', span, re.I) else 'in ' | |
| m = re.match('^who (was|is|were|are) (.+)$', s, re.I) | |
| if m: | |
| return f'{_cap(m.group(2))} {m.group(1).lower()} {b}.' | |
| m = re.match('^who (founded|created|invented|wrote|directed|discovered|built|designed|painted|composed|developed|produced|started|established|won|scored) (.+)$', s, re.I) | |
| if m: | |
| return f'{_cap(m.group(2))} was {m.group(1).lower()} by {b}.' | |
| m = re.match('^(what|which) (is|was|are|were) (.+)$', s, re.I) | |
| if m: | |
| return f'{_cap(m.group(3))} {m.group(2).lower()} {b}.' | |
| m = re.match('^where (is|was|are|were) (.+?)(?: located| based| situated)?$', s, re.I) | |
| if m: | |
| return f'{_cap(m.group(2))} {m.group(1).lower()} {prep}{b}.' | |
| 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) | |
| if m: | |
| return f'{_cap(m.group(2))} {m.group(1).lower()} {m.group(3).lower()} {prep}{b}.' | |
| m = re.match('^when did (.+?) (end|begin|start|happen|die|occur|open|close|take place|finish)$', s, re.I) | |
| if m: | |
| return f'{_cap(m.group(1))} {_PAST[m.group(2).lower()]} {prep}{b}.' | |
| return None | |
| 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'} | |
| VERBALIZE = os.environ.get('MOSS_VERBALIZE', 'template') | |
| DECODER_URL = os.environ.get('MOSS_DECODER', 'http://127.0.0.1:8089') | |
| PLANNER_URL = os.environ.get('MOSS_PLANNER', 'http://127.0.0.1:8093') | |
| VERBALISER_URL = os.environ.get('MOSS_VERBALISER', '') | |
| VERB_TAU = float(os.environ.get('MOSS_VERB_TAU', '0.0')) | |
| VERB_SPAN = os.environ.get('MOSS_VERB_SPAN', '0') == '1' | |
| _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'} | |
| def _wordsl(t): | |
| return re.findall('[a-z0-9]+', t.lower()) | |
| def _post_json(url, body, timeout=20): | |
| import urllib.request | |
| req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={'Content-Type': 'application/json'}) | |
| with urllib.request.urlopen(req, timeout=timeout) as r: | |
| return json.loads(r.read()) | |
| def _tidy_lead(t): | |
| t = re.sub('\\s+', ' ', t).strip().rstrip('.').strip() | |
| return t[:1].upper() + t[1:] + '.' if t else t | |
| def own_lead(q, span, cited, title, natural=True, vscore=None, info=None, q_user=None): | |
| import collections | |
| qc = collections.Counter(_wordsl(q)) | |
| sw = set(_wordsl(span)) | |
| ew = set(_wordsl(cited)) | set(_wordsl(title)) if natural else set() | |
| for w, n in collections.Counter(_wordsl(q_user or '')).items(): | |
| qc[w] = max(qc[w], n) | |
| def content_free(text): | |
| cc = collections.Counter((w for w in _wordsl(text) if w not in _FUNC and w not in sw)) | |
| return all((w in qc and cc[w] <= qc[w] or w in ew for w in cc)) | |
| if VERBALISER_URL and natural: | |
| try: | |
| vp = f'<|evidence|>\n[E1] ({title}) {cited}\n<|question|> {q.strip()}\n' + (f'<|span|> {span.strip()}\n' if VERB_SPAN else '') + '<|answer|>' | |
| d = _post_json(f'{VERBALISER_URL}/completion', {'prompt': vp, 'n_predict': 64, 'temperature': 0.0, 'stop': ['<|end|>'], 'cache_prompt': False}, timeout=10) | |
| t = re.sub('\\s+', ' ', d.get('content', '').split('<|end|>')[0]).strip() | |
| v = None | |
| ok = t and t != '<abstain>' and (3 <= len(t.split()) <= 45) and (normalize(span) in normalize(t)) and content_free(t) | |
| if ok and vscore is not None: | |
| v = float(vscore(t)) | |
| ok = v >= VERB_TAU | |
| if info is not None: | |
| info.update({'verbaliser': t or None, 'verbaliser_v': None if v is None else round(v, 2)}) | |
| if ok: | |
| i = t.lower().find(span.lower()) | |
| t = t[:i] + f'**{t[i:i + len(span)]}**' + t[i + len(span):] if i >= 0 else t | |
| return (_tidy_lead(t), 'verbaliser') | |
| except Exception: | |
| pass | |
| try: | |
| g = gbnf(1, allowed=[1]).replace('root ::= "<abstain>" | answer', 'root ::= answer') | |
| 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) | |
| parts, abst = parse_answer(d.get('content', '')) | |
| if not abst and sum((1 for k, _ in parts if k == 'ref')) == 1: | |
| glue = ' '.join((v for k, v in parts if k == 'glue')) | |
| inserted = normalize(span) not in normalize(glue) | |
| 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 | |
| else: | |
| t = ''.join((f'**{span}**' if k == 'ref' else v for k, v in parts)) | |
| dup = bool((set(_wordsl(glue)) & sw) - (set(qc) if natural else set())) and (inserted or not natural) | |
| if content_free(glue) and (not dup) and (3 <= len(t.split()) <= 30): | |
| return (_tidy_lead(t), 'decoder') | |
| except Exception: | |
| pass | |
| try: | |
| 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) | |
| m = re.search('"hypothetical"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"', d.get('content', '')) | |
| hyp = json.loads('"' + m.group(1) + '"') if m else '' | |
| if hyp.count('____') == 1 and content_free(hyp.replace('____', ' ')) and (3 <= len(hyp.split()) <= 30): | |
| return (_tidy_lead(hyp.replace('____', f'**{span}**')), 'planner') | |
| except Exception: | |
| pass | |
| return (None, None) | |
| def quote_clean(q, sent, span): | |
| if not sent or len(sent) > 230 or sent.rstrip()[-1:] not in '.!?' or ('...' in sent) or ('…' in sent): | |
| return False | |
| if span and normalize(span) not in normalize(sent): | |
| return False | |
| cw = [w for w in re.findall('[a-z0-9]+', q.lower()) if w not in QSTOP and len(w) > 2] | |
| ns = normalize(sent) | |
| return sum((1 for w in cw if w in ns)) >= max(1, len(cw) // 2) | |
| FALLBACK = os.environ.get('MOSS_FALLBACK', '0') == '1' | |
| RETRY_TAU = float(os.environ.get('MOSS_RETRY_TAU', '5.5')) | |
| PLANNER_RETRY = os.environ.get('MOSS_PLANNER_RETRY', '0') == '1' | |
| RETRY_PROVIDER = os.environ.get('MOSS_RETRY_PROVIDER', 'serper') | |
| AGREE = int(os.environ.get('MOSS_AGREE', '3')) | |
| SIEVE_RETRY = os.environ.get('MOSS_SIEVE_RETRY', '0') == '1' | |
| _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}") | |
| _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'} | |
| _FORUMS = '-site:reddit.com -site:quora.com -site:facebook.com -site:pinterest.com -site:youtube.com -site:answers.com' | |
| def retry_queries(q): | |
| out = [('noforum', f"{q.rstrip('?')} {_FORUMS}")] | |
| ns = [m.strip() for m in _NAMES.findall(q) if m.split()[0] not in _QCAP and len(m) > 2] | |
| if ns: | |
| rest = q | |
| for n in ns: | |
| rest = rest.replace(n, '') | |
| 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) | |
| out.append(('names', ' '.join((f'"{n}"' for n in ns)) + ' ' + re.sub('\\s+', ' ', rest).strip())) | |
| l = lead(q, '') | |
| if l: | |
| l = l.replace(' ****.', '').replace('****.', '').strip().rstrip('.') | |
| if 3 <= len(l.split()) <= 12: | |
| out.append(('stub', f'"{l}"')) | |
| if PLANNER_RETRY: | |
| try: | |
| 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) | |
| txt = d.get('content', '') | |
| m = re.search('"hypothetical"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"', txt) | |
| hyp = json.loads('"' + m.group(1) + '"') if m else '' | |
| terms = re.findall('"([^"]{2,40})"', txt.split('"search_terms"')[1].split(']')[0]) if '"search_terms"' in txt else [] | |
| ents = re.findall('"([^"]{2,40})"', txt.split('"entities"')[1].split(']')[0]) if '"entities"' in txt else [] | |
| tq = ' '.join(dict.fromkeys(ents + terms)) | |
| if len(tq.split()) >= 2: | |
| out.append(('plan_terms', tq[:160])) | |
| h = re.sub('\\s+', ' ', hyp.replace('____', ' ')).strip(' .') | |
| import collections as _c | |
| qc = _c.Counter(_wordsl(q)) | |
| hc = _c.Counter((w for w in _wordsl(h) if w not in _FUNC)) | |
| 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}"')) | |
| except Exception: | |
| pass | |
| return out | |
| SPELL = os.environ.get('MOSS_SPELL', '1') == '1' | |
| TAU_V = float(os.environ.get('MOSS_TAU_V', '3.0')) | |
| def _lev(a, b): | |
| if abs(len(a) - len(b)) > 3: | |
| return 9 | |
| d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] | |
| for i in range(len(a) + 1): | |
| d[i][0] = i | |
| for j in range(len(b) + 1): | |
| d[0][j] = j | |
| for i in range(1, len(a) + 1): | |
| for j in range(1, len(b) + 1): | |
| 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) | |
| 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) | |
| return d[-1][-1] | |
| def corpus_spelling(q, results): | |
| import collections | |
| vocab = collections.Counter() | |
| for r in results: | |
| for w in set(re.findall('[a-z]{4,}', (r.get('title', '') + ' ' + r.get('body', '')).lower())): | |
| vocab[w] += 1 | |
| fixes = {} | |
| for w in re.findall('\\b[a-z]{5,}\\b', q): | |
| if w in vocab or w in QSTOP or w in _FUNC: | |
| continue | |
| 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) | |
| if best and 0 < best[0] <= (3 if len(w) >= 8 else 2): | |
| fixes[w] = best[2] | |
| out = q | |
| for w, v in fixes.items(): | |
| out = re.sub('\\b' + re.escape(w) + '\\b', v, out) | |
| return (out, fixes) | |
| 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()) | |
| MAX_EVIDENCE = 16 | |
| REF_TOKENS = [f'<q E{i}>' for i in range(1, MAX_EVIDENCE + 1)] | |
| ABSTAIN = '<abstain>' | |
| BOS_EVIDENCE, BOS_QUESTION, BOS_ANSWER, EOS_ANSWER = ('<|evidence|>', '<|question|>', '<|answer|>', '<|end|>') | |
| def gbnf(n_evidence: int, max_glue_tokens: int=40, allowed: list[int] | None=None) -> str: | |
| ids = allowed or list(range(1, n_evidence + 1)) | |
| refs = ' | '.join((f'"<q E{i}>"' for i in ids)) | |
| return f'root ::= "{ABSTAIN}" | answer\nanswer ::= segment+ glue?\nsegment ::= glue? ref\nref ::= {refs}\nglue ::= [^<]{{1,{max_glue_tokens * 5}}}\n' | |
| REF_RE = re.compile('<q E(\\d+)>') | |
| def parse_answer(text: str) -> tuple[list[tuple[str, str]], bool]: | |
| text = text.split(EOS_ANSWER)[0].strip() | |
| if text.startswith(ABSTAIN): | |
| return ([], True) | |
| parts: list[tuple[str, str]] = [] | |
| pos = 0 | |
| for m in REF_RE.finditer(text): | |
| glue = text[pos:m.start()] | |
| if glue.strip(): | |
| parts.append(('glue', glue)) | |
| parts.append(('ref', f'E{m.group(1)}')) | |
| pos = m.end() | |
| tail = text[pos:] | |
| if tail.strip(): | |
| parts.append(('glue', tail)) | |
| return (parts, False) | |
| class Stack: | |
| def __init__(self): | |
| from sentence_transformers import CrossEncoder | |
| dev = os.environ.get('MOSS_DEVICE', 'cpu') | |
| self.rank = CrossEncoder(os.environ.get('MOSS_RANKER') or os.path.join(BK, 'models', 'ranker'), max_length=256, device=dev) | |
| self.verify = CrossEncoder(os.environ.get('MOSS_VERIFIER') or os.path.join(BK, 'models', 'verifier'), max_length=256, device=dev) | |
| from .extract import extract as _extract | |
| self.extract = _extract | |
| self.hhem = None | |
| if os.environ.get('MOSS_HHEM') == '1': | |
| try: | |
| from transformers import AutoModelForSequenceClassification | |
| self.hhem = AutoModelForSequenceClassification.from_pretrained('vectara/hallucination_evaluation_model', trust_remote_code=True) | |
| except Exception as ex: | |
| print(f'[webqa] HHEM unavailable: {type(ex).__name__}: {str(ex)[:120]}', flush=True) | |
| def _sieve(self): | |
| if not hasattr(self, '_sv'): | |
| from .sieve import Sieve | |
| sv = Sieve.__new__(Sieve) | |
| sv.verify = self.verify | |
| self._sv = sv | |
| return self._sv | |
| def answer_iter(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None): | |
| if tau_v is None: | |
| tau_v = TAU_V | |
| t0 = time.time() | |
| res = search(q, provider=provider) | |
| t1 = time.time() | |
| q_user = q | |
| fixes = {} | |
| if SPELL and res: | |
| q, fixes = corpus_spelling(q, res) | |
| 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} | |
| cands = candidates(res, q) | |
| if not cands: | |
| yield {'stage': 'done', 'tier': 3, 'why': 'no results', 'ms_search': round(1000 * (t1 - t0)), 'ms_models': 0, 'results': res} | |
| return | |
| ta = time.time() | |
| s1 = self.rank.predict([(q, f"{c['title']}. {c['sent']}") for c in cands], batch_size=32, show_progress_bar=False) | |
| order = sorted(range(len(cands)), key=lambda i: -float(s1[i]))[:8] | |
| tb = time.time() | |
| yield {'stage': 'rank', 'ms': round(1000 * (tb - ta)), 'n': len(cands), 'top': [cands[i]['sent'][:90] for i in order[:3]]} | |
| s2 = self.verify.predict([(q, f"{cands[i]['title']}. {cands[i]['sent']}") for i in order], batch_size=32, show_progress_bar=False) | |
| 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 | |
| def quotable(c): | |
| if not QUOTABLE: | |
| return 0.0 | |
| 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) | |
| ver = [j for j in range(len(order)) if float(s2[j]) >= tau_v] | |
| 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])) | |
| c = cands[order[best]] | |
| score2 = float(s2[best]) | |
| tc = time.time() | |
| tier = 1 if score2 >= tau_v else 2 if score2 >= tau_lo else 3 | |
| yield {'stage': 'verify', 'ms': round(1000 * (tc - tb)), 'score': round(score2, 2), 'tier': tier} | |
| retry = None | |
| if FALLBACK and tier != 1: | |
| rprov = RETRY_PROVIDER if RETRY_PROVIDER == 'serper' and os.environ.get('SERPER_API_KEY') else provider | |
| for name, rq in retry_queries(q): | |
| 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}] | |
| if not more: | |
| continue | |
| r1 = self.rank.predict([(q, f"{x['title']}. {x['sent']}") for x in more], batch_size=32, show_progress_bar=False) | |
| ro = sorted(range(len(more)), key=lambda i: -float(r1[i]))[:8] | |
| r2 = self.verify.predict([(q, f"{more[i]['title']}. {more[i]['sent']}") for i in ro], batch_size=32, show_progress_bar=False) | |
| rb = max(range(len(ro)), key=lambda j: float(r2[j]) - pen(more[ro[j]]) + quotable(more[ro[j]])) | |
| rv = float(r2[rb]) | |
| yield {'stage': 'retry', 'ms': round(1000 * (time.time() - tr)), 'query': rq, 'name': name, 'score': round(rv, 2), 'n': len(more), 'taken': rv >= RETRY_TAU} | |
| if rv >= RETRY_TAU: | |
| c = more[ro[rb]] | |
| score2 = rv | |
| tier = 1 | |
| retry = name | |
| res = res + search(rq, provider=rprov) | |
| break | |
| tc = time.time() | |
| span = self.extract(q, [(f"{c['title'].split(' | ')[0].strip()}. {c['body']}", 'E1')], answer_type=None) | |
| if span: | |
| span['answer'] = re.sub('\\b(\\w+)\\1\\b', '\\1', span['answer']).strip() | |
| span['answer'] = re.sub('\\b(\\w+(?:\\s\\w+)?)\\s+\\1\\b', '\\1', span['answer']).strip() | |
| if not span and re.match('^(?:who|which)\\b', q.strip(), re.I): | |
| head = re.split('\\s+[-|—–:]\\s+', c['title'])[0].strip() | |
| if 2 <= len(head.split()) <= 5 and head[:1].isupper(): | |
| span = {'answer': head, 'score': 0.0, 'kind': 'title'} | |
| spans = {} | |
| for j, i in enumerate(order if os.environ.get('MOSS_CONSENSUS') == '1' else []): | |
| cj = cands[i] | |
| sp = self.extract(q, [(f"{cj['title'].split(' | ')[0].strip()}. {cj['body']}", 'E1')], answer_type=None) | |
| if not sp: | |
| continue | |
| key = normalize(re.sub('\\b(\\w+)\\1\\b', '\\1', sp['answer'])) | |
| if not key or len(key) > 80: | |
| continue | |
| e = spans.setdefault(key, {'answer': sp['answer'], 'sources': set(), 'best_v': -99.0, 'cand': None}) | |
| e['best_v'] = max(e['best_v'], float(s2[j])) | |
| e['cand'] = e['cand'] or cj | |
| for key, e in spans.items(): | |
| e['sources'] = {r['href'] for r in res if key in normalize(r['title'] + ' ' + r['body'])} | |
| cons = max(spans.values(), key=lambda e: (len(e['sources']), e['best_v'])) if spans else None | |
| pkey = normalize(span['answer']) if span else '' | |
| 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 | |
| if STRICT and tier == 1 and (support < 2): | |
| tier = 2 | |
| verified_by = 'verifier' if tier == 1 else None | |
| if AGREE and tier != 1 and span and (support >= AGREE) and (score2 >= 0.0): | |
| tier = 1 | |
| verified_by = 'agreement' | |
| sieve_ev = None | |
| if SIEVE_RETRY and tier != 1 and re.match('^(?:which|who)\\b', q.strip(), re.I) and (not span or support <= 1): | |
| try: | |
| ts = time.time() | |
| sv = self._sieve() | |
| out = sv.run(q, provider=rprov if FALLBACK else provider, k_ent=8) or {} | |
| 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)) | |
| 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)} | |
| if ok: | |
| span = {'answer': ent, 'score': 0.0, 'kind': 'sieve'} | |
| pkey = normalize(ent) | |
| 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) | |
| support = len({r.get('href') or r['body'] for r in res if pkey in normalize(r['title'] + ' ' + r['body'])}) + 1 | |
| tier = 1 if score2 >= tau_v else 2 | |
| retry = 'sieve' | |
| verified_by = 'verifier' if tier == 1 else None | |
| except Exception as ex: | |
| sieve_ev = {'stage': 'sieve', 'ms': 0, 'error': type(ex).__name__} | |
| if sieve_ev: | |
| yield sieve_ev | |
| td = time.time() | |
| 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} | |
| hh = None | |
| if self.hhem is not None and span: | |
| try: | |
| hh = float(self.hhem.predict([(c['body'], f"The answer to the question '{q}' is {span['answer']}.")])[0]) | |
| except Exception: | |
| hh = None | |
| ld, ld_by = (None, None) | |
| vmode = verbalize or VERBALIZE | |
| linfo = {} | |
| if span and tier == 1 and (vmode != 'none'): | |
| if vmode in ('own', 'own-strict'): | |
| ttl = c['title'].split(' | ')[0].split(' - ')[0].strip() | |
| 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])) | |
| if not ld: | |
| ld, ld_by = (lead(q, span['answer']), 'template' if lead(q, span['answer']) else None) | |
| 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} | |
| 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} | |
| def answer(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None): | |
| for ev in self.answer_iter(q, tau_v, tau_lo, provider, verbalize): | |
| if ev['stage'] == 'done': | |
| return {k: v for k, v in ev.items() if k != 'stage'} | |