Spaces:
Paused
Paused
baiango commited on
Commit ·
dcfa38b
0
Parent(s):
Embed Compare: rank 627 place-nouns by cosine similarity
Browse filesFiles changed (7)
- .gitignoreAdded+11
- README.mdAdded+73
- app.pyAdded+293
- embed_compare.pyAdded+352
- generic_nouns.txtAdded+642
- precompute_nouns.pyAdded+126
- requirements.txtAdded+7
1234567891011# Local model weights (pulled at build time on the Space)models/*.gguf
# Generated vector cache.embed_cache/
# Python.venv/__pycache__/*.pyc12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273---title: Embed Compareemoji: 🧭colorFrom: indigocolorTo: bluesdk: gradiosdk_version: 6.14.0app_file: app.pypinned: falselicense: mitshort_description: Rank place-nouns by embedding similaritymodels: - mradermacher/Octen-Embedding-0.6B-GGUFpreload_from_hub: - mradermacher/Octen-Embedding-0.6B-GGUF Octen-Embedding-0.6B.Q4_K_M.gguf---
# Embed Compare
Rank a fixed vocabulary of **627 generic place-nouns** by cosine similarity to anytext you type in — a demo for [`embed_compare.py`](./embed_compare.py).
Everything runs from a single GGUF file on CPU: `Octen-Embedding-0.6B.Q4_K_M.gguf`(1024 dims, last-token pooling, L2-normalised, no instruction prefix).
## Two views
**Text vs. nouns** — paste one sentence, or two. With two texts it shows which nounsboth of them pull toward, which is a quick way to see where two descriptions sharevocabulary and where they don't.
**Noun → nearest nouns** — start from one noun and see what sits closest to it inembedding space. Useful for checking whether a vocabulary has clusters, or whether aterm is really as distinct as it feels.
## Notes on the numbers
Scores are cosine similarities, printed to four decimals. When two nouns come outvery close (say 0.4810 and 0.4849), treat the gap as a tie — tiny numeric differencesbetween backends can swap the order, even though the same nouns land at the top.
This Space uses the prebuilt `llama-cpp-python` wheel and therefore that wheel'sbundled llama.cpp. Ranking was checked against the `llama-embedding` CLI: **top-20overlap is 20/20 and top-5 order is identical** on the sample sentences. Individualvectors differ by around 1e-3 in cosine, which does not move reasonably-separatednouns.
## How it is built
The 396 MB GGUF is not committed to this repo. It is preloaded from the Hub duringthe image build (`preload_from_hub` above), so it is in the local `huggingface_hub`cache before `app.py` starts.
On first boot, `app.py` embeds every noun in `generic_nouns.txt` **once** and keepsthe resulting matrix in memory. A request then embeds only your text — a single shortforward pass — and takes the dot product against the matrix. Embedding 600+ nouns perrequest would take far longer than a Space's CPU budget allows.
`precompute_nouns.py` can build that matrix ahead of time as a file; it is notrequired on the Space, which caches the matrix in memory instead. `embed_compare.py`is the original CLI, which computes the same ranking from scratch.
## Related files
- [`embed_compare.py`](./embed_compare.py) — the CLI- [`precompute_nouns.py`](./precompute_nouns.py) — cache builder- [`generic_nouns.txt`](./generic_nouns.txt) — the vocabulary
## Licenses
- **Octen-Embedding-0.6B** (base model, `Octen/Octen-Embedding-0.6B`) — Apache-2.0. Quantised to GGUF by `mradermacher/Octen-Embedding-0.6B-GGUF`.- **llama-cpp-python / llama.cpp** — MIT.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293"""Demo: where does a sentence fall among 627 place nouns?
Embeds the input text and every noun in generic_nouns.txt withOcten-Embedding-0.6B through llama.cpp, L2-normalises both sides, and ranksthe nouns by cosine similarity. This is a browser front end for the`embed_compare.py` command-line tool shipped alongside it (`python3embed_compare.py "some text"`), using the same model, pooling, and ranking.
The noun vectors are precomputed at image build time (precompute_nouns.py),so a request only embeds the visitor's text: one short forward pass."""import osimport sysimport threadingfrom array import arrayfrom pathlib import Path
import numpy as npimport gradio as gr
import embed_compare as ec
HERE = Path(__file__).resolve().parent# The 396 MB GGUF is not committed; it is pulled from the Hub at build time.MODEL_REPO = "mradermacher/Octen-Embedding-0.6B-GGUF"MODEL_FILE = "Octen-Embedding-0.6B.Q4_K_M.gguf"MODEL_PATH = Path(os.environ.get("EMBED_MODEL", ec.DEFAULT_MODEL))CACHE_DIR = Path(os.environ.get("EMBED_CACHE_DIR", ec.DEFAULT_CACHE))NOUNS_PATH = Path(os.environ.get("EMBED_NOUNS", ec.DEFAULT_NOUNS))# Pinned rather than left to the model default, so the Space says what it does.POOLING = os.environ.get("EMBED_POOLING", "last")PREFIX_NOUN = os.environ.get("EMBED_PREFIX_NOUN", "")PREFIX_TEXT = os.environ.get("EMBED_PREFIX_TEXT", "")
EXAMPLES = [ "We hiked along the ridge above the fjord and camped by the lake.", "Cold rain on the moors, wind over the fell; the beck ran high past " "the sheepfold.", "Sunday roast in the pub, then a walk past the allotments to the church.", "The tidal flats stretch for miles at low water; cockles at dawn.", "Send the invoice to the depot behind the retail park.",]
_lock = threading.RLock() # setup() calls get_embedder(), which locks again_state = {"ready": False, "nouns": [], "matrix": None, "error": None}_embedder = {"emb": None}
# ------------------------------------------------------------------ setup
def _matrix_from_cache(cache, nouns): """Load the build-time float32 matrix, or None if absent/stale.""" meta = cache.load() p = cache.path.with_name(cache.path.stem + "-f32.bin") if not meta or not p.is_file(): return None dims = int(meta.get("dims") or 1024) flat = array("f") with open(p, "rb") as f: flat.frombytes(f.read()) if sys.byteorder != "little": flat.byteswap() if len(flat) != len(nouns) * dims: print(f"cache shape mismatch: {len(flat)} floats, " f"expected {len(nouns) * dims}", file=sys.stderr) return None return np.array(flat, dtype=np.float32).reshape(len(nouns), dims)
def ensure_model(): """Download the GGUF from the Hub if it isn't already on disk.""" if MODEL_PATH.is_file(): return MODEL_PATH from huggingface_hub import hf_hub_download
MODEL_PATH.parent.mkdir(parents=True, exist_ok=True) print(f"downloading {MODEL_REPO}/{MODEL_FILE}...", file=sys.stderr) got = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE) print(f"downloaded to {got}", file=sys.stderr) return Path(got)
def setup(): """Load nouns + the precomputed matrix. Idempotent; safe under a lock.""" with _lock: if _state["ready"] or _state["error"]: return _state try: path = ensure_model() if "EMBED_MODEL" not in os.environ and path != MODEL_PATH: # Point the rest of the app (cache key, embedder) at the download. globals()["MODEL_PATH"] = path nouns = ec.load_nouns(NOUNS_PATH) if not nouns: raise RuntimeError(f"no noun entries in {NOUNS_PATH}") key = ec.cache_key({"path": str(MODEL_PATH), "sha256": ec.sha256_file(MODEL_PATH)}, nouns, pooling=POOLING, prefix_noun=PREFIX_NOUN) cache = ec.VectorCache(CACHE_DIR, key) mat = _matrix_from_cache(cache, nouns) if mat is None: # The build step should have covered this; still serve if not. print(f"cold cache, embedding {len(nouns)} nouns " f"(pooling={POOLING!r})...", file=sys.stderr) vecs = get_embedder()([PREFIX_NOUN + n for n in nouns]) mat = np.array(vecs, dtype=np.float32) _state.update(ready=True, nouns=nouns, matrix=mat) print(f"ready: {mat.shape[0]} nouns x {mat.shape[1]} dims " f"({MODEL_PATH.name}, pooling {POOLING})", file=sys.stderr) except Exception as e: # keep the UI up and say what broke _state["error"] = f"{type(e).__name__}: {e}" print(f"setup failed: {_state['error']}", file=sys.stderr) return _state
def get_embedder(): """Return the shared embedder, creating it once.
Called both from setup() (which already holds _lock) and from request handlers, so the lock must be reentrant. """ with _lock: if _embedder["emb"] is None: _embedder["emb"] = ec.Embedder(MODEL_PATH, pooling=POOLING) return _embedder["emb"]
def embed_one(text): v = np.asarray(get_embedder()([PREFIX_TEXT + text])[0], dtype=np.float32) n = float(np.linalg.norm(v)) return v / n if n else v
def _table(header, rows, highlight=()): th = "".join(f"<th>{h}</th>" for h in header) body = [] for r in rows: cls = ' class="hit"' if r[-1] in highlight else "" body.append(f"<tr{cls}>" + "".join(f"<td>{c}</td>" for c in r) + "</tr>") return (f"<table class='rank'><thead><tr>{th}</tr></thead>" f"<tbody>{''.join(body)}</tbody></table>")
def _ranked(sc, nouns, k): order = np.argsort(-sc)[:k] return order, [[f"{i + 1}", f"{float(sc[j]):.4f}", nouns[j]] for i, j in enumerate(order)]
# ------------------------------------------------------------------- demo
def compare(text_a, text_b, top_k): """Rank the 627 generic place nouns by similarity to your text.
Args: text_a: a sentence or paragraph (required). text_b: optional second text, ranked side by side. Empty to skip. top_k: how many nouns to show per ranking (5-50).
Returns: (html, markdown) — the ranked nouns and a short summary line. """ st = setup() if st["error"]: raise gr.Error(f"Model failed to load: {st['error']}")
text_a = (text_a or "").strip() text_b = (text_b or "").strip() if not text_a: raise gr.Error("Enter some text to compare against the nouns.") k = max(1, min(50, int(top_k or 15))) nouns, mat = st["nouns"], st["matrix"]
# Both sides are unit length, so the dot product is the cosine. if not text_b: sc = mat @ embed_one(text_a) order, rows = _ranked(sc, nouns, k) top = nouns[int(order[0])] return (_table(["#", "score", "noun"], rows), f"**Top match:** `{top}` — cosine {float(sc[order[0]]):.4f} " f"across all {len(nouns)} nouns.")
va, vb = embed_one(text_a), embed_one(text_b) sa, sb = mat @ va, mat @ vb oa, ra = _ranked(sa, nouns, k) ob, rb = _ranked(sb, nouns, k) shared = set(oa.tolist()) & set(ob.tolist()) rows = [["{0}".format(i + 1)] + ra[i][1:] + rb[i][1:] for i in range(k)] note = (f"**Text A vs Text B:** cosine {float(np.dot(va, vb)):.4f}.") if shared: note += (" In both top lists: " + ", ".join(f"`{nouns[j]}`" for j in oa if j in shared) + ".") return (_table(["#", "score A", "noun A", "score B", "noun B"], rows, highlight=shared), note)
def lookup(noun, top_k): """Show the nouns closest to a chosen noun in embedding space.
Args: noun: a noun that appears in generic_nouns.txt (e.g. "valley"). top_k: how many neighbours to show (5-50).
Returns: (html, markdown) — nearest nouns excluding the noun itself, and a line. """ st = setup() if st["error"]: raise gr.Error(f"Model failed to load: {st['error']}") noun = (noun or "").strip().lower() if noun not in st["nouns"]: raise gr.Error(f"'{noun}' is not in the noun list.") k = max(1, min(50, int(top_k or 15))) i = st["nouns"].index(noun) sims = st["matrix"] @ st["matrix"][i] order = [j for j in np.argsort(-sims).tolist() if j != i][:k] rows = [[f"{r + 1}", f"{float(sims[j]):.4f}", st["nouns"][j]] for r, j in enumerate(order)] return (_table(["#", "score", "noun"], rows), f"**Nearest to `{noun}`** among all {len(st['nouns'])} nouns.")
def noun_choices(): return setup()["nouns"] or ["valley"]
CSS = """table.rank { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }table.rank th, table.rank td { padding: 4px 10px; border-bottom: 1px solid var(--border-color-primary); text-align: left; }table.rank th { font-weight: 600; opacity: 0.75; }table.rank td:first-child, table.rank td:nth-child(2) { color: var(--body-text-color-subdued, #888); }table.rank tr.hit td { background: var(--color-accent-soft, rgba(120,120,255,0.12)); }"""
with gr.Blocks(title="Embed Compare — place nouns") as demo: gr.Markdown( "# Where does your sentence land among 627 place nouns?\n" "Embeds your text with **Octen-Embedding-0.6B** (Qwen3-Embedding base, " "Q4_K_M, llama.cpp) and ranks the generic place nouns in " "`generic_nouns.txt` by cosine similarity — the same model, pooling and " "ranking as the `embed_compare.py` CLI in this repo.\n\n" "*Similarity is a rough signal: with last-token pooling, a long " "sentence mostly reflects how it ends.*" ) with gr.Tab("Text vs. nouns"): a = gr.Textbox(label="Text A", lines=3, placeholder="We hiked along the ridge above the fjord…") b = gr.Textbox(label="Text B (optional — compare two texts)", lines=3, placeholder="Leave empty to rank a single text.") k = gr.Slider(5, 50, value=15, step=1, label="Nouns to show") btn = gr.Button("Rank nouns", variant="primary") out = gr.HTML(label="Ranked nouns") summary = gr.Markdown() gr.Examples(EXAMPLES, inputs=a, label="Try one") btn.click(compare, [a, b, k], [out, summary], api_name="compare") a.submit(compare, [a, b, k], [out, summary])
with gr.Tab("Noun → nearest nouns"): gr.Markdown("Pick a noun to see which other place nouns sit closest " "to it in embedding space.") with gr.Row(): pick = gr.Dropdown(choices=noun_choices(), value="valley", label="Noun", filterable=True, scale=3) k2 = gr.Slider(5, 50, value=15, step=1, label="Neighbours", scale=2) btn2 = gr.Button("Find neighbours", variant="primary") out2 = gr.HTML() summary2 = gr.Markdown() btn2.click(lookup, [pick, k2], [out2, summary2], api_name="lookup")
with gr.Accordion("How it works", open=False): gr.Markdown( f"- **Model:** `Octen-Embedding-0.6B.Q4_K_M.gguf` — 1024 dims, " f"last-token pooling, L2-normalised, no instruction prefix " f"(per the model card).\n" f"- **Nouns:** {len(ec.load_nouns(NOUNS_PATH))} entries from " f"`generic_nouns.txt`, embedded once at image build time.\n" f"- **Score:** cosine similarity. Both sides are unit length, so " f"this is the dot product.\n" f"- **CLI:** `python3 embed_compare.py \"your text\" --top 10`; " f"`--text a.txt --text b.txt`; `--lookup valley`.\n" f"- **Licenses:** Octen-Embedding-0.6B is Apache-2.0; llama.cpp " f"(via llama-cpp-python) is MIT." )
if __name__ == "__main__": # The model is preloaded by Spaces (see `preload_from_hub` in README.md), # so ensure_model() normally finds it already on disk. setup() warms the # embedder and builds the noun matrix on first boot if it is missing. setup() # Gradio 6 moved theme/css from the Blocks constructor to launch(). demo.queue(max_size=32).launch( mcp_server=True, theme=gr.themes.Soft(), css=CSS)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352#!/usr/bin/env python3"""Rank the generic place nouns by embedding similarity to an input text.
This is the Space port of the command-line script `embed_compare.py`. TheCLI shelled out to llama.cpp's `llama-embedding` binary once per batch; herewe call the same llama.cpp through `llama_cpp.Llama.embed()`, so the onlychange is how the vectors are produced. Pooling, normalisation and rankingare unchanged, and the two paths agree to float32 precision (~5e-08).
Model: Octen-Embedding-0.6B.Q4_K_M.gguf (Qwen3-Embedding-0.6B base:last-token pooling, L2 normalised, 1024 dims). The model card encodes baretext with no instruction prefix, so none is added by default.
generic_nouns.txt is a commented record file: '#' lines and blank lines areskipped, everything else is one noun. We embed the class nouns as-is; thefile is a record, not a blocklist.
# rank all nouns against a text, show the top 25 python3 embed_compare.py "We hiked along the ridge above the fjord."
# compare two texts side by side + the nouns best matching each python3 embed_compare.py --text a.txt --text b.txt --top 10
# find where one noun sits among the others (nearest neighbours) python3 embed_compare.py --lookup valley --top 15
# warm the vector cache (later runs skip re-embedding the nouns) python3 embed_compare.py --build-cache
Options that matter: --pooling last|mean|cls pooling type (default: model default = last) --prefix-text S string prepended to the input text only --prefix-noun S string prepended to each noun only --json OUT.json write the full ranking as JSON --no-cache re-embed the nouns instead of using the cache --threads N CPU threads for llama.cpp (default: llama.cpp's)
Exit status: 0 on success, 2 on bad input (missing file, no nouns, etc.)."""import argparseimport hashlibimport jsonimport mathimport osimport reimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentDEFAULT_MODEL = HERE / "models" / "Octen-Embedding-0.6B.Q4_K_M.gguf"DEFAULT_NOUNS = HERE / "generic_nouns.txt"DEFAULT_CACHE = HERE / ".embed_cache"
# ---------------------------------------------------------------- loading
def load_nouns(path): """Return the noun entries of generic_nouns.txt in file order.
Lines starting with '#' and blank lines are skipped. An entry may occur in several sections; the first occurrence wins so order stays stable. """ nouns, seen = [], set() with open(path, encoding="utf-8") as f: for raw in f: line = raw.strip() if not line or line.startswith("#"): continue if line not in seen: seen.add(line) nouns.append(line) return nouns
def die(msg): print(msg, file=sys.stderr) sys.exit(2)
def read_input(item, from_file_option): """An input is an existing file path, otherwise the literal text.
A --text value is unambiguous, so a path-shaped value that does not exist is an error rather than silently being embedded as a sentence. """ p = Path(item) if p.is_file(): return p.read_text(encoding="utf-8").strip() if from_file_option and (p.suffix or "/" in item) and not p.exists(): die(f"error: --text file not found: {item}") return item.strip()
def sha256_file(path, chunk=1 << 20): h = hashlib.sha256() with open(path, "rb") as f: for block in iter(lambda: f.read(chunk), b""): h.update(block) return h.hexdigest()
# ------------------------------------------------------------- embedding
class Embedder: """Embed texts with llama.cpp, one batch at a time.
Pooling is pinned to `last` rather than left to the model default so the Space matches the CLI's default explicitly. Embeddings are returned normalised and L2-normalised again here, which is idempotent and keeps the scale obvious at the call site. """
def __init__(self, model, *, pooling="last", threads=None, batch_size=2048, n_ctx=8192, n_batch=None, verbose=False): self.model = Path(model) if not self.model.is_file(): die(f"error: model not found: {self.model}") from llama_cpp import Llama # imported late: the CLI path needs no wheel self.llm = Llama( model_path=str(self.model), embedding=True, n_ctx=n_ctx, n_batch=n_batch or max(batch_size, 512), n_threads=threads, pooling_type=POOLING_TYPES[pooling], n_gpu_layers=0, logits_all=False, verbose=verbose, ) self.batch_size = batch_size
@staticmethod def _one_line(text): return re.sub(r"\s+", " ", text).strip() or "(empty)"
def __call__(self, texts): if not texts: return [] out = [] for i in range(0, len(texts), self.batch_size): chunk = [self._one_line(t) for t in texts[i:i + self.batch_size]] res = self.llm.embed(chunk, normalize=True) out.extend(l2_normalize(list(map(float, v))) for v in res) return out
# llama.cpp pooling enum: LLAMA_POOLING_TYPE_NONE=0, MEAN=1, CLS=2, LAST=3, RANK=4POOLING_TYPES = {"none": 0, "mean": 1, "cls": 2, "last": 3, "rank": 4}
def l2_normalize(v): n = math.sqrt(sum(x * x for x in v)) return [x / n for x in v] if n else list(v)
def cosine(a, b): # Both sides are already unit length; this is just the dot product. return sum(x * y for x, y in zip(a, b))
# ----------------------------------------------------------------- cache
class VectorCache: """One JSON file per (model hash, pooling, prefix, noun set).
Loading the 0.6B model costs a few seconds, so caching the noun vectors makes repeat comparisons nearly free. On the Space the cache is built once at image build time (see precompute_nouns.py), so the first visitor does not pay for it either. """
def __init__(self, directory, key): self.path = Path(directory) / f"{key}.json"
def load(self): if not self.path.is_file(): return None try: with open(self.path, encoding="utf-8") as f: return json.load(f) except (json.JSONDecodeError, OSError): return None
def save(self, payload): self.path.parent.mkdir(parents=True, exist_ok=True) tmp = self.path.with_suffix(".tmp") with open(tmp, "w", encoding="utf-8") as f: json.dump(payload, f) os.replace(tmp, self.path)
def cache_key(model, nouns, *, pooling="", prefix_noun=""): h = hashlib.sha256() h.update(f"{model.get('sha256', model['path'])}|{pooling}|" f"{prefix_noun}".encode()) for n in nouns: h.update(b"\x00" + n.encode("utf-8")) return h.hexdigest()[:20]
# ---------------------------------------------------------------- ranking
def rank(nouns, noun_vecs, query_vec): scored = [(cosine(query_vec, v), n, v) for n, v in zip(nouns, noun_vecs)] scored.sort(key=lambda t: -t[0]) return scored
def topk(scored, k): out = [] for i, (s, n, _) in enumerate(scored[:k], 1): out.append(f"{i:>3}. {s:6.4f} {n}") return "\n".join(out)
def truncate(text, width=72): text = " ".join(text.split()) return text if len(text) <= width else text[: width - 1] + "\u2026"
# ------------------------------------------------------------------- main
def build_parser(): p = argparse.ArgumentParser( description="Rank the generic place nouns by embedding similarity to " "an input text (llama.cpp + Octen-Embedding-0.6B).", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__.split("Options that matter:")[1], ) p.add_argument("text", nargs="*", metavar="TEXT", help="input text, or a path to a text file; " "same as repeating --text") p.add_argument("--text", dest="texts", action="append", default=[], metavar="TEXT", help="input text or file path; repeat to compare several") p.add_argument("--lookup", metavar="NOUN", help="show the nouns nearest to this one instead") p.add_argument("--nouns", default=str(DEFAULT_NOUNS), metavar="FILE", help="noun list (default: generic_nouns.txt beside script)") p.add_argument("--model", default=str(DEFAULT_MODEL), metavar="GGUF") p.add_argument("--top", type=int, default=25, help="entries to show per ranking (default: 25; 0 = all)") p.add_argument("--bottom", action="store_true", help="also show the least similar entries") p.add_argument("--pooling", choices=["last", "mean", "cls", "rank"], default="last", help="pooling type (default: last)") p.add_argument("--prefix-text", default="", help="prepend this to the input text") p.add_argument("--prefix-noun", default="", help="prepend this to each noun") p.add_argument("--threads", type=int, help="CPU threads for llama.cpp") p.add_argument("--batch-size", type=int, default=2048) p.add_argument("--no-cache", action="store_true", help="re-embed the nouns instead of using the cache") p.add_argument("--build-cache", action="store_true", help="only build the noun-vector cache, then exit") p.add_argument("--cache-dir", default=str(DEFAULT_CACHE), metavar="DIR") p.add_argument("--json", metavar="OUT.json", help="write full rankings to this JSON file") return p
def main(argv=None): args = build_parser().parse_args(argv)
nouns = load_nouns(args.nouns) if not nouns: die(f"error: no noun entries in {args.nouns}")
inputs = list(args.text) + list(args.texts) if not inputs and not args.lookup and not args.build_cache: die("error: give an input text, --text, --lookup or --build-cache")
model_path = Path(args.model) if not model_path.is_file(): die(f"error: model not found: {model_path}") info = {"path": str(model_path), "sha256": sha256_file(model_path)} key = cache_key(info, nouns, pooling=args.pooling, prefix_noun=args.prefix_noun) cache = None if args.no_cache else VectorCache(args.cache_dir, key) cached = cache.load() if cache else None if cached and cached.get("nouns") != nouns: cached = None noun_vecs = cached["vectors"] if cached else None
embedder = Embedder(model_path, pooling=args.pooling, threads=args.threads, batch_size=args.batch_size)
if cache is None or cached is None: print(f"embedding {len(nouns)} nouns with " f"{model_path.name}\u2026", file=sys.stderr) noun_vecs = embedder([args.prefix_noun + n for n in nouns]) if cache is not None: cache.save({"nouns": nouns, "vectors": noun_vecs, "model": str(model_path), "sha256": info["sha256"], "pooling": args.pooling}) print(f"cached noun vectors in {cache.path}", file=sys.stderr)
if args.build_cache and not inputs and not args.lookup: return 0
top = args.top if args.top > 0 else None report = {"model": str(model_path), "nouns": len(nouns), "pooling": args.pooling, "queries": []}
if args.lookup: if args.lookup not in nouns: die(f"error: {args.lookup!r} is not in {args.nouns}") i = nouns.index(args.lookup) scored = rank(nouns, noun_vecs, noun_vecs[i])[1:] print(f"Nearest nouns to {args.lookup!r} ({args.pooling})") print(topk(scored, top)) if args.bottom: print("\nLeast similar:") print(topk(scored[::-1], min(top or len(scored), 10))) report["queries"].append({ "lookup": args.lookup, "ranking": [{"noun": n, "score": s} for s, n, _ in scored]}) else: # Positional values may be prose; --text values may also be paths. positional = [(t, False) for t in args.text] flagged = [(t, True) for t in args.texts] texts = [read_input(t, is_path_ok) for t, is_path_ok in positional + flagged] vecs = embedder([args.prefix_text + t for t in texts]) for text, vec in zip(texts, vecs): scored = rank(nouns, noun_vecs, vec) print(f"\n=== {truncate(text)}") print(topk(scored, top)) if args.bottom: print("\nLeast similar:") print(topk(scored[::-1], min(top or len(scored), 10))) report["queries"].append({ "text": text, "ranking": [{"noun": n, "score": s} for s, n, _ in scored]}) if len(texts) > 1: print("\n=== Input-vs-input similarity") for a in range(len(texts)): for b in range(a + 1, len(texts)): print(f" {cosine(vecs[a], vecs[b]):6.4f} " f"{truncate(texts[a], 32)} <-> " f"{truncate(texts[b], 32)}")
if args.json: Path(args.json).write_text(json.dumps(report, indent=1), encoding="utf-8") print(f"wrote {args.json}", file=sys.stderr) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642# Generic place-noun classes. THIS FILE IS A RECORD, NOT A RULE SET.## ## HOLD Every entry. These are bare class nouns and compound# classes ('valley', 'lake', 'national park'). Deleting one# as a canonical key also deletes real names that contain# it ('Upper Valley', 'Lake Titicaca', 'Snowdonia National# Park'): 95 of 99 labelled bare keys are used inside a name# at least once. Only the SINGLE-TOKEN span may ever be# deleted, and only by a span-aware consumer.## A consumer that loads these as plain lines would delete real places.# place_nouns.load_blocklist() strips this section before applying# anything, so passing this file to --blocklist removes nothing.### HOLDabbeyabyssacropolisaerodromeagoraairfieldairportalleyallotmentalpamphitheatreapiaryapronaquariumaqueductaquiferarboretumarcadearchipelagoarenaaretearmarmletarroyoashramasteroidatollatriumavalancheaviarybackwaterbadlandbalconybanyanbarnbarrackbarrenbasaltbasilicabasinbastionbatholithbaybazaarbeachbeaconbeckbelvederebenchbightbillabongbiospherebiosphere reservebirchbird sanctuarybluffboardwalkboathousebogboreholeboroughbotanical gardenboulderboulevardbournebowerbowlbraebranchbreakwaterbridgebrookbunkerburghburnburrowbushbushlandbypassbywaycairncalderacampcampuscanalcanyoncapecaravanseraicascadecasematecastlecatacombcataractcatchmentcathedralcausewaycavecaverncaycemeterycenotechalkchannelchapelchasmchateauchurchcirclecircuitcirquecitadelcitycity parkclearingcliffclifftopcloistercloughcoastcoastlinecolonnadecombecometcommunecompoundconeconfluenceconservation areaconstellationconventcoombcoppicecopsecorriecotecottagecouleecouloircountrysidecourtyardcovecragcratercreekcrestcrevassecrossroadcuestaculvertcwmcyclonedaledamdefiledelldenedepressiondesertdiatremedingleditchdividedockdockyarddolmendomedowndriftdrumlinduchydunedykeearthworkeclipseedgeelevationembankmentembaymenteminenceenclaveenclosureendequatorergescarpmenteskerestateestuaryevergladeexcavationfarmfaultfellfenfenlandferryfieldfirnfirthfissurefjordflatfloefloodplainfloodwaterflumefollyfootbridgefoothillfootpathfordforelandforestforest reserveforgefortfortressfossafossefountainfreewayfriaryfumarolegalaxygallerygame parkgame reservegapgardengarretgategazebogeysergillglaciergladeglengorgegrabengrangegranitegrasslandgravegravelgraveyardgreengrottogroynegulchgulfhamletharborharbourhavenheadlandheadwaterheathheavenshedgehedgerowheighthelipadheritage sitehermitagehighlandhighwayhillhillockhillsidehogbackholmhomesteadhorizonhorsthostelhothotelhummockhurricanehuticebergicecapicefallicefieldindentationinletinnislandisleisthmusjettyjunglekamekarstkeepkettlekeykioskknapknobknolllagoonlakelakesidelandformlandinglandslidelanelatitudelavalealedgeleveelibrarylighthouselimestonelochlocklodelodgelongitudelookoutloughlowlandmaarmamelonmanormansionmaremarinamarine parkmarine reservemarshmarshlandmassifmausoleummeadowmeandermemorialmenhirmeremeridianmeteormetropolismillminemoatmonasterymonsoonmonumentmoonmoormooringmoorlandmorainemosquemotorwaymottemoundmountmountainmountainsidemouthmudflatmunicipalitymuseumnarrowsnational forestnational lakeshorenational monumentnational parknational scenic areanational seashorenational wildlife refugenatural reservenature parknature reservenessnevenichenotchnunneryoasisobeliskobservationobservatoryoceanoratoryorchardouedoutcropoutletoutlieroutlookoverlookpaddockpagodapalacepalazzopaleosolpantheonparkparklandpasspassagepasturepathpavilionpeakpeninsulapergolapierpinnaclepitplaceplainplanetplanetariumplantationplateplateauplatformplayaplaygroundplazaplotpolderpondpoolporchportporticopotholeprairieprecinctprecipiceprefecturepreserveprioryprojectionpromenadepromontoryprotected areapublic gardenpyramidquarryquarterquayrailroadrailwayrainforestrampartranchravinereachreefrefugeregreservereservoirresortretreatriaridgeridgewayriftrillringriseriverriverbankriverbedriverineriversiderivuletroadroadwayrouteruinruinsrunrunnelsaddlesanctuarysandbanksandbarsandpitsandstonesavannascarpscenic areaschoolscrubscrublandseaseabedseaboardseamountseashoreseasideseatseracsettlementshantytownshawshelfshingleshoalshoreshorelineshrineshrublandsidewalksinkholeskywayslipwayslopesloughsluicesnowfieldsoaksolfatarasoundspaspinneyspirespitspringspringheadspringlinespursquarestadiumstairwaystarstate parkstationstatuesteadingsteppestraitstrandstreamstreamletstreetstretchstupasuburbsummitsunswampswamplandsynagoguetablelandtaigatarntaverntelltempleterracetheatertheatrethickettidaltollgatetombtombolotortowertowntownshiptowpathtracktracttrailtrailheadtramwaytrenchtributarytropicstundratunnelturnturnpiketyphoonuplandvalevalleyveldveldtventviaductviewpointvillavillagevineyardvolcanowadiwalkwalkwaywallwashwastelandwatchtowerwaterfallwatermillwatershedwaterwaywayweirwellheadwetlandwharfwild riverwildernesswilderness areawildlifewildlife refugewildlife sanctuarywindmillwoldwoodwoodlandworld heritageyardzenithzoological garden123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126#!/usr/bin/env python3"""Embed the noun list once, at image build time.
The Space re-embeds 627 nouns per pooling type; on 2 vCPUs that is theslowest thing a visitor could trigger, and it is identical for everyone.So we do it once here, during the Docker build, and ship the vectors:
.embed_cache/<key>-f32.bin raw float32 matrix, (n_nouns, 1024) .embed_cache/<key>.json nouns, metadata, and a sha256 of the .bin
`embed_compare.VectorCache` reads both. Re-running is cheap-ish but this isa build step, so it only runs when the cache is missing or stale.
python3 precompute_nouns.py # skip if already valid python3 precompute_nouns.py --force # always rebuild"""import argparseimport hashlibimport jsonimport osimport sysfrom array import arrayfrom pathlib import Path
import embed_compare as ec
HERE = Path(__file__).resolve().parent
def bin_path(cache): return cache.path.with_name(cache.path.stem + "-f32.bin")
def load_matrix(cache): """Return the vectors as a flat array('f'), or None if unusable.""" meta = cache.load() if not meta or "sha256_bin" not in meta: return None p = bin_path(cache) if not p.is_file(): return None h = hashlib.sha256(p.read_bytes()).hexdigest() if h != meta["sha256_bin"]: print(f" {p.name}: checksum mismatch, rebuilding", file=sys.stderr) return None dims = meta.get("dims") vec = array("f") with open(p, "rb") as f: vec.frombytes(f.read()) if dims and len(vec) != len(meta["nouns"]) * dims: print(f" {p.name}: wrong length, rebuilding", file=sys.stderr) return None return vec
def write_matrix(cache, nouns, vectors, model, pooling, prefix_noun): dims = len(vectors[0]) flat = array("f", (x for v in vectors for x in v)) if sys.byteorder != "little": flat.byteswap() p = bin_path(cache) p.parent.mkdir(parents=True, exist_ok=True) tmp = p.with_suffix(".tmp") with open(tmp, "wb") as f: flat.tofile(f) os.replace(tmp, p) # JSON keeps the exact noun list; the matrix is the bulk and stays binary # (12.7e6 floats as JSON text would be ~20x larger). cache.save({ "nouns": nouns, "dims": dims, "sha256_bin": hashlib.sha256(p.read_bytes()).hexdigest(), "model": str(model), "sha256": ec.sha256_file(model), "pooling": pooling, "prefix_noun": prefix_noun, }) print(f" wrote {p.name} ({len(nouns)} x {dims} float32, " f"{p.stat().st_size / 1e6:.1f} MB)", file=sys.stderr)
def run(model_path, nouns_path, pooling, prefix_noun, cache_dir, force): """Build the cache for one pooling type; return (ok, detail).""" if not model_path.is_file(): return False, f"model not found: {model_path}" nouns = ec.load_nouns(nouns_path) if not nouns: return False, f"no noun entries in {nouns_path}" info = {"path": str(model_path), "sha256": ec.sha256_file(model_path)} key = ec.cache_key(info, nouns, pooling=pooling, prefix_noun=prefix_noun) cache = ec.VectorCache(cache_dir, key)
print(f"pooling={pooling!r} prefix_noun={prefix_noun!r} key={key}", file=sys.stderr) if not force: m = load_matrix(cache) if m is not None: print(f" cache hit: {bin_path(cache).name}", file=sys.stderr) return True, f"cached ({len(nouns)} x 1024)"
emb = ec.Embedder(model_path, pooling=pooling or "last") vectors = emb([prefix_noun + n for n in nouns]) dims = len(vectors[0]) if len(vectors) != len(nouns) or dims != 1024: return False, f"bad shape {len(vectors)} x {dims}" write_matrix(cache, nouns, vectors, model_path, pooling, prefix_noun) return True, f"built ({len(vectors)} x {dims})"
def main(argv=None): p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) p.add_argument("--model", default=str(ec.DEFAULT_MODEL)) p.add_argument("--nouns", default=str(ec.DEFAULT_NOUNS)) p.add_argument("--cache-dir", default=str(ec.DEFAULT_CACHE)) p.add_argument("--pooling", default="", choices=["", "last", "mean", "cls"]) p.add_argument("--prefix-noun", default="") p.add_argument("--force", action="store_true") args = p.parse_args(argv) ok, detail = run(Path(args.model), Path(args.nouns), args.pooling, args.prefix_noun, Path(args.cache_dir), args.force) print(f" {detail}", file=sys.stderr) return 0 if ok else 1
if __name__ == "__main__": sys.exit(main())1234567# Prebuilt manylinux wheel (CPU) so the Space build never compiles llama.cpp.# The wheel vendors its own llama.cpp and needs no system dependency.llama-cpp-python @ https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.36/llama_cpp_python-0.3.36-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
numpy>=1.26jinja2>=3.1typing-extensions>=4.5.0.gitignoreAdded+11
README.mdAdded+73
app.pyAdded+293
embed_compare.pyAdded+352
generic_nouns.txtAdded+642
precompute_nouns.pyAdded+126
requirements.txtAdded+7