29  Media-tower LoRA — change, control, round trip, selectivity, and the corrupt-row contract

Verbs: fine_tune(method="lora", task=…, target_modules=…) on an image, a text and an audio tower · encode_query · infer · Background: LoRA — a frozen base weight plus a trainable low-rank update (Hu et al. 2022) — injected into OpenCLIP’s shared vision/text ResidualAttentionBlock (Radford et al. 2021) and into CLAP’s HTSAT-Swin audio tower (Wu et al. 2023) · Checked: measurement (five properties of a tower adapter, each measured live).

Every other fine-tuning chapter trains a text encoder. This one adapts the media towers with the same fine_tune verb: the vision and text towers of one OpenCLIP checkpoint (task= alone chooses which) and the audio tower of a CLAP checkpoint, each with target_modules naming real sites on that tower’s own architecture — in_proj/c_fc on OpenCLIP’s attention block, query/value/linear1 on HTSAT-Swin. At small scale the towers are the committed random-weight fixtures; at full, the real checkpoints. Either way the chapter measures five things, because a single “the vector changed” check leaves four questions open:

  1. Change — the adapter moves the served embedding. Direction and quality are not claimed: the corpora are synthetic shapes and tones with no semantic ground truth.
  2. Control — the same input through the same checkpoint twice is identical, so the change is a parameter delta, not inference noise.
  3. Round trip — the adapter survives the engine closing and a fresh engine opening over the same catalog: it is served from what was saved, not from a process’s warm cache.
  4. Selectivity — adapting one OpenCLIP tower leaves the other’s served embedding untouched.
  5. The corrupt-row contract — in a batch, a null and an undecodable row fail on their own row, and the good row is still served, whether the media column holds bytes or file paths.
import tempfile
from pathlib import Path

import jammi
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from jammi_cookbook import encoders, fixtures, scale
from jammi_cookbook.claims import claim

SCALE = scale.current()
IMAGE_MODEL = encoders.image(SCALE)
AUDIO_MODEL = encoders.audio(SCALE)
work = Path(tempfile.mkdtemp())
home = f"file://{tempfile.mkdtemp()}"
db = jammi.connect(home)

images = {p.stem: p.read_bytes() for p in sorted(fixtures.path("tiny_image_corpus").glob("img_*.png"))}
clips = {p.stem: p.read_bytes() for p in sorted(fixtures.path("tiny_audio_corpus").glob("clip_*.wav"))}
print(f"{len(images)} images, {len(clips)} audio clips")
20 images, 20 audio clips

29.1 Three towers, three adapters

A triplet source supervises each tower: an anchor, a positive of the same kind (the next image of the same shape, the next clip of the same waveform) and a negative of another kind. For the text tower the triplets are short captions of the same shapes.

def kind(name: str) -> str:
    return name.split("_")[1]


def triplets(items: dict) -> dict:
    names = sorted(items)
    rows = {"anchor": [], "positive": [], "negative": []}
    for name in names:
        same = [n for n in names if kind(n) == kind(name) and n != name]
        other = next(n for n in names if kind(n) != kind(name))
        rows["anchor"].append(items[name])
        rows["positive"].append(items[same[0]])
        rows["negative"].append(items[other])
    return rows


captions = {f"cap_{kind(n)}_{i}": f"a {kind(n)} drawn in outline, view {i}"
            for i, n in enumerate(sorted(images))}
for name, rows in [("image_triplets", triplets(images)), ("text_triplets", triplets(captions)),
                   ("audio_triplets", triplets(clips))]:
    pq.write_table(pa.table(rows), work / f"{name}.parquet")
    db.add_source(name, url=str(work / f"{name}.parquet"), format="parquet")

TOWERS = {
    "vision": ("image_triplets", IMAGE_MODEL, "image_embedding", ["in_proj", "c_fc"]),
    "text": ("text_triplets", IMAGE_MODEL, "text_embedding", ["in_proj", "c_fc"]),
    "audio": ("audio_triplets", AUDIO_MODEL, "audio_embedding", ["query", "value", "linear1"]),
}


def adapt(source, base, task, sites) -> str:
    job = db.fine_tune(
        source=source, base_model=base, columns=["anchor", "positive", "negative"],
        method="lora", task=task, target_modules=sites, lora_rank=4, learning_rate=5e-3,
        epochs=2, batch_size=4, validation_fraction=0.0, early_stopping_metric="train_loss",
        seed=0,
    )
    job.wait()
    return job.output_model_id


tuned = {tower: adapt(*spec) for tower, spec in TOWERS.items()}
for tower, model in tuned.items():
    print(f"{tower:<7} -> {model}  ({db.describe_model(model)['task']})")
vision  -> jammi:fine-tuned:23a1e335-f4ae-4ecd-9c6e-e502c20e96a6  (image_embedding)
text    -> jammi:fine-tuned:0eb2e379-1392-4a9a-8ee9-df6ba13ec512  (text_embedding)
audio   -> jammi:fine-tuned:ad6e43e0-a49d-4bbc-9fd2-0aba14b4d4d2  (audio_embedding)

29.2 1 and 2 — the change, against the control

One probe per tower — an image, a caption, a clip — encoded through the base checkpoint twice and through the adapted model once.

PROBES = {
    "vision": ("image", images["img_circle_0"]),
    "text": ("text", "a circle drawn in outline"),
    "audio": ("audio", clips["clip_sine_0"]),
}


def encode(model: str, tower: str) -> np.ndarray:
    modality, probe = PROBES[tower]
    return np.asarray(db.encode_query(model=model, query=probe, modality=modality))


base = {tower: encode(spec[1], tower) for tower, spec in TOWERS.items()}
change, control = {}, {}
for tower, spec in TOWERS.items():
    control[tower] = float(np.abs(encode(spec[1], tower) - base[tower]).max())
    change[tower] = float(np.abs(encode(tuned[tower], tower) - base[tower]).max())
    print(f"{tower:<7} change max|Δ| {change[tower]:.6f}   control max|Δ| {control[tower]:.1f}")
vision  change max|Δ| 0.049073   control max|Δ| 0.0
text    change max|Δ| 0.489702   control max|Δ| 0.0
audio   change max|Δ| 0.699044   control max|Δ| 0.0
claim("the same checkpoint serves the same input bit-identically",
      all(control[tower] == 0.0 for tower in TOWERS))
claim("and each tower's adapter moves its embedding", all(change[tower] > 0.0 for tower in TOWERS),
      ", ".join(f"{tower} {change[tower]:.2e}" for tower in TOWERS))
✓ the same checkpoint serves the same input bit-identically
✓ and each tower's adapter moves its embedding (vision 4.91e-02, text 4.90e-01, audio 6.99e-01)

The control is exactly zero: the same checkpoint serves the same input bit-identically, so every coordinate the adapter moved, it moved.

29.3 3 — the round trip through a fresh engine

The engine is closed — its model cache and every loaded adapter with it — and a new one opens over the same catalog. The adapted models are resolved from the catalog and the adapters reloaded from their saved bundles.

served_before = {tower: encode(tuned[tower], tower) for tower in TOWERS}
db.close()
db = jammi.connect(home)
round_trip = {tower: float(np.abs(encode(tuned[tower], tower) - served_before[tower]).max())
              for tower in TOWERS}
for tower, diff in round_trip.items():
    print(f"{tower:<7} served before vs after the reopen: max|Δ| {diff:.1f}")
vision  served before vs after the reopen: max|Δ| 0.0
text    served before vs after the reopen: max|Δ| 0.0
audio   served before vs after the reopen: max|Δ| 0.0
claim("reloaded by a fresh engine from the catalog, every adapted model serves bit-identically",
      all(diff == 0.0 for diff in round_trip.values()))
✓ reloaded by a fresh engine from the catalog, every adapted model serves bit-identically

29.4 4 — adapting one tower leaves the other alone

The vision and text towers share one checkpoint and one site vocabulary; task= scopes an adapter to one of them. The vision-adapted model’s text embedding of the caption, and the text-adapted model’s image embedding of the image, are each compared with the base checkpoint’s.

selectivity = {
    "vision adapter, text probe": float(np.abs(encode(tuned["vision"], "text") - base["text"]).max()),
    "text adapter, image probe": float(np.abs(encode(tuned["text"], "vision") - base["vision"]).max()),
}
for label, diff in selectivity.items():
    print(f"{label:<28} max|Δ| vs base {diff:.1f}")
vision adapter, text probe   max|Δ| vs base 0.0
text adapter, image probe    max|Δ| vs base 0.0
claim("adapting one tower leaves the other bit-identical", all(diff == 0.0 for diff in selectivity.values()))
✓ adapting one tower leaves the other bit-identical

Bit-identical, not merely close: the untouched tower is served exactly as the base checkpoint serves it. This measures the outcome only — whether because training touched only the tuned tower’s sites or because serving applies an adapter only under its own task, the served embedding of the other tower does not move.

29.5 5 — the corrupt-row contract, in both input arms

A media column arrives either as the encoded bytes or as a path to a file. Each arm gets a batch of three rows: a valid one, a null, and one whose bytes decode as nothing (an existing file of junk). infer returns one row per input with a _status, and a bad row fails on its own row.

junk = work / "junk.bin"
junk.write_bytes(b"not an image and not an audio clip")
good_image, good_clip = work / "good.png", work / "good.wav"
good_image.write_bytes(images["img_circle_0"])
good_clip.write_bytes(clips["clip_sine_0"])

ARMS = {
    ("image", "bytes"): pa.array([images["img_circle_0"], None, junk.read_bytes()], pa.binary()),
    ("image", "path"): pa.array([str(good_image), None, str(junk)], pa.string()),
    ("audio", "bytes"): pa.array([clips["clip_sine_0"], None, junk.read_bytes()], pa.binary()),
    ("audio", "path"): pa.array([str(good_clip), None, str(junk)], pa.string()),
}
contract = {}
for (modality, arm), column in ARMS.items():
    name = f"{modality}_{arm}"
    pq.write_table(pa.table({"id": [0, 1, 2], "media": column}), work / f"{name}.parquet")
    db.add_source(name, url=str(work / f"{name}.parquet"), format="parquet")
    model = IMAGE_MODEL if modality == "image" else AUDIO_MODEL
    out = db.infer(source=name, model=model, columns=["media"], task=f"{modality}_embedding",
                   key="id").sort_by("_row_id")
    contract[name] = list(zip(out.column("_status").to_pylist(), out.column("_error").to_pylist()))
    print(f"{name:<12} " + "  ".join(f"row {i}: {s}" for i, (s, _) in enumerate(contract[name])))
db.close()
image_bytes  row 0: ok  row 1: error  row 2: error
image_path   row 0: ok  row 1: error  row 2: error
audio_bytes  row 0: ok  row 1: error  row 2: error
audio_path   row 0: ok  row 1: error  row 2: error
2026-10-03T07:43:15.085258Z ERROR symphonia_core::probe: probe reach EOF at 34 bytes.
2026-10-03T07:43:15.121550Z ERROR symphonia_core::probe: probe reach EOF at 34 bytes.
for name, rows in contract.items():
    (good, _), (null, null_error), (corrupt, corrupt_error) = rows
    claim(f"{name}: the valid row is served, the null and the corrupt rows refused",
          (good, null, corrupt) == ("ok", "error", "error"))
    claim(f"{name}: each refusal names its row — the null as null, the corrupt by position",
          "null" in null_error.lower() and "row 2" in corrupt_error)
✓ image_bytes: the valid row is served, the null and the corrupt rows refused
✓ image_bytes: each refusal names its row — the null as null, the corrupt by position
✓ image_path: the valid row is served, the null and the corrupt rows refused
✓ image_path: each refusal names its row — the null as null, the corrupt by position
✓ audio_bytes: the valid row is served, the null and the corrupt rows refused
✓ audio_bytes: each refusal names its row — the null as null, the corrupt by position
✓ audio_path: the valid row is served, the null and the corrupt rows refused
✓ audio_path: each refusal names its row — the null as null, the corrupt by position

The valid row is served in every arm; the null row names itself as null; the undecodable row names its own position. A missing path — a file that does not exist — is a different failure: resolving paths to bytes happens before any row is decoded, so it refuses the whole call rather than one row.

29.6 Bridge note

A tower adapter earns its place by five properties, not one. The change is its reason to exist; the control makes that change interpretable; the round trip makes “saved” mean what a fresh engine can serve; selectivity keeps an adapter on its own tower; and the per-row contract keeps one bad input from failing a batch. Each is measured here through the same public surface a caller uses, on random fixtures at small and on real OpenCLIP and CLAP checkpoints at full.

Hu, Edward J., Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, and Weizhu Chen. 2022. “LoRA: Low-Rank Adaptation of Large Language Models.” In International Conference on Learning Representations (ICLR).
Radford, Alec, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, et al. 2021. “Learning Transferable Visual Models from Natural Language Supervision.” In International Conference on Machine Learning (ICML).
Wu, Yusong, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, and Shlomo Dubnov. 2023. “Large-Scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation.” In IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP).