#!/usr/bin/env python3 """ match_demo.py: Let's user get a feeling for how easy or hard it is to match a sentence to a random submission. embeds a hard-coded 30-sentence message into one normalised sum vector, then let you type sentences and see how strongly each one matches the submission. Runs entirely on a Mac (Apple Silicon / Metal). Model: Qwen3-Embedding-0.6B, GGUF Q8_0 (~640 MB download on first run, cached afterwards). Setup (once): python3 -m venv .venv && source .venv/bin/activate pip install -U llama-cpp-python huggingface_hub numpy Run: python match_demo.py At the prompt, type a sentence and press Enter. :why toggle "debug" view (shows which hidden sentence it resembled; a real user would NOT see this, it is only for calibrating) :self score every sentence of the message against its own sum :q quit """ import os, sys import numpy as np # ------------------------------------------------------------------ message MESSAGE = """I fish for steelhead at night using a thermal monocular to read the current seams. Infrared scopes fog badly when the air drops below forty degrees near the river. The best bite on the lower Columbia comes two hours after the tide turns. I tie my own jigs with marabou dyed in tea and coffee for a natural color. Low frequency sonar picks up fish holding behind submerged logs better than high frequency. Cormorants on the estuary are a reliable sign that baitfish are moving upstream. I log water temperature, moon phase and barometric pressure for every trip. Fishing under a new moon has been consistently better for me than under a full moon. My drift boat is a 1978 wooden hull that I restored over three winters. I prefer fluorocarbon leaders because they disappear in clear winter water. Cold hands are the real limit on how long I can stay out after dark. I've been learning to read 12th-century neume notation from scanned manuscripts. Square notation made chant easier to sing but lost many rhythmic nuances. I sing in a small group that performs Gregorian chant twice a year. The acoustics of old stone churches change how fast you can sing a melisma. I'm slowly translating a medieval Latin treatise on music theory. Vellum manuscripts survive far better than the paper ones from two centuries later. I build simple tube radios from salvaged parts as a winter hobby. A good antenna matters more than the receiver when listening to distant stations. I keep a notebook of shortwave stations I've heard and the conditions at the time. Solar activity can make the high bands go completely silent for days. I bake sourdough with a starter that is now eleven years old. Rye flour makes the starter more active in a cold kitchen. I'm interested in how ergodic theory describes long-run averages of dynamical systems. Interval exchange transformations are a surprisingly rich source of examples. I walk the same coastal trail every Sunday morning regardless of weather. Tide pools after a winter storm are full of things you never see in summer. I volunteer counting shorebirds for a regional survey each spring. Dunlins move in tight flocks that turn all at once like a single animal. I'd like to find people who combine fieldwork outdoors with old manuscripts or old radios.""".splitlines() # Unrelated everyday sentences: used for the background mean (centring) and # for the noise baseline that turns raw scores into z-scores. In the real app # these are a fixed public list shipped with the model. REFERENCE = """The weather was mild for most of the week. She bought groceries on the way home from work. The committee will meet again next Tuesday. Prices rose sharply in the second quarter. He spent the afternoon repairing the fence. The museum opens at nine in the morning. Our team won the match in extra time. The recipe calls for two cups of flour. Traffic was heavy on the bridge this morning. The new policy takes effect in January. They watched a documentary about whales. The software update fixed several bugs. Children played in the park until sunset. The hotel offers free breakfast to guests. Scientists published the results last month. I need to renew my passport before the trip. The train was delayed by twenty minutes. The band released its third album in May. Students must submit essays by Friday. My phone battery dies too quickly these days. The restaurant downtown has a new chef. We painted the kitchen a pale yellow. The stock market closed slightly higher today. Our neighbors adopted a rescue dog. The flight to Denver was overbooked. I finally finished reading that long novel. The city is repaving the main road this summer. She runs five kilometers before breakfast. The printer at work keeps jamming. He is learning to play the guitar. The library extended its weekend hours. Our internet was down for most of the evening. The kids are excited about the school trip. I switched to a cheaper phone plan. The new coffee shop is always crowded. They are renovating the old train station. My sister just started a new job in marketing. The movie was longer than I expected. We need to replace the tires on the car. The garden center has a sale on roses. He forgot his umbrella at the office. The concert sold out in ten minutes. Our landlord is raising the rent next year. I signed up for a pottery class. The bakery closes early on Sundays. The meeting was moved to the larger room. She is planning a trip to Portugal. The elevator in our building is broken again. I bought a new pair of running shoes. The council approved the budget after a long debate.""".splitlines() # ------------------------------------------------------------------ model DIMS = 1024 # Qwen3-Embedding-0.6B native size; Matryoshka lets you cut this EOS = "<|endoftext|>" # Qwen3-Embedding expects inputs to end with this token def load_embedder(): if os.environ.get("DUMMY"): # offline self-test, no model download import re, zlib def emb(texts): out = np.zeros((len(texts), DIMS), np.float32) for i, t in enumerate(texts): for w in re.findall(r"\w+", t.lower()): out[i] += np.random.default_rng(zlib.crc32(w.encode())).standard_normal(DIMS) return out / (np.linalg.norm(out, axis=1, keepdims=True) + 1e-9) return emb import llama_cpp from llama_cpp import Llama print("Loading Qwen3-Embedding-0.6B (first run downloads ~640 MB)...") llm = Llama.from_pretrained( repo_id="Qwen/Qwen3-Embedding-0.6B-GGUF", filename="*Q8_0.gguf", embedding=True, pooling_type=llama_cpp.LLAMA_POOLING_TYPE_LAST, # required for Qwen3-Embedding n_ctx=512, n_batch=512, n_ubatch=512, n_gpu_layers=-1, # use the M1 GPU via Metal verbose=False, ) def emb(texts): vecs = [llm.embed(t + EOS, normalize=True) for t in texts] E = np.asarray(vecs, np.float32)[:, :DIMS] return E / np.linalg.norm(E, axis=1, keepdims=True) return emb def centre(E, mu): X = E - mu return X / np.linalg.norm(X, axis=1, keepdims=True) def verdict(z): if z >= 4: return "STRONG match" if z >= 3: return "likely match" if z >= 2: return "weak / same general area" return "no match" # ------------------------------------------------------------------ main def main(): emb = load_embedder() R_raw = emb(REFERENCE) mu = R_raw.mean(0) # public background mean M = centre(emb(MESSAGE), mu) # private: individual sentences S = M.sum(0); S /= np.linalg.norm(S) # PUBLIC: what gets uploaded ref = centre(R_raw, mu) @ S # noise baseline for this submission m0, s0 = ref.mean(), ref.std() zself = (M @ S - m0) / s0 print(f"\nSubmission: {len(MESSAGE)} sentences -> one {DIMS}-dim unit vector.") print(f"Unrelated sentences score {m0:+.3f} ± {s0:.3f}.") print(f"The message's own sentences score z = {zself.mean():.1f} on average " f"(min {zself.min():.1f}, max {zself.max():.1f}).") print("Type a sentence (or :why, :self, :q).\n") debug = False while True: try: q = input("> ").strip() except (EOFError, KeyboardInterrupt): print(); break if not q: continue if q == ":q": break if q == ":why": debug = not debug print(f" debug view {'on' if debug else 'off'}") continue if q == ":self": for i in np.argsort(-zself): print(f" z={zself[i]:5.1f} {MESSAGE[i][:90]}") continue v = centre(emb([q]), mu)[0] s = float(v @ S) z = (s - m0) / s0 bar = "#" * max(0, min(40, int(round(z * 4)))) print(f" score {s:+.3f} z = {z:5.1f} {verdict(z):<26} {bar}") if debug: sims = M @ v for i in np.argsort(-sims)[:3]: print(f" (closest hidden sentence, cos {sims[i]:.2f}): {MESSAGE[i][:80]}") if __name__ == "__main__": main()