Run image-to-image semantic search over a corpus with an OpenCLIP-format vision model, measure retrieval quality, and adapt the vision tower itself on caller-supplied image triplets.
When to use this pattern. You have a corpus of images (figures, drawings, photos) and want to find the ones most similar to a query image — and a number that tells you how good the retrieval is. This is the image counterpart of the text eval_embeddings recipe.
5.1 Model
A domain-specialized CLIP checkpoint is a drop-in for the reference model when your corpus is technical drawings or diagrams rather than photographs — a generic CLIP has seen few of them, and a checkpoint tuned on that kind of imagery separates them far better. patentclip/PatentCLIP_Vit_B on the Hugging Face Hub is one such checkpoint:
patentclip/PatentCLIP_Vit_B is pulled from the Hugging Face Hub on first use and produces 512-dim L2-normalized embeddings. Any OpenCLIP-format model works the same way — OpenAI CLIP, LAION CLIP-ViT-B-32-*, EVA-CLIP, etc. — the encoder is auto-detected from the model’s open_clip_config.json.
By default (no env var) the recipe runs against the hermetic cookbook/fixtures/tiny_open_clip fixture so it runs offline in CI — about two seconds on a laptop, nearly all of it the tower-LoRA and refusal legs (the search-and-eval flow alone is a fraction of a second). That fixture has random weights, so its retrieval numbers are meaningless — it exercises the full pipeline, not model quality. Point JAMMI_IMAGE_MODEL at any real checkpoint for real numbers.
Same column shape as text and audio triplets — task="image_embedding" is what tells the loader to read the three columns as encoded images rather than text.
5.2.2 Vision-tower LoRA sites
target_modules names sites on this architecture. The OpenCLIP towers offer in_proj (fused QKV), out_proj, c_fc and c_proj; all-linear selects every one. A selector matches a site name exactly or as a suffix of it. A list matching nothing fails the job with a message that echoes what you submitted and lists the tower’s real names.
5.3 Input schema
column
type
notes
image_id
utf8
per-row key
image
binary
raw PNG/JPEG/TIFF bytes (decoded by the encoder)
Preprocessing (pad-to-square, no center crop, normalization, L2-normalized output) is handled inside the encoder per the model’s preprocess_cfg.
5.4 Golden source shape (image mode)
eval_embeddings switches to image-query mode when the golden source carries a query_image (binary) column instead of query_text:
column
type
example
query_id
utf8
q_circle
query_image
binary
raw PNG bytes of the query image
relevant_id
utf8
img_circle_0 (matches image_id)
5.5 Fixtures
cookbook/fixtures/tiny_image_corpus/ — 20 synthetic 224×224 PNGs in 5 shape families (circle / triangle / square / hexagon / grating), 4 per family, plus a held-out query image per family under queries/. Rendered programmatically by cookbook/fixtures/generate.py — no real-world imagery (licensing).
cookbook/fixtures/tiny_image_golden.json — per-query → expected corpus IDs (same shape family).
cookbook/fixtures/tiny_open_clip/ — tiny offline OpenCLIP fixture used as the default CI model.
JAMMI_IMAGE_MODEL names the checkpoint, any OpenCLIP-format model id or local:<path>; the default is the random-weight tiny_open_clip fixture, which runs offline in seconds.
The corpus is 20 synthetic 224×224 PNGs in five shape families, held inline as bytes in a Parquet source: image_id, and image with the raw PNG.
paths =sorted(IMAGE_CORPUS_DIR.glob("img_*.png"))assert paths, f"no corpus images under {IMAGE_CORPUS_DIR}"pq.write_table( pa.table( {"image_id": pa.array([p.stem for p in paths], type=pa.utf8()),"image": pa.array([p.read_bytes() for p in paths], type=pa.binary()), } ), home /"corpus.parquet",)db.add_source("corpus", url=str(home /"corpus.parquet"), format="parquet")
5.7 Embed them
generate_embeddings with modality="image" runs the vision tower over the image column. The encoder is read from the checkpoint’s OpenCLIP config, preprocesses each image as the model’s preprocess_cfg says, and writes L2-normalized vectors.
The golden set holds a held-out query image per family and the corpus images of that family. A query_image (binary) column in place of query_text is what switches eval_embeddings to image queries. The numbers are reported, not judged: the fixture’s weights are random, and a real checkpoint is where they mean something.
query_ids, query_images, relevant_ids = [], [], []for q in json.loads(fixtures.path("tiny_image_golden.json").read_text()): image_bytes = (IMAGE_CORPUS_DIR / q["query_image"]).read_bytes()for rid in q["relevant_ids"]: query_ids.append(q["query_id"]) query_images.append(image_bytes) relevant_ids.append(str(rid))pq.write_table( pa.table( {"query_id": pa.array(query_ids, type=pa.utf8()),"query_image": pa.array(query_images, type=pa.binary()),"relevant_id": pa.array(relevant_ids, type=pa.utf8()), } ), home /"golden.parquet",)db.add_source("golden", url=str(home /"golden.parquet"), format="parquet")metrics = db.eval_embeddings(source="corpus", golden_source="golden.public.golden", k=5)for key in ("recall_at_k", "precision_at_k", "mrr", "ndcg"): value = metrics["aggregate"][key]assert0.0<= value <=1.0, f"{key} out of range: {value}"print(f"{key:<16}{value:.4f}")assertlen(metrics["per_query"]) >0, "per_query must carry one record per query"
(anchor, positive, negative) image triplets: for each image, the positive is the next image of its family and the negative an image of another family. What makes an image a “positive” — a redraw, another view of the same object, an augmentation — is the caller’s data; the trainer only minimizes the triplet loss over whatever images are paired.
A non-empty target_modules puts LoRA inside the vision transformer itself: in_proj is its fused query-key-value projection and c_fc the MLP’s first linear, so the tower’s own representation moves. (The audio recipe shows the other mode: an empty list trains a projection head on a frozen tower.) The adapted model is registered under the image task, so search resolves it as an image encoder.
job = db.fine_tune( source="triplets", base_model=MODEL, columns=["anchor", "positive", "negative"], method="lora", task="image_embedding", target_modules=["in_proj", "c_fc"], lora_rank=4, learning_rate=5e-3, epochs=2, batch_size=4, warmup_steps=0, validation_fraction=0.0, early_stopping_metric="train_loss",)job.wait()tuned_model = job.output_model_idassert tuned_model.startswith("jammi:fine-tuned:"), f"unexpected model_id: {tuned_model}"print(f"fine-tuned image model: {tuned_model}")described = db.describe_model(tuned_model)assert described isnotNone, f"{tuned_model} missing from the catalog"assert described["task"] =="image_embedding", f"registered under the wrong task: {described}"
The same query image, encoded through the adapted model, must come out different from the base encoding: an adapter that trained but was dropped at serve time would leave the two vectors identical. This checks change, not improvement — the fixture’s weights are random, so the direction of the change carries no information — and it checks the vectors rather than top-k metrics, which on a set this small rarely flip even when the vectors move.
tuned_query_vec = db.encode_query(model=tuned_model, query=query_png, modality="image")assertlen(tuned_query_vec) ==len(query_vec), (f"tuned dim {len(tuned_query_vec)} differs from base dim {len(query_vec)}")max_abs_diff =max(abs(b - t) for b, t inzip(query_vec, tuned_query_vec))print(f"query embedding max |Δ| (base vs tuned): {max_abs_diff:.6f}")assert max_abs_diff >1e-4, (f"the tuned query vector equals the base one (max |Δ| = {max_abs_diff:.2e}): ""the adapter was trained but is not applied when the model is served")
query embedding max |Δ| (base vs tuned): 0.008759
5.13 A selector that matches nothing is refused
q_proj is a real site on many decoder checkpoints and on nothing in an OpenCLIP tower. Selecting no site would train zero parameters and publish an adapter that changes nothing, so the engine fails the job instead, and the message names this tower’s real sites.
refused = db.fine_tune( source="triplets", base_model=MODEL, columns=["anchor", "positive", "negative"], method="lora", task="image_embedding", target_modules=["q_proj"], lora_rank=4, epochs=1, batch_size=4, warmup_steps=0, validation_fraction=0.0, early_stopping_metric="train_loss",)try: refused.wait()except TrainingError as error: message =str(error)print(f"refused: {message}")assert"q_proj"in message, f"the refusal must echo the submitted selector: {message}"assert"in_proj"in message, f"the refusal must name this tower's real sites: {message}"else:raiseAssertionError("a target_modules list matching no site must fail the job")
refused: Fine-tune error: target_modules ["q_proj"] matched no LoRA site on the 'open_clip' vision tower (base model 'local:/__w/jammi-ai/jammi-ai/cookbook/book/jammi_cookbook/_fixtures/tiny_open_clip', model_type '<absent>'), so this job would train zero parameters and publish an adapter that changes nothing. This tower's own LoRA site names are: ["in_proj", "out_proj", "c_fc", "c_proj"] — a selector matches a site name exactly or as a suffix of it (so 'query' selects 'attention.self.query' on a BERT-family tower, whose sites are named by their full dotted checkpoint path), and 'all-linear' selects every site.
2026-10-03T07:44:13.982657Z ERROR jammi_ai::fine_tune::worker: training job failed job_id=5a5f4151-8c39-464d-a7e4-67d075e73ec7 error=Fine-tune error: target_modules ["q_proj"] matched no LoRA site on the 'open_clip' vision tower (base model 'local:/__w/jammi-ai/jammi-ai/cookbook/book/jammi_cookbook/_fixtures/tiny_open_clip', model_type '<absent>'), so this job would train zero parameters and publish an adapter that changes nothing. This tower's own LoRA site names are: ["in_proj", "out_proj", "c_fc", "c_proj"] — a selector matches a site name exactly or as a suffix of it (so 'query' selects 'attention.self.query' on a BERT-family tower, whose sites are named by their full dotted checkpoint path), and 'all-linear' selects every site.