Encoder: apply the Llama-3 chat header explicitly, and pin the identity at the worker's call site

The child wraps every text with text_encoding.chat_header and tokenizes it itself, so the prompt form no
longer rides on the model's _name_or_path. The identity names the assembly truthfully (header form
included, as a hash of the template) and re-keys the cache. The worker builds its identity through
live_identity and installed_versions, which the tests reach; the identity test now uses live-length
revisions, so a truncated identity or key fails. An env-gated test compares a fresh child vector with
Kimodo's own encoder loaded from the repo ids.

Supersedes encoder-assembly-b (motion-pipeline:ruling:encoder-chat-header-on).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-23 17:20:01 +02:00
commit 4fe1fc963c
4 changed files with 155 additions and 49 deletions

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python3
import argparse
import hashlib
import json
import os
import shutil
@ -10,10 +9,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Lock
from types import SimpleNamespace
import accelerate
import peft
import torch
import transformers
from huggingface_hub.constants import HF_HOME
from kimodo import DEFAULT_MODEL, load_model
@ -51,20 +47,8 @@ model_load_started_at = time.time()
preset = TEXT_ENCODER_PRESETS["llm2vec"]["kwargs"]
kimodo_commit = os.environ["VILI_KIMODO_COMMIT"]
python_env = os.environ["VILI_PYTHON_ENV"]
encoder_identity = text_encoding.encoder_identity(
assembly=text_encoding.ASSEMBLY,
device=device,
revisions={
repo: text_encoding.read_snapshot_revision(HF_HOME, repo)
for repo in (preset["base_model_name_or_path"], preset["peft_model_name_or_path"], text_encoding.LLAMA_BASE)
},
dtype=preset["dtype"],
torch_version=torch.__version__,
transformers_version=transformers.__version__,
peft_version=peft.__version__,
accelerate_version=accelerate.__version__,
kimodo_commit=kimodo_commit,
loader_sha256=hashlib.sha256(text_encoding.CHILD_PATH.read_bytes()).hexdigest(),
encoder_identity = text_encoding.live_identity(
HF_HOME, preset, kimodo_commit, text_encoding.installed_versions(),
)
# The 8B encoder never lives here: misses go to a one-shot child (kimodo-text-encode.py), hits come from the store.
text_encoder = text_encoding.CachedTextEncoder(

View file

@ -1,8 +1,7 @@
#!/usr/bin/env python3
"""One-shot Kimodo text encoder: texts on stdin, vectors in --out, then exit so the OS reclaims its RAM.
Reads {"texts": [...]} as JSON on stdin. Loads LLM2Vec assembly B on CPU in bfloat16, encodes each text alone as
LLM2VecEncoder does, and writes a MessagePack answer. The torch thread budget is VILI_THREADS.
Reads {"texts": [...]} as JSON on stdin. Loads the LLM2Vec encoder on CPU in bfloat16, wraps each text in the Llama-3 chat header, encodes it alone, and writes a MessagePack answer. The torch thread budget is VILI_THREADS.
"""
import json
import os
@ -15,7 +14,7 @@ import msgpack
import torch
sys.path.insert(0, str(Path(__file__).resolve().parent))
from text_encoding import ASSEMBLY, EMBEDDING_DIM, LLAMA_BASE, apply_thread_cap, snapshot_path # noqa: E402
from text_encoding import ASSEMBLY, EMBEDDING_DIM, LLAMA_BASE, apply_thread_cap, chat_header, snapshot_path # noqa: E402
from peft import PeftModel # noqa: E402
from transformers import AutoConfig, AutoTokenizer # noqa: E402
@ -25,14 +24,11 @@ from kimodo.model.load_model import TEXT_ENCODER_PRESETS # noqa: E402
def load_encoder(hf_home, mntp_id, supervised_id, dtype):
"""Assembly B: the Llama base with the MNTP adapter merged in, then the supervised adapter on top.
"""The Llama base with the MNTP adapter merged in, then the supervised adapter on top (motion-pipeline:ruling:encoder-own-loader).
Kimodo's own LLM2VecEncoder loads the MNTP repo as the base (assembly A); this assembly is ours
(motion-pipeline:ruling:encoder-assembly-b). Everything loads from the local snapshot directories, as the
research's reference vector did: the model's _name_or_path is then a path, not the repo id, so
LLM2Vec.prepare_for_tokenization does not wrap the text in Llama's chat header, which is what separates B's
vector from A's. The identity carries the Kimodo commit and this file's sha256, so a changed loader misses.
"""
Everything loads from the local snapshot directories, so the model's _name_or_path is a path and LLM2Vec never
adds the chat header itself; main() wraps every text with chat_header, so the prompt form is ours and no
side effect of the load decides it. The identity carries the Kimodo commit and this file's sha256."""
llama, mntp, supervised = (snapshot_path(hf_home, repo) for repo in (LLAMA_BASE, mntp_id, supervised_id))
tokenizer = AutoTokenizer.from_pretrained(llama)
tokenizer.pad_token = tokenizer.eos_token
@ -60,7 +56,7 @@ def main() -> int:
vectors, encode_seconds = [], []
for text in texts:
began = time.perf_counter()
features = model.tokenize([model.prepare_for_tokenization(model._convert_to_str("", text))])
features = model.tokenize([chat_header(text)])
with torch.no_grad():
vector = model.forward(features).detach().cpu().to(torch.float32)[0]
assert vector.shape == (EMBEDDING_DIM,)

View file

@ -1,4 +1,7 @@
"""Run inside the Kimodo image: python -m unittest discover -s /opt/vili -p test_text_encoding.py"""
import hashlib
import os
import subprocess
import sys
import tempfile
import textwrap
@ -43,26 +46,82 @@ class Identity(unittest.TestCase):
self.assertNotEqual(te.embedding_key("a", "x"), te.embedding_key("a", "y"))
self.assertNotEqual(te.embedding_key("ab", "x"), te.embedding_key("a", "bx"))
def test_key_is_a_full_sha256_over_the_whole_text(self):
key = te.embedding_key("id", "text a")
self.assertEqual(len(key), 64)
int(key, 16)
self.assertNotEqual(key, te.embedding_key("id", "text b"))
def test_chat_header_is_the_llama3_user_turn(self):
self.assertEqual(te.chat_header(" hello "), "<|start_header_id|>user<|end_header_id|>" + chr(10) * 2 + "hello<|eot_id|>")
form = hashlib.sha256(("<|start_header_id|>user<|end_header_id|>" + chr(10) * 2 + "|<|eot_id|>").encode("utf-8")).hexdigest()
self.assertEqual(te.PROMPT_FORM, "llama3-chat-header:" + form)
def test_every_identity_field_changes_the_key(self):
# The repos' names alone exceed 40 characters, so a key built from a truncated identity cannot tell
# the later fields apart: each field here sits past that point.
base = dict(
assembly=te.ASSEMBLY, device="cpu", revisions={"r/one": "111", "r/two": "222", "r/three": "333"}, dtype="bfloat16",
# Built the way the worker builds it, from a mounted cache with 40-hex revisions, so the first 268 characters
# are the revisions and every other field sits past any prefix a truncated identity could keep.
preset = {"base_model_name_or_path": "McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp", "peft_model_name_or_path":
"McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp-supervised", "dtype": "bfloat16"}
versions = {"torch": "2.5.1+cpu", "transformers": "5.1.0", "peft": "0.18.1", "accelerate": "1.13.0"}
with tempfile.TemporaryDirectory() as home, tempfile.TemporaryDirectory() as bytes_dir:
loader = Path(bytes_dir) / "child.py"
loader.write_bytes(b"one")
repos = [preset["base_model_name_or_path"], preset["peft_model_name_or_path"], te.LLAMA_BASE]
revision = {repo: f"{index}" * 40 for index, repo in enumerate(repos, start=1)}
def write_revision(repo, value):
refs = Path(home) / "hub" / ("models--" + repo.replace("/", "--")) / "refs"
refs.mkdir(parents=True, exist_ok=True)
(refs / "main").write_text(value + chr(10))
for repo in repos:
write_revision(repo, revision[repo])
real_child = te.CHILD_PATH
te.CHILD_PATH = loader
try:
def identity(preset=preset, commit="6bb5848", versions=versions):
return te.live_identity(home, preset, commit, versions)
base = identity()
self.assertGreater(base.index("assembly="), 200)
changed = {
"dtype": identity(preset={**preset, "dtype": "float32"}),
"kimodo": identity(commit="abcdef0"),
**{f"version:{name}": identity(versions={**versions, name: "9.9.9"}) for name in versions},
}
for repo in repos:
write_revision(repo, "f" * 40)
changed[f"revision:{repo}"] = identity()
write_revision(repo, revision[repo])
loader.write_bytes(b"two")
changed["loader"] = identity()
loader.write_bytes(b"one")
self.assertEqual(identity(), base)
finally:
te.CHILD_PATH = real_child
self.assertEqual(len(changed), 9)
for field, other in changed.items():
self.assertNotEqual(te.embedding_key(base, "x"), te.embedding_key(other, "x"), field)
for field in ("assembly", "prompt", "device"):
self.assertIn(f"{field}=", base)
def test_assembly_prompt_and_device_change_the_key(self):
fields = dict(
assembly=te.ASSEMBLY, prompt_form=te.PROMPT_FORM, device="cpu", revisions={"r/one": "1" * 40}, dtype="bfloat16",
torch_version="2.5.1+cpu", transformers_version="5.1.0", peft_version="0.18.1", accelerate_version="1.13.0",
kimodo_commit="6bb5848", loader_sha256="a" * 64,
)
key = te.embedding_key(te.encoder_identity(**base), "x")
changes = dict(
assembly="llm2vec-A", device="other-device", dtype="float32", torch_version="2.6.0+cpu", transformers_version="5.2.0",
peft_version="0.19.0", accelerate_version="1.14.0", kimodo_commit="abcdef0", loader_sha256="b" * 64,
)
for repo in base["revisions"]:
changes[f"revision:{repo}"] = {**base["revisions"], repo: "999"}
self.assertEqual(len(changes), 12)
for field, other in changes.items():
name = "revisions" if field.startswith("revision:") else field
changed = te.embedding_key(te.encoder_identity(**{**base, name: other}), "x")
self.assertNotEqual(key, changed, field)
key = te.embedding_key(te.encoder_identity(**fields), "x")
for name, other in (("assembly", "llm2vec-A"), ("prompt_form", "none"), ("device", "cuda")):
self.assertNotEqual(key, te.embedding_key(te.encoder_identity(**{**fields, name: other}), "x"), name)
def test_installed_versions_are_the_libraries_in_use(self):
import accelerate
import peft
import transformers
self.assertEqual(te.installed_versions(), {
"torch": te.torch.__version__, "transformers": transformers.__version__, "peft": peft.__version__, "accelerate": accelerate.__version__,
})
def test_snapshot_revision_is_read_from_the_mounted_cache(self):
with tempfile.TemporaryDirectory() as home:
@ -179,6 +238,10 @@ class ThreadCap(unittest.TestCase):
source = (Path(te.__file__).with_name("kimodo-text-encode.py")).read_text()
self.assertLess(source.index("apply_thread_cap(os.environ)"), source.index("load_encoder(os.environ"))
def test_the_worker_caps_interop_threads_before_it_loads_the_model(self):
source = (Path(te.__file__).with_name("kimodo-resident-worker.py")).read_text()
self.assertLess(source.index("torch.set_num_interop_threads(1)"), source.index("model, resolved_model = load_model("))
def test_the_worker_applies_the_cap_before_it_loads_the_model(self):
source = (Path(te.__file__).with_name("kimodo-resident-worker.py")).read_text()
self.assertLess(source.index("text_encoding.apply_thread_cap(os.environ)"), source.index("model, resolved_model = load_model("))
@ -208,5 +271,36 @@ class ChildBoundary(unittest.TestCase):
self.assertEqual(len(answer["vectors"]), 2)
REFERENCE_MODELS = os.environ.get("VILI_REFERENCE_MODELS")
ROCK = "A person shakes their fist up and down three times, then thrusts a closed fist forward like a rock."
REFERENCE_CODE = """
import sys, numpy as np
from kimodo.model.load_model import TEXT_ENCODER_PRESETS
from kimodo.model.llm2vec.llm2vec_wrapper import LLM2VecEncoder
kwargs = TEXT_ENCODER_PRESETS["llm2vec"]["kwargs"]
encoder = LLM2VecEncoder(**kwargs, device="cpu")
vector, _ = encoder(sys.argv[2])
np.save(sys.argv[1], vector.float().numpy().reshape(-1))
"""
@unittest.skipUnless(REFERENCE_MODELS, "set VILI_REFERENCE_MODELS to a Hugging Face cache with the three repos (Yggdrasil)")
class ReferenceVector(unittest.TestCase):
"""The encoder child, in a fresh process, against Kimodo's own encoder loaded from the repo ids (which applies the chat header)."""
def test_the_child_vector_matches_kimodo_with_the_chat_header(self):
import numpy as np
env = {**os.environ, "HF_HOME": REFERENCE_MODELS, "HF_HUB_OFFLINE": "1", "VILI_THREADS": os.environ.get("VILI_THREADS", "8")}
with tempfile.TemporaryDirectory() as directory:
reference = Path(directory) / "reference.npy"
subprocess.run([sys.executable, "-c", REFERENCE_CODE, str(reference), ROCK], env=env, check=True)
os.environ.update(env)
ours = np.frombuffer(te.run_child([ROCK], Path(directory) / "answer.mp")["vectors"][0], dtype=np.float32)
expected = np.load(reference)
cosine = float(ours @ expected / (np.linalg.norm(ours) * np.linalg.norm(expected)))
print("cosine to Kimodo from repo ids:", cosine)
self.assertGreaterEqual(cosine, 0.9999)
if __name__ == "__main__":
unittest.main()

View file

@ -26,7 +26,12 @@ EMBEDDING_DIM = 4096
EMBEDDING_BYTES = EMBEDDING_DIM * 4
CHILD_PATH = Path(__file__).with_name("kimodo-text-encode.py")
LLAMA_BASE = "meta-llama/Meta-Llama-3-8B-Instruct" # the base model both LLM2Vec adapters are applied to
ASSEMBLY = "llm2vec-B-mntp-merged-then-supervised"
ASSEMBLY = "llm2vec-mntp-merged-then-supervised"
# Llama-3 Instruct's chat header, applied by Vili's own code (motion-pipeline:ruling:encoder-chat-header-on): the
# text goes in as a user turn, as LLM2Vec does for this model when it is loaded from the repo id.
CHAT_HEADER_PREFIX = "<|start_header_id|>user<|end_header_id|>\n\n"
CHAT_HEADER_SUFFIX = "<|eot_id|>"
PROMPT_FORM = "llama3-chat-header:" + hashlib.sha256((CHAT_HEADER_PREFIX + "|" + CHAT_HEADER_SUFFIX).encode("utf-8")).hexdigest()
MAX_THREADS = 16
@ -55,19 +60,46 @@ def snapshot_path(hf_home: Path, repo_id: str) -> Path:
return Path(hf_home) / "hub" / ("models--" + repo_id.replace("/", "--")) / "snapshots" / read_snapshot_revision(hf_home, repo_id)
def encoder_identity(*, assembly: str, device: str, revisions: dict, dtype: str, torch_version: str, transformers_version: str,
peft_version: str, accelerate_version: str, kimodo_commit: str, loader_sha256: str) -> str:
def chat_header(text: str) -> str:
"""The text as the encoder reads it: a user turn in Llama-3 Instruct's chat format."""
return CHAT_HEADER_PREFIX + text.strip() + CHAT_HEADER_SUFFIX
def encoder_identity(*, assembly: str, prompt_form: str, device: str, revisions: dict, dtype: str, torch_version: str,
transformers_version: str, peft_version: str, accelerate_version: str, kimodo_commit: str,
loader_sha256: str) -> str:
"""The canonical string a vector is keyed under: every input that can change it, in a fixed field order.
Thread count is provenance, not identity; the encoder child's own bytes are, through loader_sha256."""
parts = [f"{repo}@{revision}" for repo, revision in sorted(revisions.items())]
parts += [
f"assembly={assembly}", f"device={device}", f"dtype={dtype}", f"torch={torch_version}", f"transformers={transformers_version}",
f"assembly={assembly}", f"prompt={prompt_form}", f"device={device}", f"dtype={dtype}", f"torch={torch_version}", f"transformers={transformers_version}",
f"peft={peft_version}", f"accelerate={accelerate_version}", f"kimodo={kimodo_commit}", f"loader={loader_sha256}",
]
return ";".join(parts)
def installed_versions() -> dict:
"""The versions of the libraries that load and run the encoder, read from the installed packages."""
import accelerate
import peft
import transformers
return {"torch": torch.__version__, "transformers": transformers.__version__, "peft": peft.__version__, "accelerate": accelerate.__version__}
def live_identity(hf_home, preset: dict, kimodo_commit: str, versions: dict) -> str:
"""The identity the worker keys vectors under: the three snapshot revisions the mounted cache names, the preset's
dtype, the library versions, the Kimodo commit and the sha256 of the encoder child's own bytes."""
repos = (preset["base_model_name_or_path"], preset["peft_model_name_or_path"], LLAMA_BASE)
return encoder_identity(
assembly=ASSEMBLY, prompt_form=PROMPT_FORM, device="cpu",
revisions={repo: read_snapshot_revision(hf_home, repo) for repo in repos},
dtype=preset["dtype"], torch_version=versions["torch"], transformers_version=versions["transformers"],
peft_version=versions["peft"], accelerate_version=versions["accelerate"], kimodo_commit=kimodo_commit,
loader_sha256=hashlib.sha256(CHILD_PATH.read_bytes()).hexdigest(),
)
def embedding_key(identity: str, text: str) -> str:
return hashlib.sha256((identity + "\n" + text).encode("utf-8")).hexdigest()