Download rlm_vec.py from Haster1137/AI_Forum: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/datasets/Haster1137/AI_Forum/resolve/main/rlm_vec.py
- Command line
-
hf download hf://datasets/Haster1137/AI_Forum/rlm_vec.py
-
curl -L -o rlm_vec.py https://huggingface.co/datasets/Haster1137/AI_Forum/resolve/main/rlm_vec.py
15.6 kB
| """ | |
| rlm_vec.py - vector math and context-inspection helpers for the RLM REPL. | |
| Pure Python, no third-party imports, so it works on a bare install. Everything | |
| public here is injected into the REPL namespace by rlm_core, which means the | |
| model can call these directly from code it writes (and build on them). | |
| Vectors are plain lists of floats; matrices are lists of rows. | |
| """ | |
| import json | |
| import math | |
| import random | |
| import re | |
| import zlib | |
| # --------------------------------------------------------------------------- | |
| # Vector / matrix primitives | |
| # --------------------------------------------------------------------------- | |
| def dot(a, b): | |
| return sum(x * y for x, y in zip(a, b)) | |
| def norm(a): | |
| return math.sqrt(sum(x * x for x in a)) | |
| def normalize(a): | |
| n = norm(a) | |
| return [x / n for x in a] if n else list(a) | |
| def add(a, b): | |
| return [x + y for x, y in zip(a, b)] | |
| def sub(a, b): | |
| return [x - y for x, y in zip(a, b)] | |
| def scale(a, k): | |
| return [x * k for x in a] | |
| def mean(vecs): | |
| vecs = list(vecs) | |
| if not vecs: | |
| return [] | |
| n = len(vecs) | |
| return [sum(col) / n for col in zip(*vecs)] | |
| def cosine(a, b): | |
| na, nb = norm(a), norm(b) | |
| return dot(a, b) / (na * nb) if na and nb else 0.0 | |
| def euclid(a, b): | |
| return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) | |
| def transpose(m): | |
| return [list(r) for r in zip(*m)] | |
| def matmul(a, b): | |
| bt = transpose(b) | |
| return [[dot(row, col) for col in bt] for row in a] | |
| def matvec(m, v): | |
| return [dot(row, v) for row in m] | |
| def softmax(a, temperature=1.0): | |
| if not a: | |
| return [] | |
| t = float(temperature) or 1.0 | |
| top = max(a) | |
| exps = [math.exp((x - top) / t) for x in a] | |
| total = sum(exps) | |
| return [e / total for e in exps] | |
| def solve(a, b): | |
| """Solve a x = b by Gaussian elimination with partial pivoting.""" | |
| n = len(a) | |
| m = [list(map(float, row)) + [float(b[i])] for i, row in enumerate(a)] | |
| for col in range(n): | |
| piv = max(range(col, n), key=lambda r: abs(m[r][col])) | |
| if abs(m[piv][col]) < 1e-12: | |
| raise ValueError("matrix is singular") | |
| m[col], m[piv] = m[piv], m[col] | |
| for r in range(col + 1, n): | |
| f = m[r][col] / m[col][col] | |
| if f: | |
| for c in range(col, n + 1): | |
| m[r][c] -= f * m[col][c] | |
| x = [0.0] * n | |
| for r in range(n - 1, -1, -1): | |
| x[r] = (m[r][n] - sum(m[r][c] * x[c] for c in range(r + 1, n))) / m[r][r] | |
| return x | |
| def linreg(xs, ys, ridge=1e-9): | |
| """Least squares with intercept. xs: rows of features. Returns (weights, bias).""" | |
| rows = [list(map(float, r)) + [1.0] for r in xs] | |
| d = len(rows[0]) | |
| ata = [[sum(r[i] * r[j] for r in rows) + (ridge if i == j else 0.0) | |
| for j in range(d)] for i in range(d)] | |
| atb = [sum(r[i] * y for r, y in zip(rows, ys)) for i in range(d)] | |
| w = solve(ata, atb) | |
| return w[:-1], w[-1] | |
| def power_iter(m, iters=100, seed=0): | |
| """Dominant eigenvalue and eigenvector of a square matrix.""" | |
| rnd = random.Random(seed) | |
| v = normalize([rnd.random() + 0.1 for _ in m]) | |
| val = 0.0 | |
| for _ in range(iters): | |
| w = matvec(m, v) | |
| val = norm(w) | |
| if not val: | |
| break | |
| v = [x / val for x in w] | |
| return val, v | |
| def pca(vecs, k=2, iters=60, seed=0): | |
| """ | |
| Top-k principal axes by power iteration on the implicit covariance. | |
| Returns (components, projected) where projected is each row in k dims. | |
| """ | |
| vecs = [list(map(float, v)) for v in vecs] | |
| mu = mean(vecs) | |
| x = [sub(v, mu) for v in vecs] | |
| rnd = random.Random(seed) | |
| comps = [] | |
| for _ in range(max(1, int(k))): | |
| v = normalize([rnd.random() - 0.5 for _ in mu]) | |
| for _ in range(iters): | |
| w = [0.0] * len(v) | |
| for row in x: | |
| s = dot(row, v) | |
| if s: | |
| for i, r in enumerate(row): | |
| w[i] += s * r | |
| for c in comps: | |
| p = dot(w, c) | |
| w = [wi - p * ci for wi, ci in zip(w, c)] | |
| n = norm(w) | |
| if not n: | |
| break | |
| v = [wi / n for wi in w] | |
| comps.append(v) | |
| x = [sub(row, scale(v, dot(row, v))) for row in x] | |
| base = [sub(v, mu) for v in vecs] | |
| return comps, [[dot(row, c) for c in comps] for row in base] | |
| def kmeans(vecs, k=3, iters=25, seed=0): | |
| """Lloyd's algorithm with k-means++ seeding. Returns (labels, centroids).""" | |
| vecs = [list(map(float, v)) for v in vecs] | |
| n = len(vecs) | |
| if not n: | |
| return [], [] | |
| k = max(1, min(int(k), n)) | |
| rnd = random.Random(seed) | |
| cents = [vecs[rnd.randrange(n)]] | |
| while len(cents) < k: | |
| d2 = [min(euclid(v, c) ** 2 for c in cents) for v in vecs] | |
| total = sum(d2) | |
| if not total: | |
| cents.append(vecs[rnd.randrange(n)]) | |
| continue | |
| pick, acc = rnd.random() * total, 0.0 | |
| for v, d in zip(vecs, d2): | |
| acc += d | |
| if acc >= pick: | |
| cents.append(v) | |
| break | |
| else: | |
| cents.append(vecs[-1]) | |
| labels = [0] * n | |
| for _ in range(iters): | |
| changed = False | |
| for i, v in enumerate(vecs): | |
| best = min(range(k), key=lambda c: euclid(v, cents[c])) | |
| if best != labels[i]: | |
| labels[i], changed = best, True | |
| for c in range(k): | |
| members = [vecs[i] for i in range(n) if labels[i] == c] | |
| if members: | |
| cents[c] = mean(members) | |
| if not changed: | |
| break | |
| return labels, cents | |
| def topk(query, vecs, k=5): | |
| """Indices and cosine scores of the k rows most similar to query.""" | |
| scored = sorted(((cosine(query, v), i) for i, v in enumerate(vecs)), | |
| reverse=True)[:max(0, int(k))] | |
| return [(i, round(s, 4)) for s, i in scored] | |
| # --------------------------------------------------------------------------- | |
| # Text -> vector (feature hashing; deterministic, no model, no download) | |
| # --------------------------------------------------------------------------- | |
| _WORD = re.compile(r"[A-Za-z0-9_]+") | |
| def embed(text, dim=256): | |
| """Signed-hash bag of words + character trigrams, L2-normalised.""" | |
| dim = max(8, int(dim)) | |
| counts = {} | |
| for word in _WORD.findall(str(text).lower()): | |
| counts[("w", word)] = counts.get(("w", word), 0) + 1 | |
| padded = "<%s>" % word | |
| for i in range(len(padded) - 2): | |
| key = ("t", padded[i:i + 3]) | |
| counts[key] = counts.get(key, 0) + 1 | |
| vec = [0.0] * dim | |
| for (kind, tok), c in counts.items(): | |
| h = zlib.crc32(tok.encode("utf-8")) | |
| sign = 1.0 if (h >> 31) & 1 else -1.0 | |
| vec[h % dim] += sign * math.log1p(c) * (1.0 if kind == "w" else 0.4) | |
| return normalize(vec) | |
| def embed_many(texts, dim=256): | |
| return [embed(t, dim) for t in texts] | |
| def bm25_rank(query, docs, k=5, k1=1.5, b=0.75): | |
| """Lexical ranking. Returns [(index, score)] best first.""" | |
| toks = [_WORD.findall(str(d).lower()) for d in docs] | |
| q = set(_WORD.findall(str(query).lower())) | |
| n = len(toks) | |
| if not n or not q: | |
| return [] | |
| avg = (sum(len(t) for t in toks) / n) or 1.0 | |
| df = {w: sum(1 for t in toks if w in t) for w in q} | |
| out = [] | |
| for i, t in enumerate(toks): | |
| score = 0.0 | |
| for w in q: | |
| if not df[w]: | |
| continue | |
| tf = t.count(w) | |
| idf = math.log(1 + (n - df[w] + 0.5) / (df[w] + 0.5)) | |
| score += idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * len(t) / avg)) | |
| out.append((i, round(score, 4))) | |
| out.sort(key=lambda p: -p[1]) | |
| return out[:max(0, int(k))] | |
| class VectorIndex: | |
| """A small persistent semantic index: add(text, meta), search(query, k).""" | |
| def __init__(self, dim=256, path=None): | |
| self.dim = int(dim) | |
| self.path = path | |
| self.items = [] # dicts: id, text, meta, vec | |
| if path: | |
| self.load(path) | |
| def __len__(self): | |
| return len(self.items) | |
| def add(self, text, meta=None, item_id=None): | |
| item = {"id": item_id if item_id is not None else len(self.items), | |
| "text": str(text), "meta": meta or {}, | |
| "vec": embed(text, self.dim)} | |
| self.items.append(item) | |
| return item["id"] | |
| def search(self, query, k=5, min_score=0.0): | |
| q = embed(query, self.dim) | |
| scored = sorted(((cosine(q, it["vec"]), n) for n, it in enumerate(self.items)), | |
| reverse=True)[:max(0, int(k))] | |
| return [dict(score=round(s, 4), **{x: self.items[n][x] for x in ("id", "text", "meta")}) | |
| for s, n in scored if s >= min_score] | |
| def save(self, path=None): | |
| path = path or self.path | |
| if not path: | |
| raise ValueError("no path to save to") | |
| slim = [dict(it, vec=[round(x, 4) for x in it["vec"]]) for it in self.items] | |
| with open(path, "w", encoding="utf-8") as fh: | |
| json.dump({"dim": self.dim, "items": slim}, fh) | |
| return path | |
| def load(self, path): | |
| try: | |
| with open(path, "r", encoding="utf-8") as fh: | |
| data = json.load(fh) | |
| except (OSError, ValueError): | |
| return False | |
| self.dim = int(data.get("dim", self.dim)) | |
| self.items = list(data.get("items", [])) | |
| return True | |
| # --------------------------------------------------------------------------- | |
| # Context inspection: treat a huge string as an environment, not a prompt | |
| # --------------------------------------------------------------------------- | |
| _HEAD_PATTERNS = [ | |
| re.compile(r"^\s{0,3}#{1,6}\s+\S"), # markdown | |
| re.compile(r"^\s*(def|class|function|fn|func|public|private|static)\s+\w+"), | |
| re.compile(r"^\s*(chapter|section|part|article|appendix)\b", re.I), | |
| re.compile(r"^\s*\d+(\.\d+)*[.)]?\s+[A-Z][^\n]{2,70}$"), # 1.2 Title | |
| re.compile(r"^[A-Z][A-Z0-9 _:/-]{5,60}$"), # ALL CAPS LINE | |
| ] | |
| class Ctx: | |
| """Read-only inspection helpers over one big string.""" | |
| def __init__(self, text, name="context"): | |
| self.text = text if isinstance(text, str) else str(text) | |
| self.name = name | |
| self._lines = None | |
| self._starts = None | |
| def __len__(self): | |
| return len(self.text) | |
| def __repr__(self): | |
| return "<Ctx %s: %d chars, %d lines>" % (self.name, len(self.text), len(self.lines)) | |
| def lines(self): | |
| if self._lines is None: | |
| self._lines = self.text.split("\n") | |
| return self._lines | |
| def _line_starts(self): | |
| if self._starts is None: | |
| pos, starts = 0, [] | |
| for ln in self.lines: | |
| starts.append(pos) | |
| pos += len(ln) + 1 | |
| self._starts = starts | |
| return self._starts | |
| def line_of(self, offset): | |
| """1-based line number containing a character offset.""" | |
| import bisect | |
| return bisect.bisect_right(self._line_starts(), max(0, int(offset))) | |
| def stats(self): | |
| words = len(self.text.split()) | |
| return {"chars": len(self.text), "lines": len(self.lines), "words": words, | |
| "approx_tokens": round(len(self.text) / 3.6), | |
| "longest_line": max((len(l) for l in self.lines), default=0), | |
| "blank_lines": sum(1 for l in self.lines if not l.strip())} | |
| def peek(self, start=0, n=800): | |
| start = max(0, int(start)) | |
| return self.text[start:start + int(n)] | |
| def head(self, n=800): | |
| return self.text[:int(n)] | |
| def tail(self, n=800): | |
| return self.text[-int(n):] if n else "" | |
| def slice_lines(self, a, b=None): | |
| """Lines a..b (1-based, inclusive) joined back together.""" | |
| a = max(1, int(a)) | |
| b = int(b) if b is not None else a | |
| return "\n".join(self.lines[a - 1:b]) | |
| def grep(self, pattern, width=80, limit=40, flags=re.I): | |
| """Regex search. Returns [(offset, line_no, snippet)].""" | |
| out = [] | |
| try: | |
| rx = re.compile(pattern, flags) | |
| except re.error: | |
| rx = re.compile(re.escape(pattern), flags) | |
| for m in rx.finditer(self.text): | |
| a = max(0, m.start() - width) | |
| b = min(len(self.text), m.end() + width) | |
| out.append((m.start(), self.line_of(m.start()), | |
| self.text[a:b].replace("\n", " "))) | |
| if len(out) >= limit: | |
| break | |
| return out | |
| def count(self, pattern, flags=re.I): | |
| try: | |
| return len(re.findall(pattern, self.text, flags)) | |
| except re.error: | |
| return self.text.lower().count(str(pattern).lower()) | |
| def between(self, start_pat, end_pat, flags=re.I | re.S, maxlen=20000): | |
| m = re.search("(" + start_pat + ").*?(" + end_pat + ")", self.text, flags) | |
| return m.group(0)[:maxlen] if m else "" | |
| def chunk(self, size=8000, overlap=200): | |
| """Split into <=size pieces, preferring newline boundaries.""" | |
| size = max(200, int(size)) | |
| overlap = max(0, min(int(overlap), size // 2)) | |
| n, pos, out = len(self.text), 0, [] | |
| while pos < n: | |
| end = min(pos + size, n) | |
| if end < n: | |
| cut = self.text.rfind("\n", pos + size // 2, end) | |
| if cut != -1: | |
| end = cut + 1 | |
| out.append(self.text[pos:end]) | |
| if end >= n: | |
| break | |
| pos = max(end - overlap, pos + 1) | |
| return out | |
| def outline(self, limit=60): | |
| """Likely headings / definitions as [(line_no, text)].""" | |
| out = [] | |
| for i, ln in enumerate(self.lines, 1): | |
| if len(ln) > 120 or not ln.strip(): | |
| continue | |
| if any(p.match(ln) for p in _HEAD_PATTERNS): | |
| out.append((i, ln.strip())) | |
| if len(out) >= limit: | |
| break | |
| return out | |
| def sample(self, n=5, width=300, seed=0): | |
| rnd = random.Random(seed) | |
| if len(self.text) <= width: | |
| return [self.text] | |
| return [self.text[p:p + width] | |
| for p in sorted(rnd.randrange(0, len(self.text) - width) for _ in range(n))] | |
| def top_terms(self, n=25, min_len=4): | |
| stop = set("that this with from have they will would there their about which " | |
| "were been into than then them some what when your more also only".split()) | |
| freq = {} | |
| for w in _WORD.findall(self.text.lower()): | |
| if len(w) >= min_len and w not in stop: | |
| freq[w] = freq.get(w, 0) + 1 | |
| return sorted(freq.items(), key=lambda p: -p[1])[:n] | |
| def rank(self, query, chunks=None, k=5, dim=256): | |
| """Semantic top-k over chunks (default: 4000-char chunks of this context).""" | |
| chunks = chunks if chunks is not None else self.chunk(4000, 200) | |
| q = embed(query, dim) | |
| scored = topk(q, [embed(c, dim) for c in chunks], k) | |
| return [(i, s, chunks[i]) for i, s in scored] | |
| def lexical(self, query, chunks=None, k=5): | |
| chunks = chunks if chunks is not None else self.chunk(4000, 200) | |
| return [(i, s, chunks[i]) for i, s in bm25_rank(query, chunks, k)] | |
| VEC_API = {n: globals()[n] for n in ( | |
| "dot", "norm", "normalize", "add", "sub", "scale", "mean", "cosine", "euclid", | |
| "transpose", "matmul", "matvec", "softmax", "solve", "linreg", "power_iter", | |
| "pca", "kmeans", "topk", "embed", "embed_many", "bm25_rank", "VectorIndex", "Ctx")} | |