Files
alzeo/vectors-check.py
T

86 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""Whether a CPU embedding lane gives the vectors its model is published with: the proof of install-clipstral.sh and
install-embeddings.sh, and a check for anyone.
vectors-check.py http://127.0.0.1:30030 clipstral-reference.json
vectors-check.py http://127.0.0.1:30028 pplx-reference.json
A reference holds texts, and images for a model that reads them, each with the vector that what its `by` names gave for it, in
float32, at the revision it names (docs/clipstral-lane.md and docs/embed-lane.md say how each was made). They are asked in one
request, mixed, as a client would; each vector that comes back must have the reference's dimensions, norm 1, and a cosine with
its reference at or above `least`, a text's and an image's apart. One line each, 0 when all of them do. A box's key, for a proxy,
is read from the environment (VECTORS_KEY), never from the command line. Standard library only.
"""
import base64
import json
import math
import os
import struct
import sys
import urllib.error
import urllib.request
def floats(b64):
raw = base64.b64decode(b64)
if len(raw) % 4:
raise ValueError(f"{len(raw)} bytes, not float32s")
return struct.unpack(f"<{len(raw) // 4}f", raw)
def cosine(a, b):
return math.fsum(x * y for x, y in zip(a, b)) / math.sqrt(math.fsum(x * x for x in a) * math.fsum(y * y for y in b))
def check(base, ref, say=print, timeout=300):
"""True when every reference comes back."""
images, by = ref.get("images", []), ref.get("by", "the published code")
asked = [t["text"] for t in ref["texts"]] + [{"type": "image_url", "image_url": "data:image/png;base64," + i["png"]}
for i in images]
names = [repr(t["text"][:40]) for t in ref["texts"]] + [i["name"] for i in images]
want = [floats(x["vector"]) for x in (*ref["texts"], *images)]
least = [ref["least"]["texts"]] * len(ref["texts"]) + [ref["least"].get("images", 1)] * len(images)
headers = {"Content-Type": "application/json"}
if os.environ.get("VECTORS_KEY"):
headers["Authorization"] = "Bearer " + os.environ["VECTORS_KEY"]
req = urllib.request.Request(base.rstrip("/") + "/v1/embeddings", headers=headers, data=json.dumps(
{"model": ref["model"], "input": asked, "encoding_format": "base64"}).encode())
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
d = json.load(r)
except urllib.error.HTTPError as e:
say(f" HTTP {e.code}: {e.read(300).decode(errors='replace')}")
return False
except (OSError, ValueError) as e:
say(f" no answer: {type(e).__name__}: {e}")
return False
if d.get("model") != ref["model"]:
say(f" the model that answered is {d.get('model')!r}, not {ref['model']}")
return False
got = {x.get("index"): x.get("embedding") for x in d.get("data") or []}
ok = len(got) == len(asked)
if not ok:
say(f" {len(got)} vectors for {len(asked)} inputs")
for i, (name, w, floor) in enumerate(zip(names, want, least)):
try:
v = floats(got[i])
if len(v) != len(w):
raise ValueError(f"{len(v)} values")
norm = math.sqrt(math.fsum(x * x for x in v))
c = cosine(v, w) if norm else 0.0
except (KeyError, TypeError, ValueError) as e:
say(f" {name}: {type(e).__name__}: {e}")
ok = False
continue
good = c >= floor and abs(norm - 1) < 1e-3
ok = ok and good
say(f" {'ok ' if good else 'NOT'} cosine {c:.6f} with {by}, {name}")
return ok
if __name__ == "__main__":
if len(sys.argv) != 3:
raise SystemExit(__doc__)
with open(sys.argv[2], encoding="utf-8") as fh:
raise SystemExit(0 if check(sys.argv[1], json.load(fh)) else 1)