Download tools/build_dataset.py from vocabradar/WordEmbedding: direct link, hf CLI and curl.
- Browser
- Download file 28.9 kB
-
https://huggingface.co/datasets/vocabradar/WordEmbedding/resolve/main/tools/build_dataset.py
- Command line
-
hf download hf://datasets/vocabradar/WordEmbedding/tools/build_dataset.py
-
curl -L -o build_dataset.py https://huggingface.co/datasets/vocabradar/WordEmbedding/resolve/main/tools/build_dataset.py
28.9 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """WordEmbedding builder. | |
| Computes one 384-dimensional vector per word in the cleaned wordfreq lists | |
| (42 languages) with llama.cpp + bekko-embedding-v1-a25m-Q8_0, quantizes each | |
| L2-normalized vector to int8 (scale 127) and writes: | |
| data/<lang>.words.txt UTF-8, one word per line, wordfreq frequency order | |
| data/<lang>.int8.vector int8, row-major N x 384; row i = line i of words file | |
| Commands: | |
| embed compute missing language files (a llama-server is started/reused) | |
| finalize verify files, write meta.json + files.json, regenerate README tables | |
| all embed + finalize | |
| Every batch is appended to data/<lang>.int8.vector.part and fsynced, with progress in | |
| work/parts/<lang>.json, so an interrupted run resumes at the last durable | |
| batch instead of redoing the whole language. The .part is renamed to | |
| <lang>.int8.vector only after the final batch. | |
| Examples: | |
| python tools/build_dataset.py all | |
| python tools/build_dataset.py embed --langs en zh | |
| python tools/build_dataset.py finalize --allow-partial | |
| Several workers can run at the same time. The recommended way is a shared work | |
| queue: put one language code per line in a file and let every worker claim | |
| languages one at a time via an atomic O_EXCL claim under | |
| work/claims/<queue-hash>/. A free worker takes the next language, so a faster | |
| worker simply does more of them instead of letting a fast one idle: | |
| python tools/build_dataset.py embed --queue work/queue.txt --worker gpu \ | |
| --port 18083 --gpu-layers 99 | |
| python tools/build_dataset.py embed --queue work/queue.txt --worker cpu \ | |
| --port 18085 --gpu-layers 0 --threads 8 | |
| Claims are kept for the life of the queue file, so a finished language is never | |
| claimed twice; a new queue file starts from a fresh claim directory. --langs | |
| still runs a fixed list one language after another. | |
| The GGUF is downloaded from hf-mirror.com on first use and SHA-256 verified. | |
| llama-server is looked up in BrowserExtention/backend/bin/llamacpp by default; | |
| override with --llama-server or the LLAMA_SERVER environment variable. | |
| Runtime: roughly 300-700 words/s per task on a 16-thread laptop CPU/GPU. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import gzip | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| import time | |
| import urllib.request | |
| from datetime import datetime | |
| from pathlib import Path | |
| import msgpack | |
| import numpy as np | |
| import requests | |
| # ---------------------------------------------------------------- constants | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DATA_DIR = ROOT / "data" | |
| WORK_DIR = ROOT / "work" | |
| STATS_DIR = WORK_DIR / "stats" | |
| PARTS_DIR = WORK_DIR / "parts" | |
| CLAIMS_DIR = WORK_DIR / "claims" | |
| MODELS_DIR = WORK_DIR / "models" | |
| LOG_PATH = WORK_DIR / "build.log" | |
| DEFAULT_FREQ_DIR = ROOT.parent / "VocabFreq" / "data_small" | |
| DEFAULT_SERVER = (ROOT.parents[2] / "BrowserExtention" / "backend" / "bin" | |
| / "llamacpp" / "llama-server.exe") | |
| MODEL_REPO = "hotchpotch/bekko-embedding-v1-a25m-GGUF" | |
| MODEL_FILE = "bekko-embedding-v1-a25m-BF16.gguf" | |
| MODEL_SHA256 = "f85eda97336c37afd448a280153cd96f0bb19abfc4b3ae753f0aaaa9e093d559" | |
| MODEL_BYTES = 252522944 | |
| MODEL_URL = f"https://hf-mirror.com/{MODEL_REPO}/resolve/main/{MODEL_FILE}" | |
| DIM = 384 | |
| SCALE = 127.0 | |
| DEFAULT_PORT = 18080 | |
| # ---------------------------------------------------------------- utilities | |
| def log(msg: str) -> None: | |
| """Timestamped line on stdout and in the task log (best effort).""" | |
| line = f"{time.strftime('%H:%M:%S')} {msg}" | |
| print(line, flush=True) | |
| try: | |
| LOG_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| with LOG_PATH.open("a", encoding="utf-8") as f: | |
| f.write(line + "\n") | |
| except OSError: | |
| pass | |
| def sha256_file(path: Path, chunk: int = 1 << 20) -> str: | |
| """Streaming SHA-256 of a file.""" | |
| h = hashlib.sha256() | |
| with path.open("rb") as f: | |
| for block in iter(lambda: f.read(chunk), b""): | |
| h.update(block) | |
| return h.hexdigest() | |
| def write_atomic(path: Path, data: bytes) -> None: | |
| """Write bytes to path via a sibling .tmp file, then replace.""" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_name(path.name + ".tmp") | |
| tmp.write_bytes(data) | |
| os.replace(tmp, path) | |
| def load_wordfreq_meta(freq_dir: Path) -> dict: | |
| """Read the wordfreq dataset meta.json sitting next to data/ (optional).""" | |
| p = freq_dir.parent / "meta.json" | |
| if not p.exists(): | |
| return {} | |
| return json.loads(p.read_text(encoding="utf-8")) | |
| def read_queue(path: Path) -> list[str]: | |
| """Language codes from a queue file: one per line, # comments ignored.""" | |
| lines = path.read_text(encoding="utf-8").splitlines() | |
| return [l.strip() for l in lines if l.strip() and not l.strip().startswith("#")] | |
| def claim_language(queue_file: Path, lang: str, worker: str) -> bool: | |
| """Atomically claim one language of a shared queue; False when already taken. | |
| The claim is a zero-byte-plus-note file created with O_EXCL, which is atomic | |
| on Windows and POSIX, so two workers racing for the same language cannot | |
| both win. Claims live under a directory named after the queue content, so a | |
| new queue file starts with an empty claim set. | |
| """ | |
| digest = hashlib.sha1(queue_file.read_bytes()).hexdigest()[:12] | |
| path = CLAIMS_DIR / digest / f"{lang}.claim" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| try: | |
| fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | |
| except FileExistsError: | |
| return False | |
| with os.fdopen(fd, "w", encoding="utf-8") as f: | |
| f.write(f"{worker} pid={os.getpid()} at={time.strftime('%H:%M:%S')}\n") | |
| return True | |
| def list_languages(freq_dir: Path) -> list[str]: | |
| """Language codes that have a small_<code>.msgpack.gz in the wordfreq data dir.""" | |
| return sorted(p.name[len("small_"):-len(".msgpack.gz")] | |
| for p in freq_dir.glob("small_*.msgpack.gz")) | |
| def load_words(freq_dir: Path, lang: str) -> list[str]: | |
| """Load one cleaned wordfreq list (cB MessagePack: [header, bucket1, ...]).""" | |
| path = freq_dir / f"small_{lang}.msgpack.gz" | |
| with gzip.open(path, "rb") as f: | |
| obj = msgpack.unpack(f, raw=False) | |
| if not isinstance(obj, list) or not obj or obj[0].get("format") != "cB": | |
| raise ValueError(f"{path}: not a cB wordfreq list") | |
| return [w for bucket in obj[1:] for w in bucket] | |
| # ---------------------------------------------------------------- model | |
| def ensure_model(path: Path) -> Path: | |
| """Return a verified BF16 GGUF, downloading it from hf-mirror if needed.""" | |
| if path.exists(): | |
| size = path.stat().st_size | |
| if size == MODEL_BYTES and sha256_file(path) == MODEL_SHA256: | |
| return path | |
| log(f"model at {path} is incomplete or has the wrong hash; re-downloading") | |
| path.unlink() | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_name(path.name + ".part") | |
| log(f"downloading {MODEL_URL}") | |
| with requests.get(MODEL_URL, stream=True, timeout=120) as r: | |
| r.raise_for_status() | |
| total = int(r.headers.get("Content-Length") or 0) | |
| done = 0 | |
| next_report = 0 | |
| with tmp.open("wb") as f: | |
| for block in r.iter_content(1 << 20): | |
| f.write(block) | |
| done += len(block) | |
| if done >= next_report: | |
| pct = f" ({done * 100 // total}%)" if total else "" | |
| log(f" {done / 2**20:.1f} MiB{pct}") | |
| next_report = done + 20 * 2**20 | |
| digest = sha256_file(tmp) | |
| if digest != MODEL_SHA256: | |
| tmp.unlink(missing_ok=True) | |
| raise RuntimeError(f"model SHA-256 mismatch: {digest}") | |
| os.replace(tmp, path) | |
| log(f"model ready: {path} ({path.stat().st_size} bytes)") | |
| return path | |
| def server_version(server: Path) -> str: | |
| """First line of `llama-server --version`, for provenance in meta.json.""" | |
| try: | |
| out = subprocess.run([str(server), "--version"], capture_output=True, | |
| text=True, timeout=60) | |
| for line in (out.stdout + out.stderr).splitlines(): | |
| if "version:" in line: | |
| return line.strip() | |
| except Exception: | |
| pass | |
| return "unknown" | |
| # ---------------------------------------------------------------- server | |
| def server_health(port: int) -> bool: | |
| """True when a llama-server on this port reports status=ok.""" | |
| try: | |
| r = requests.get(f"http://127.0.0.1:{port}/health", timeout=1.5) | |
| return r.ok and r.json().get("status") == "ok" | |
| except Exception: | |
| return False | |
| def wait_health(port: int, seconds: int) -> None: | |
| """Block until /health is ok or raise after the timeout.""" | |
| deadline = time.time() + seconds | |
| while time.time() < deadline: | |
| if server_health(port): | |
| return | |
| time.sleep(0.5) | |
| raise RuntimeError(f"llama-server on port {port} did not become healthy") | |
| def start_server(server: Path, model: Path, port: int, ctx: int, | |
| gpu_layers: str = "99", threads: int = 0, | |
| verbose: bool = False) -> subprocess.Popen | None: | |
| """Reuse a healthy server on the port, otherwise start one and wait for it. | |
| Returns the Popen handle when this process started the server, else None. | |
| Server logs are disabled unless --verbose-server is given: llama-server's | |
| default per-slot logging is very heavy (tens of MB per hour) and measurably | |
| slows long embedding runs. | |
| """ | |
| if server_health(port): | |
| log(f"reusing llama-server already listening on 127.0.0.1:{port}") | |
| return None | |
| if not server.exists(): | |
| raise FileNotFoundError( | |
| f"llama-server not found: {server} (pass --llama-server or set LLAMA_SERVER)") | |
| WORK_DIR.mkdir(parents=True, exist_ok=True) | |
| log_path = WORK_DIR / f"llama-server-{port}.log" | |
| args = [ | |
| str(server), | |
| "--model", str(model), | |
| "--embedding", | |
| "--pooling", "mean", | |
| "--embd-normalize", "2", | |
| "--ctx-size", str(ctx), | |
| "--host", "127.0.0.1", | |
| "--port", str(port), | |
| "-np", "4", | |
| "-b", "2048", | |
| "-ub", "2048", | |
| "-ngl", str(gpu_layers), | |
| ] | |
| if threads: | |
| args += ["-t", str(threads)] | |
| if not verbose: | |
| args.append("--log-disable") | |
| flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0 | |
| log(f"starting llama-server on 127.0.0.1:{port} " | |
| f"(ngl={gpu_layers}, threads={threads or 'auto'}, log: {log_path})") | |
| with log_path.open("ab") as logf: | |
| proc = subprocess.Popen(args, cwd=str(server.parent), stdout=logf, | |
| stderr=subprocess.STDOUT, creationflags=flags) | |
| wait_health(port, 180) | |
| log("llama-server is healthy") | |
| return proc | |
| def stop_server(proc: subprocess.Popen | None) -> None: | |
| """Stop a server started by this process.""" | |
| if proc is None: | |
| return | |
| proc.terminate() | |
| try: | |
| proc.wait(timeout=15) | |
| except subprocess.TimeoutExpired: | |
| proc.kill() | |
| # ---------------------------------------------------------------- embedding | |
| def post_embeddings(session: requests.Session, port: int, words: list[str], | |
| retries: int = 4) -> list[dict]: | |
| """POST one batch to /v1/embeddings, retrying transient failures.""" | |
| url = f"http://127.0.0.1:{port}/v1/embeddings" | |
| payload = {"input": words, "model": "bekko", "encoding_format": "base64"} | |
| for attempt in range(retries): | |
| try: | |
| r = session.post(url, json=payload, timeout=600) | |
| r.raise_for_status() | |
| data = r.json().get("data") | |
| if not isinstance(data, list): | |
| raise ValueError("response has no data list") | |
| return data | |
| except Exception as exc: | |
| if attempt == retries - 1: | |
| raise | |
| wait = 2 ** attempt | |
| log(f" request failed ({type(exc).__name__}: {exc}); retry in {wait}s") | |
| time.sleep(wait) | |
| raise AssertionError("unreachable") | |
| def embed_language(session: requests.Session, port: int, words: list[str], | |
| batch_size: int, lang: str, backend: str | |
| ) -> tuple[int, float, float, float]: | |
| """Embed one language with per-batch checkpoints. | |
| Vectors are appended to data/<lang>.int8.vector.part as soon as each batch is | |
| quantized and fsynced; work/parts/<lang>.json records how many words are | |
| durable. An interrupted run therefore loses at most one batch, not the | |
| whole language. The .part file is renamed to <lang>.int8.vector only after | |
| the last batch. | |
| Returns (zero_vectors, int8_cosine_min, int8_cosine_mean, seconds). | |
| """ | |
| n = len(words) | |
| part = DATA_DIR / f"{lang}.int8.vector.part" | |
| state_path = PARTS_DIR / f"{lang}.json" | |
| words_hash = hashlib.sha1("\n".join(words).encode("utf-8")).hexdigest() | |
| done = 0 | |
| zero = 0 | |
| cos_min = 1.0 | |
| cos_sum = 0.0 | |
| cos_count = 0 | |
| elapsed_before = 0.0 | |
| if state_path.exists() and part.exists(): | |
| try: | |
| state = json.loads(state_path.read_text(encoding="utf-8")) | |
| except (OSError, ValueError): | |
| state = None | |
| if state and state.get("words_hash") == words_hash \ | |
| and 0 <= state.get("words_done", -1) <= n: | |
| done = int(state["words_done"]) | |
| want = done * DIM | |
| have = part.stat().st_size | |
| if have >= want: | |
| if have > want: # drop a torn trailing batch | |
| with part.open("r+b") as f: | |
| f.truncate(want) | |
| zero = int(state.get("zero_vectors", 0)) | |
| cos_min = float(state.get("cos_min", 1.0)) | |
| cos_sum = float(state.get("cos_sum", 0.0)) | |
| cos_count = int(state.get("cos_count", 0)) | |
| elapsed_before = float(state.get("seconds", 0.0)) | |
| log(f"{lang}: resuming at {done:,}/{n:,} words") | |
| else: | |
| done = 0 | |
| if done == 0: | |
| part.unlink(missing_ok=True) | |
| state_path.unlink(missing_ok=True) | |
| # The word list is deterministic; write it before the vectors so a resumed | |
| # run can always check alignment. | |
| write_words(DATA_DIR / f"{lang}.words.txt", words) | |
| PARTS_DIR.mkdir(parents=True, exist_ok=True) | |
| t0 = time.time() | |
| with part.open("ab") as f: | |
| for start in range(done, n, batch_size): | |
| chunk = words[start:start + batch_size] | |
| data = post_embeddings(session, port, chunk) | |
| if len(data) != len(chunk): | |
| raise RuntimeError( | |
| f"server returned {len(data)} vectors for {len(chunk)} inputs") | |
| rows = np.zeros((len(chunk), DIM), dtype=np.float32) | |
| for item in data: | |
| idx = int(item["index"]) | |
| emb = item.get("embedding") | |
| if isinstance(emb, str): # encoding_format=base64 | |
| vec = np.frombuffer(base64.b64decode(emb), dtype="<f4") | |
| else: | |
| vec = np.asarray(emb or [], dtype=np.float32) | |
| if idx < 0 or idx >= len(chunk): | |
| raise RuntimeError(f"bad response index {idx}") | |
| if vec.size != DIM: | |
| raise RuntimeError(f"expected {DIM} dimensions, got {vec.size}") | |
| rows[idx] = vec | |
| norms = np.linalg.norm(rows, axis=1, keepdims=True) | |
| zero += int((norms[:, 0] < 1e-6).sum()) | |
| rows /= np.maximum(norms, 1e-12) | |
| q = quantize(rows) | |
| f.write(q.tobytes()) | |
| f.flush() | |
| os.fsync(f.fileno()) # the batch is durable before the state advances | |
| bmin, bmean = int8_cosine(rows, q) | |
| cos_min = min(cos_min, bmin) | |
| cos_sum += bmean * len(chunk) | |
| cos_count += len(chunk) | |
| done += len(chunk) | |
| elapsed = elapsed_before + time.time() - t0 | |
| state = { | |
| "words_done": done, | |
| "words_hash": words_hash, | |
| "zero_vectors": zero, | |
| "cos_min": cos_min, | |
| "cos_sum": cos_sum, | |
| "cos_count": cos_count, | |
| "seconds": round(elapsed, 1), | |
| "backend": backend, | |
| } | |
| write_atomic(state_path, (json.dumps(state) + "\n").encode("utf-8")) | |
| rate = done / elapsed if elapsed else 0 | |
| eta = (n - done) / rate if rate else 0 | |
| log(f" {done:,}/{n:,} words {rate:,.0f} w/s eta {eta / 60:.1f} min") | |
| if part.stat().st_size != n * DIM: | |
| raise RuntimeError(f"{part}: size {part.stat().st_size}, expected {n * DIM}") | |
| os.replace(part, DATA_DIR / f"{lang}.int8.vector") | |
| state_path.unlink(missing_ok=True) | |
| seconds = elapsed_before + time.time() - t0 | |
| return zero, cos_min, (cos_sum / cos_count if cos_count else 0.0), seconds | |
| def quantize(rows: np.ndarray) -> np.ndarray: | |
| """Round L2-normalized float32 rows to symmetric int8 with scale 127.""" | |
| q = np.rint(rows * SCALE) | |
| np.clip(q, -SCALE, SCALE, out=q) | |
| return q.astype(np.int8) | |
| def int8_cosine(rows: np.ndarray, q: np.ndarray) -> tuple[float, float]: | |
| """Min/mean cosine between float32 rows and their dequantized int8 copies.""" | |
| back = q.astype(np.float32) / SCALE | |
| norms = np.linalg.norm(back, axis=1, keepdims=True) | |
| valid = norms[:, 0] > 1e-6 | |
| if not valid.any(): | |
| return 0.0, 0.0 | |
| cos = (rows[valid] * (back[valid] / norms[valid])).sum(axis=1) | |
| return float(cos.min()), float(cos.mean()) | |
| def write_words(path: Path, words: list[str]) -> None: | |
| """Write the word list as plain UTF-8, one word per line, trailing newline.""" | |
| write_atomic(path, ("\n".join(words) + "\n").encode("utf-8")) | |
| # ---------------------------------------------------------------- commands | |
| def cmd_embed(args: argparse.Namespace) -> None: | |
| """Compute/missing language files and per-language stats.""" | |
| freq_dir = Path(args.freq_dir) | |
| wf_meta = load_wordfreq_meta(freq_dir) | |
| queue_file = Path(args.queue) if args.queue else None | |
| worker = args.worker or f"pid{os.getpid()}" | |
| if queue_file is not None: | |
| languages = read_queue(queue_file) | |
| if not languages: | |
| raise SystemExit(f"queue file is empty: {queue_file}") | |
| counts = wf_meta.get("languages", {}) | |
| # Largest lists first so the tail is short: if one worker races ahead it | |
| # finishes on small languages while the other still has a big one. | |
| languages.sort(key=lambda l: -int((counts.get(l) or {}).get("kept") or 0)) | |
| log(f"queue {queue_file}: {len(languages)} languages, worker {worker}, " | |
| f"largest first") | |
| else: | |
| languages = args.langs or list_languages(freq_dir) | |
| worker = None | |
| model = ensure_model(Path(args.model)) | |
| server = Path(args.llama_server) | |
| backend = args.backend_tag or ("llamacpp-cpu" if str(args.gpu_layers) == "0" | |
| else "llamacpp-vulkan") | |
| proc = start_server(server, model, args.port, args.ctx, | |
| gpu_layers=args.gpu_layers, threads=args.threads, | |
| verbose=args.verbose_server) | |
| try: | |
| session = requests.Session() | |
| for lang in languages: | |
| if worker is not None and not claim_language(queue_file, lang, worker): | |
| continue # another worker owns this language | |
| if worker is not None: | |
| log(f"{lang}: claimed by {worker}") | |
| out_bin = DATA_DIR / f"{lang}.int8.vector" | |
| out_words = DATA_DIR / f"{lang}.words.txt" | |
| stat_path = STATS_DIR / f"{lang}.json" | |
| words = load_words(freq_dir, lang) | |
| expected = (wf_meta.get("languages", {}).get(lang) or {}).get("kept") | |
| if expected is not None and expected != len(words): | |
| log(f"WARNING {lang}: wordfreq meta says {expected} words, file has {len(words)}") | |
| if not args.force and out_bin.exists() and out_words.exists() \ | |
| and out_bin.stat().st_size == len(words) * DIM: | |
| log(f"{lang}: up to date ({len(words):,} words), skipping") | |
| continue | |
| log(f"{lang}: embedding {len(words):,} words ({backend})") | |
| for attempt in (1, 2): | |
| try: | |
| zero, cos_min, cos_mean, seconds = embed_language( | |
| session, args.port, words, args.batch, lang, backend) | |
| break | |
| except Exception as exc: | |
| if attempt == 2: | |
| raise | |
| log(f"{lang}: failed ({type(exc).__name__}: {exc}); " | |
| f"restarting llama-server and retrying (checkpoint kept)") | |
| stop_server(proc) | |
| proc = start_server(server, model, args.port, args.ctx, | |
| gpu_layers=args.gpu_layers, threads=args.threads, | |
| verbose=args.verbose_server) | |
| session = requests.Session() | |
| stat = { | |
| "words": len(words), | |
| "vectors_bytes": len(words) * DIM, | |
| "zero_vectors": zero, | |
| "int8_cosine_min": round(cos_min, 6), | |
| "int8_cosine_mean": round(cos_mean, 6), | |
| "seconds": round(seconds, 1), | |
| "backend": backend, | |
| } | |
| STATS_DIR.mkdir(parents=True, exist_ok=True) | |
| stat_path.write_text(json.dumps(stat, ensure_ascii=False, indent=2) + "\n", | |
| encoding="utf-8") | |
| log(f"{lang}: done in {seconds / 60:.1f} min, int8 cosine {cos_min:.5f}..{cos_mean:.5f}") | |
| if worker is not None and queue_file is not None: | |
| log(f"worker {worker}: queue exhausted, every language is claimed") | |
| finally: | |
| stop_server(proc) | |
| def cmd_finalize(args: argparse.Namespace) -> None: | |
| """Verify data/, write meta.json + files.json and regenerate README tables.""" | |
| freq_dir = Path(args.freq_dir) | |
| languages = args.langs or list_languages(freq_dir) | |
| wf_meta = load_wordfreq_meta(freq_dir) | |
| present = [l for l in languages if (DATA_DIR / f"{l}.int8.vector").exists() | |
| and (DATA_DIR / f"{l}.words.txt").exists()] | |
| missing = [l for l in languages if l not in present] | |
| if missing and not args.allow_partial: | |
| raise SystemExit(f"missing output for {len(missing)} languages: {' '.join(missing)}\n" | |
| f"run `python tools/build_dataset.py embed` or pass --allow-partial") | |
| entries = {} | |
| files = [] | |
| total_words = 0 | |
| total_bytes = 0 | |
| total_zero = 0 | |
| for lang in present: | |
| words = load_words(freq_dir, lang) | |
| bin_path = DATA_DIR / f"{lang}.int8.vector" | |
| words_path = DATA_DIR / f"{lang}.words.txt" | |
| size = bin_path.stat().st_size | |
| if size != len(words) * DIM: | |
| raise SystemExit(f"{bin_path}: {size} bytes, expected {len(words) * DIM}") | |
| stat_path = STATS_DIR / f"{lang}.json" | |
| stat = json.loads(stat_path.read_text(encoding="utf-8")) if stat_path.exists() else {} | |
| entry = { | |
| "words": len(words), | |
| "vectors_bytes": size, | |
| "zero_vectors": stat.get("zero_vectors", 0), | |
| "int8_cosine_min": stat.get("int8_cosine_min"), | |
| "backend": stat.get("backend", "llamacpp"), | |
| } | |
| entries[lang] = entry | |
| total_words += len(words) | |
| total_bytes += size | |
| total_zero += entry["zero_vectors"] | |
| for p in (bin_path, words_path): | |
| files.append({ | |
| "file": p.relative_to(ROOT).as_posix(), | |
| "bytes": p.stat().st_size, | |
| "sha256": sha256_file(p), | |
| }) | |
| meta = { | |
| "version": 1, | |
| "generatedAt": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"), | |
| "dataset": "vocabradar/WordEmbedding", | |
| "layout": "data/<lang>.words.txt + data/<lang>.int8.vector", | |
| "model": { | |
| "repo": MODEL_REPO, | |
| "file": MODEL_FILE, | |
| "sha256": MODEL_SHA256, | |
| "base_model": "hotchpotch/bekko-embedding-v1-a25m", | |
| "architecture": "ModernBERT", | |
| "license": "MIT", | |
| "quantization": "BF16", | |
| "active_parameters": 24900000, | |
| "dimension": DIM, | |
| "matryoshka": [256, 128, 64], | |
| "pooling": "mean", | |
| "normalization": "l2", | |
| "context_length": 8192, | |
| "runtime": server_version(Path(args.llama_server)), | |
| }, | |
| "format": { | |
| "words": "UTF-8, one word per line, cleaned wordfreq frequency order", | |
| "vectors": "int8, row-major, N x 384; row i = line i (0-based) of the words file", | |
| "scale": SCALE, | |
| "dequantize": "v = int8 / 127.0 (each row was L2-normalized before quantization)", | |
| "cosine": "dot(q_a, q_b) / 127^2, after casting to float32/int32 (int8 matmul overflows)", | |
| }, | |
| "source": { | |
| "dataset": "vocabradar/wordfreq", | |
| "version": wf_meta.get("version"), | |
| "generatedAt": wf_meta.get("generatedAt"), | |
| }, | |
| "languages": entries, | |
| "totals": { | |
| "languages": len(entries), | |
| "words": total_words, | |
| "vectors_bytes": total_bytes, | |
| "zero_vectors": total_zero, | |
| }, | |
| } | |
| write_atomic(ROOT / "meta.json", | |
| (json.dumps(meta, ensure_ascii=False, indent=2) + "\n").encode("utf-8")) | |
| files.sort(key=lambda x: x["file"]) | |
| write_atomic(ROOT / "files.json", (json.dumps({ | |
| "generatedAt": meta["generatedAt"], | |
| "algorithm": "sha256", | |
| "files": files, | |
| }, ensure_ascii=False, indent=2) + "\n").encode("utf-8")) | |
| log(f"meta.json: {len(entries)} languages, {total_words:,} words, " | |
| f"{total_bytes / 2**30:.2f} GiB") | |
| if not args.no_readme: | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import gen_readme # noqa: E402 (same directory) | |
| gen_readme.main() | |
| def main() -> None: | |
| """Parse arguments and dispatch.""" | |
| global LOG_PATH | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("command", choices=("embed", "finalize", "all")) | |
| ap.add_argument("--langs", nargs="+", help="language codes (default: all in wordfreq)") | |
| ap.add_argument("--queue", default=None, | |
| help="shared queue file, one language per line; workers claim " | |
| "languages one at a time (overrides --langs)") | |
| ap.add_argument("--worker", default=None, | |
| help="worker name recorded in the claim files (queue mode)") | |
| ap.add_argument("--freq-dir", default=str(DEFAULT_FREQ_DIR), | |
| help="directory with small_<lang>.msgpack.gz") | |
| ap.add_argument("--model", default=str(MODELS_DIR / MODEL_FILE), | |
| help="local GGUF path (downloaded from hf-mirror when missing)") | |
| ap.add_argument("--llama-server", default=os.environ.get("LLAMA_SERVER", str(DEFAULT_SERVER)), | |
| help="path to llama-server.exe") | |
| ap.add_argument("--port", type=int, default=DEFAULT_PORT) | |
| ap.add_argument("--batch", type=int, default=2048, help="words per /v1/embeddings request") | |
| ap.add_argument("--ctx", type=int, default=16, help="llama-server context size") | |
| ap.add_argument("--gpu-layers", default="99", | |
| help="llama.cpp -ngl value (99/all for GPU, 0 for CPU)") | |
| ap.add_argument("--threads", type=int, default=0, | |
| help="llama.cpp -t value (0 = server default)") | |
| ap.add_argument("--backend-tag", default=None, | |
| help="label written to meta.json (default: llamacpp-vulkan / llamacpp-cpu)") | |
| ap.add_argument("--verbose-server", action="store_true", | |
| help="keep llama-server per-slot logs (much slower on long runs)") | |
| ap.add_argument("--log-file", default=str(LOG_PATH), help="task log path") | |
| ap.add_argument("--force", action="store_true", help="re-embed even if outputs exist") | |
| ap.add_argument("--allow-partial", action="store_true", | |
| help="finalize with only the languages that have output") | |
| ap.add_argument("--no-readme", action="store_true", help="skip README table regeneration") | |
| args = ap.parse_args() | |
| LOG_PATH = Path(args.log_file) | |
| if args.command in ("embed", "all"): | |
| cmd_embed(args) | |
| if args.command in ("finalize", "all"): | |
| cmd_finalize(args) | |
| if __name__ == "__main__": | |
| main() | |