CLIP and ALIGN: one space for images and words
How two separate encoders learn a shared embedding space from web image–caption pairs: the symmetric contrastive loss, in-batch negatives and their false negatives, the temperature, and what such a space can and can't tell apart.
What runs in CodeSplash
- MM001CLIP Runs in CodeSplash (Experimental)
- MM002ALIGN Explained here
- Image–text search and zero-shot labels (CLIP, SigLIP) Experimental
You will be able to
- Describe a dual encoder and why it makes search fast
- Compute the symmetric contrastive loss on a small similarity matrix
- Explain in-batch negatives and how false negatives arise
- Name the kinds of detail a dual encoder misses
Two encoders, one space
ReadA dual encoderDual encoderTwo separate networks map images and texts into one embedding space, compared by cosine similarity; neither sees the other. has an image network and a text network that never see each other. Each maps its input to a vector of the same length, normalized to length one; an image and a caption match when their cosine similarityCosine similarityThe cosine of the angle between two vectors: 1 for the same direction, 0 for unrelated, −1 for opposite. is high.
Keeping the towers apart is what makes it fast. Embed a million images once; each new text query costs one text pass and a million dot products. The price is that the model can't compare fine details of a particular pair, because the two sides only meet as two vectors.
CLIP: learn from captions
ReadCLIPCLIPA pair of networks trained on web image–caption pairs so that an image and a text about it land close together in one vector space. trained such a pair on 400 million image–caption pairs from the web. In each batch of N pairs it computes all N × N similarities, divides them by a learned temperature and asks each image to pick its own caption among the N, and each caption its own image: a cross-entropy over each row and each column, averaged. This is InfoNCEInfoNCE lossA loss that asks each row to pick out its own corrupted view among the views of every row in the batch. applied in both directions.
In the program, two images and two captions have similarity scores favoring the right pairs; the symmetric loss is 0.169. It shrinks toward zero as the right pairs pull ahead.
The loss on a 2 × 2 batch
Readimport numpy as np
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
scores = np.array([[2.0, 0.1], # image 1 vs caption 1, caption 2
[0.3, 1.8]]) # image 2 vs caption 1, caption 2
image_loss = np.mean([-np.log(softmax(scores[i])[i]) for i in range(2)]) # rows
text_loss = np.mean([-np.log(softmax(scores[:, i])[i]) for i in range(2)]) # columns
print((image_loss + text_loss) / 2)softmax <- function(z) { e <- exp(z - max(z)); e / sum(e) }
scores <- rbind(c(2.0, 0.1), # image 1 vs caption 1, caption 2
c(0.3, 1.8)) # image 2 vs caption 1, caption 2
image_loss <- mean(sapply(1:2, function(i) -log(softmax(scores[i, ])[i]))) # rows
text_loss <- mean(sapply(1:2, function(i) -log(softmax(scores[, i])[i]))) # columns
print((image_loss + text_loss) / 2)Temperature sets the contrast
ExploreDividing scores by a temperature before the softmax decides how sharply the best match wins. CLIP learns its temperature; too high and every caption looks equally likely, too low and training chases tiny differences. The same knob governs a language model's sampling:
DExplorable · Temperature and top-p
What do the sampling settings on a language model actually change?
With these settings, how likely is the single most likely token?
Below 1 sharpens the distribution; above 1 flattens it.
Keep the likeliest tokens until they hold this much probability.
“The p-value tells you how extreme”
- With these settings
- Default (temperature 1, no cut-off)
Twelve sampled tokens: extreme · surprising · surprising · unusual · rare · rare · unusual · surprising · rare · extreme · surprising · likely
Commit your prediction above to see the result
Make your prediction to see the result.
The same loss trained on a toy: change the temperature and the batch.
DExplorable · InfoNCE: temperature, negatives, collapse
How does contrastive learning learn useful embeddings without labels, and what keeps it from collapsing?
After training with this objective, where do the embeddings end up?
Batch size
Each item's negatives are the rest of the batch.
Objective
Without labels, a batch can't tell them apart. Off: they're masked out.
Multiplied by min(τ, 0.15)², so low temperatures take smaller steps.
Commit your prediction above to see the result
Make your prediction to see the result.
ALIGN: more pairs, less cleaning
ReadALIGN used the same dual-encoder recipe on nearly two billion image–alt-text pairs with only light filtering. The bet: at that scale, noise averages out, and it paid off.
Every other pair in a batch serves as a wrong match (in-batch negativesIn-batch negatives (contrastive training)In contrastive training, every other pair in the batch counts as a wrong match for each image and each caption.). With web data, two entries in one batch can share an image or describe the same thing; they are then false negatives, pushed apart although they match. The program flags those pairs from a list of source image ids. Remove duplicates before training, or treat same-source pairs as positives.
Search with CLIP in CodeSplash
In the appImage–text search runs a CLIP ViT-B/32, an open replication trained on the LAION-2B web pairs, in Python and R. Type a few search texts and it ranks every image by similarity:
17 images ranked for 2 search texts.
- Images
- 17
- Search texts
- 2
Plots
View data
| File | Search text | Image | Rank | Score |
|---|---|---|---|---|
| red_circle_2.png | a red circle | 5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f6321 | 1 | 0.2981 |
| red_circle_1.png | a red circle | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 2 | 0.2941 |
| red_circle_1_copy.png | a red circle | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 3 | 0.2941 |
| yellow_square_2.png | a yellow square | fa76bf14a0ba2ef56e8166402e88d235460ce6ea91d115ad87bbc8ec9a500ed0 | 1 | 0.3287 |
| yellow_square_1.png | a yellow square | c37818ace5a34c68b5903a7aee70236022e599dc89a78dea4f5cbfa8cf53d3d3 | 2 | 0.2956 |
| yellow_circle_2.png | a yellow square | 604a35801ef2627525250e1f7dd474fa9f79e7f5e8ca8452de2cceb6ee67040f | 3 | 0.2601 |
View data
| Cosine similarity |
|---|
| 0.2941 |
| 0.2062 |
| 0.2178 |
| 0.1241 |
| 0.2260 |
| 0.1302 |
| 0.2239 |
| 0.1210 |
| 0.2981 |
| 0.2310 |
| 0.2355 |
| 0.1575 |
| 0.2414 |
| 0.1581 |
| 0.2320 |
| 0.1547 |
| 0.2941 |
| 0.1116 |
| 0.1510 |
| 0.1251 |
| 0.1785 |
| 0.1310 |
| 0.1816 |
| 0.2556 |
| 0.2956 |
| 0.1370 |
| 0.1861 |
| 0.1559 |
| 0.2214 |
| 0.1590 |
| 0.2267 |
| 0.2601 |
| 0.3287 |
| 0.1116 |
View data
| Group | PC 1 | PC 2 |
|---|---|---|
| Images | 0.3347 | 0.2984 |
| Images | −0.2839 | 0.2952 |
| Images | 0.1721 | 0.1685 |
| Images | −0.3015 | 0.1529 |
| Images | 0.2475 | 0.0618 |
| Images | −0.2808 | 0.0773 |
| Images | 0.1769 | 0.1547 |
| Images | −0.3399 | 0.1976 |
| Images | 0.3175 | −0.1227 |
| Images | −0.2224 | −0.0265 |
| Images | 0.2007 | −0.2935 |
| Images | −0.2048 | −0.2399 |
| Images | 0.2314 | −0.3410 |
| Images | −0.2016 | −0.2745 |
| Images | 0.1155 | −0.2591 |
| Images | −0.2960 | −0.1475 |
| Images | 0.3347 | 0.2984 |
Assumptions
- Scores are not probabilities — The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff.
- Labels depend on wording — Labels and search results change with the words used; try a few wordings or templates.
- Learned from web images — The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.
Best images per search text
| Search text | Rank | Row | File | Cosine similarity |
|---|---|---|---|---|
| a red circle | 1 | 9 | red_circle_2.png | 0.2981 |
| a red circle | 2 | 1 | red_circle_1.png | 0.2941 |
| a red circle | 3 | 17 | red_circle_1_copy.png | 0.2941 |
| a yellow square | 1 | 16 | yellow_square_2.png | 0.3287 |
| a yellow square | 2 | 8 | yellow_square_1.png | 0.2956 |
| a yellow square | 3 | 15 | yellow_circle_2.png | 0.2601 |
- 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
- Model: CLIP ViT-B/32 (DataComp-1B). Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.
The exact R script · R R version 4.5.1 (2025-06-13)
# Image–text search and zero-shot labels (CLIP, SigLIP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_text 1.0.0 · spec 326a751997bb3b1f
# Dataset: clip_images (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_clip_* / cs_siglip_* (towers on R torch), cs_imagetext_* (twins of codesplash.imagetext.discover)
# %% Data (rows with an image path; known labels and captions may be missing)
IMAGE <- "path"
TRUTH <- NULL
CAPTION <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clip_images.parquet", col_select = c("path")))
n_input <- nrow(df)
df <- df[!is.na(df[[IMAGE]]), , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"catmull_rom\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.48145466,0.4578275,0.40821073],\"std\":[0.26862954,0.26130258,0.27577711]},\"size\":[224,224]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/discover.image_text/text_search_queries/out-r", df,
"tests/parity/fixtures/clip_images.parquet")
media_ids <- cs_media_ids(media, df)
# %% Images the host could decode (unreadable files are left out)
status <- cs_media_status(media, media_ids)
ok <- which(is.na(status))
bad <- which(!is.na(status))
n_unreadable <- length(bad)
if (!length(ok)) cs_error("CS_E_MEDIA_DECODE", file = as.character(df[[IMAGE]][bad[1]]), reason = as.character(status[bad[1]]))
if (length(bad)) {
warnings <- c(warnings, sprintf("%d image file(s) couldn't be read and are left out (first: %s).", length(bad), as.character(df[[IMAGE]][bad[1]])))
}
input_pos <- as.integer(rownames(df)) - 1L
df <- df[ok, , drop = FALSE]
ids <- media_ids[ok]
rows <- input_pos[ok] # 0-based positions in the analysis input
n <- length(rows)
files <- basename(as.character(df[[IMAGE]]))
truth <- if (is.null(TRUTH)) NULL else as.character(df[[TRUTH]])
captions <- if (is.null(CAPTION)) NULL else as.character(df[[CAPTION]])
truth_levels <- if (is.null(truth)) character(0) else sort(unique(truth[!is.na(truth)]), method = "radix")
# %% Task settings (checked before the model loads)
MODE <- "text_search"
KIND <- "clip"
TOP_K <- as.integer(3)
LABELS <- character(0); TEMPLATES <- character(0); QUERIES <- character(0); QPOS <- integer(0)
if (MODE == "zero_shot") {
LABELS <- cs_search_split_labels("")
if (!length(LABELS) && length(truth_levels)) LABELS <- truth_levels
if (length(LABELS) < 2) {
cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "at least two labels separated by commas",
value = if (length(LABELS)) paste(LABELS, collapse = ", ") else "(empty)")
}
if (anyDuplicated(LABELS)) cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "distinct labels", value = paste(LABELS, collapse = ", "))
TEMPLATES <- cs_search_split_list("a photo of a {label}.")
if (!length(TEMPLATES) || !all(grepl("{label}", TEMPLATES, fixed = TRUE))) {
cs_error("CS_E_INVALID_OPTION", option = "Prompt templates", allowed = "sentences that each contain {label}",
value = if (length(TEMPLATES)) paste(TEMPLATES, collapse = "; ") else "(empty)")
}
} else if (MODE == "text_search") {
QUERIES <- cs_search_split_list("a red circle; a yellow square")
if (!length(QUERIES) && (is.null(captions) || all(is.na(captions)))) {
cs_error("CS_E_INVALID_OPTION", option = "Search texts", allowed = "at least one text, or a caption column", value = "(empty)")
}
} else {
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Finding similar images", min = 2, n = n)
QROWS <- cs_imagetext_parse_rows("")
if (is.null(QROWS)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers separated by commas", value = "")
for (q in QROWS) {
hit <- which(rows + 1L == q)
if (!length(hit)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers of readable images", value = as.character(q))
QPOS <- c(QPOS, hit[1])
}
if (!length(QPOS)) QPOS <- seq_len(n)
}
# %% Image embeddings (CLIP ViT-B/32, double precision, one image at a time)
if (!cs_clip_available()) cs_error("CS_WEIGHTS_MISSING", model = "CLIP ViT-B/32 (DataComp-1B)")
model <- cs_clip_load()
NAME <- "CLIP ViT-B/32 (DataComp-1B)"
embed_images <- function(x) cs_clip_image_embed(model, x)
embed_texts <- function(t) cs_clip_text_embed(model, t)
LOGIT_BIAS <- 0
d <- model$dim
E <- matrix(0, n, d) # unit rows, one image at a time; files read 32 at a time from the host's decoded tensors
for (i in seq(1L, n, by = 32L)) {
idx <- i:min(n, i + 31L)
E[idx, ] <- embed_images(cs_media_load(media, ids[idx])) # (b, 3, 224, 224), the host's float32 values
}
values <- list(
n_rows = n_input, n_images = n, n_unreadable = n_unreadable, encoder = NAME, mode = MODE, dim = d,
logit_scale = model$logit_scale, logit_bias = if (KIND == "siglip") LOGIT_BIAS else NA,
n_labels = NA, n_templates = NA, labels_text = NA, mean_top_score = NA, mean_margin = NA,
template_agreement = NA, n_evaluated = NA, accuracy = NA, macro_f1 = NA, balanced_accuracy = NA,
n_queries = NA, recall_at_1 = NA, recall_at_5 = NA, recall_at_10 = NA, median_rank = NA,
clipscore_mean = NA, mean_nn_similarity = NA
)
for (j in seq_len(min(5L, d))) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)
# %% Captions: CLIPScore = 2.5 * max(cos(image, caption), 0) (Hessel et al. 2021), on this model's embeddings
cap_pos <- if (is.null(captions)) integer(0) else which(!is.na(captions))
C <- if (length(cap_pos)) embed_texts(captions[cap_pos]) else NULL
if (length(cap_pos)) values$clipscore_mean <- mean(2.5 * pmax(rowSums(C * E[cap_pos, , drop = FALSE]), 0))
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.image_text/text_search_queries/out-r")
tables <- list(); charts <- list(); statistics <- list(); artifacts <- list()
gallery <- list(media = character(0), file = character(0), group = character(0), rank = integer(0), score = numeric(0))
add_gallery <- function(group, positions, scores) {
gallery$media <<- c(gallery$media, ids[positions])
gallery$file <<- c(gallery$file, files[positions])
gallery$group <<- c(gallery$group, rep(group, length(positions)))
gallery$rank <<- c(gallery$rank, seq_along(positions))
gallery$score <<- c(gallery$score, as.numeric(scores))
}
# %% Text -> image search: images ranked by cosine similarity to each text
if (length(QUERIES)) {
Q <- embed_texts(QUERIES)
sim <- Q %*% t(E) # texts x images
qnames <- QUERIES
} else {
sim <- C %*% t(E)
qnames <- captions[cap_pos]
}
S <- if (KIND == "siglip") cs_imagetext_scores(sim, "siglip", model$logit_scale, LOGIT_BIAS) else sim
values$n_queries <- length(qnames)
K <- min(TOP_K, n)
m_query <- character(0); m_rank <- integer(0); m_row <- integer(0); m_file <- character(0); m_sim <- numeric(0); m_score <- numeric(0)
for (q in seq_along(qnames)) {
best_k <- cs_imagetext_top_k(sim[q, ], K)
m_query <- c(m_query, rep(qnames[q], length(best_k))); m_rank <- c(m_rank, seq_along(best_k)); m_row <- c(m_row, rows[best_k] + 1L)
m_file <- c(m_file, files[best_k]); m_sim <- c(m_sim, sim[q, best_k]); m_score <- c(m_score, S[q, best_k])
if (q <= 10) for (r in seq_along(best_k)) {
values[[sprintf("match_row[%d.%d]", q, r)]] <- rows[best_k[r]] + 1L
values[[sprintf("match_score[%d.%d]", q, r)]] <- sim[q, best_k[r]]
}
add_gallery(qnames[q], best_k, S[q, best_k])
}
if (!length(QUERIES)) {
own <- vapply(seq_along(cap_pos), function(i) cs_imagetext_rank_of(sim[i, ], cap_pos[i]), 0L) # 1-based rank of each caption's own image
values$recall_at_1 <- cs_imagetext_recall_at(own, 1); values$recall_at_5 <- cs_imagetext_recall_at(own, 5)
values$recall_at_10 <- cs_imagetext_recall_at(own, 10); values$median_rank <- as.numeric(stats::median(own))
statistics <- c(statistics, list(list(key = "recall_at_1", label = "Own image first", value = values$recall_at_1, format = "percent"),
list(key = "recall_at_5", label = "Own image in the top 5", value = values$recall_at_5, format = "percent"),
list(key = "median_rank", label = "Median rank of the own image", value = values$median_rank)))
charts[[length(charts) + 1]] <- cs_chart("own_rank", "histogram", "Rank of each caption's own image", list(x = cs_col("Rank", as.numeric(own))))
}
match_cols <- list(list(key = "query", label = "Search text", type = "string"), list(key = "rank", label = "Rank", type = "integer"),
list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File", type = "string"),
list(key = "similarity", label = "Cosine similarity", type = "number"))
if (KIND == "siglip") match_cols <- c(match_cols, list(list(key = "score", label = "Pair score (sigmoid)", type = "number")))
n_match <- length(m_rank)
shown <- seq_len(min(n_match, 500L))
match_rows <- lapply(shown, function(i) list(query = m_query[i], rank = m_rank[i], row = m_row[i], file = m_file[i], similarity = m_sim[i], score = m_score[i]))
tables[[length(tables) + 1]] <- list(key = "matches", title = "Best images per search text", columns = match_cols, rows = match_rows,
note = if (length(shown) == n_match) NULL else sprintf("The first %d of %d matches.", length(shown), n_match))
statistics <- c(list(list(key = "n_queries", label = "Search texts", value = length(qnames))), statistics)
charts[[length(charts) + 1]] <- cs_chart("similarities", "histogram", "Cosine similarity of every text–image pair",
list(x = cs_col("Cosine similarity", as.numeric(t(sim)))))
nanoparquet::write_parquet(data.frame(query = m_query, rank = m_rank, row = m_row, file = m_file, similarity = m_sim, score = m_score),
file.path(out, "matches.parquet"))
artifacts[[length(artifacts) + 1]] <- list(key = "matches", path = file.path(out, "matches.parquet"), format = "parquet")
summary <- paste0(sprintf("%d images ranked for %d search text%s", n, length(qnames), if (length(qnames) != 1) "s" else ""),
if (!length(QUERIES)) sprintf("; each caption's own image came first for %.0f%% of captions.", 100 * values$recall_at_1) else ".")
# %% Ranked thumbnails, the embedding map and the saved embeddings
if (length(gallery$media)) {
charts <- c(list(cs_chart("gallery", "image-ranking", if (MODE != "image_search") "Top images" else "Query images and their nearest images", list(
media = cs_col("Image", gallery$media, kind = "categorical"),
file = cs_col("File", gallery$file, kind = "categorical"),
group = cs_col(if (MODE == "zero_shot") "Label" else if (MODE == "text_search") "Search text" else "Query", gallery$group, kind = "categorical"),
rank = cs_col("Rank", as.numeric(gallery$rank)),
score = cs_col(if (MODE != "image_search") "Score" else "Cosine similarity", gallery$score)
), controls = list(per_group = min(TOP_K + (if (MODE == "image_search") 1L else 0L), 12L)))), charts)
}
if (n >= 3) {
Z <- cs_imagetext_pca2(E)
color <- if (MODE == "zero_shot") pred else if (!is.null(truth)) truth else rep("Images", n)
charts[[length(charts) + 1]] <- cs_chart("map", "cluster-scatter", "Image map (first two principal components of the embeddings)", list(
x = cs_col("PC 1", Z[, 1], "numeric"), y = cs_col("PC 2", Z[, 2], "numeric"),
cluster = cs_col(if (MODE == "zero_shot") "Zero-shot label" else if (!is.null(TRUTH)) TRUTH else "Group", ifelse(is.na(color), "(missing)", color), "categorical")
))
}
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(d)) emb[[sprintf("dim_%d", j)]] <- E[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
artifacts <- c(list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet")), artifacts)
statistics <- c(list(list(key = "n_images", label = "Images", value = n, format = "integer")), statistics)
if (!is.na(values$clipscore_mean)) statistics[[length(statistics) + 1]] <- list(key = "clipscore_mean", label = "Mean CLIPScore (captions)", value = values$clipscore_mean)
ta <- values$template_agreement
assumptions <- list(
list(key = "uncalibrated", label = "Scores are not probabilities", status = "info",
detail = "The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff."),
list(key = "prompt_wording", label = "Labels depend on wording", status = if (!is.na(ta) && ta < 0.9) "warn" else "info",
detail = if (!is.na(ta)) sprintf("%.0f%% of images get the same label under every template.", 100 * ta)
else "Labels and search results change with the words used; try a few wordings or templates."),
list(key = "web_training", label = "Learned from web images", status = "info",
detail = "The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.")
)
cs_publish(list(
title = "Image–text search and zero-shot labels (CLIP, SigLIP)",
engine = cs_engine_info("torch", "stringi", "nanoparquet"),
n = n,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
notes = list(sprintf("Model: %s. Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.", NAME)),
artifacts = artifacts
))
17 images ranked for 2 search texts.
- Images
- 17
- Search texts
- 2
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Scores are not probabilities — The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff.
- Labels depend on wording — Labels and search results change with the words used; try a few wordings or templates.
- Learned from web images — The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.
Best images per search text
| Search text | Rank | Row | File | Cosine similarity |
|---|---|---|---|---|
| a red circle | 1 | 9 | red_circle_2.png | 0.2981 |
| a red circle | 2 | 1 | red_circle_1.png | 0.2941 |
| a red circle | 3 | 17 | red_circle_1_copy.png | 0.2941 |
| a yellow square | 1 | 16 | yellow_square_2.png | 0.3287 |
| a yellow square | 2 | 8 | yellow_square_1.png | 0.2956 |
| a yellow square | 3 | 15 | yellow_circle_2.png | 0.2601 |
- 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
- Model: CLIP ViT-B/32 (DataComp-1B). Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image–text search and zero-shot labels (CLIP, SigLIP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_text 1.0.0 · spec 326a751997bb3b1f
# Dataset: clip_images (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.imagetext import discover as it # prompts, scores, rankings (twin: codesplashr cs_imagetext_*)
from codesplash.ml import embed as csembed # order-sensitive checksums (twin: cs_ml_checksum)
from codesplash.text import search as zs # label lists and agreement figures (twin: cs_search_* / cs_zero_shot_classification)
from codesplash.imagetext import clip as tower # CLIP ViT-B/32 written out on torch (twin: cs_clip_*)
# %% Data (rows with an image path; known labels and captions may be missing)
IMAGE = "path"
TRUTH = None
CAPTION = None
df = pd.read_parquet("tests/parity/fixtures/clip_images.parquet", columns=["path"])
n_input = len(df)
df = df[df[IMAGE].notna()]
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"catmull_rom\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.48145466,0.4578275,0.40821073],\"std\":[0.26862954,0.26130258,0.27577711]},\"size\":[224,224]}}"), "target/academy-parity/run-8142/discover.image_text/text_search_queries/out-python", df, "tests/parity/fixtures/clip_images.parquet")
media_ids = cs_media.ids_of(media, df)
# %% Images the host could decode (unreadable files are left out)
status = cs_media.status(media, media_ids)
ok = [k for k, s in enumerate(status) if s is None]
bad = [k for k, s in enumerate(status) if s is not None]
n_unreadable = len(bad)
if not ok:
cs.cs_error("CS_E_MEDIA_DECODE", file=str(df[IMAGE].iloc[bad[0]]), reason=str(status[bad[0]]))
if bad:
warnings.append(f"{len(bad)} image file(s) couldn't be read and are left out (first: {df[IMAGE].iloc[bad[0]]}).")
df = df.iloc[ok]
ids = [media_ids[k] for k in ok]
rows = df.index.to_numpy().astype(np.int64) # 0-based positions in the analysis input
n = len(rows)
files = [os.path.basename(str(p)) for p in df[IMAGE].tolist()]
truth = None if TRUTH is None else [None if pd.isna(v) else str(v) for v in df[TRUTH].tolist()]
captions = None if CAPTION is None else [None if pd.isna(v) else str(v) for v in df[CAPTION].tolist()]
truth_levels = [] if truth is None else sorted(set(t for t in truth if t is not None))
# %% Task settings (checked before the model loads)
MODE = "text_search"
KIND = "clip"
TOP_K = int(3)
LABELS, TEMPLATES, QUERIES, QPOS = [], [], [], []
if MODE == "zero_shot":
LABELS = zs.split_labels("")
if not LABELS and truth_levels:
LABELS = list(truth_levels)
if len(LABELS) < 2:
cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="at least two labels separated by commas", value=", ".join(LABELS) or "(empty)")
if len(set(LABELS)) < len(LABELS):
cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="distinct labels", value=", ".join(LABELS))
TEMPLATES = zs.split_list("a photo of a {label}.")
if not TEMPLATES or any(zs.LABEL_SLOT not in t for t in TEMPLATES):
cs.cs_error("CS_E_INVALID_OPTION", option="Prompt templates", allowed="sentences that each contain {label}", value="; ".join(TEMPLATES) or "(empty)")
elif MODE == "text_search":
QUERIES = zs.split_list("a red circle; a yellow square")
if not QUERIES and (captions is None or not any(c is not None for c in captions)):
cs.cs_error("CS_E_INVALID_OPTION", option="Search texts", allowed="at least one text, or a caption column", value="(empty)")
else:
if n < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Finding similar images", min=2, n=n)
QROWS = it.parse_rows("")
if QROWS is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers separated by commas", value="")
for q in QROWS:
hit = np.nonzero(rows + 1 == q)[0]
if not len(hit):
cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers of readable images", value=str(q))
QPOS.append(int(hit[0]))
if not QPOS:
QPOS = list(range(n))
# %% Image embeddings (CLIP ViT-B/32, double precision, one image at a time)
if not tower.available():
cs.cs_error("CS_WEIGHTS_MISSING", model=tower.NAME)
model = tower.Model()
LOGIT_BIAS = float(getattr(model, "logit_bias", 0.0))
d = model.dim
E = np.zeros((n, d)) # unit rows, one image at a time; files read 32 at a time from the host's decoded tensors
for i in range(0, n, 32):
E[i:i + 32] = model.image_embed(cs_media.load(media, ids[i:i + 32])) # float32 (b, 3, 224, 224)
values = {
"n_rows": n_input, "n_images": n, "n_unreadable": n_unreadable, "encoder": tower.NAME, "mode": MODE, "dim": d,
"logit_scale": model.logit_scale, "logit_bias": LOGIT_BIAS if KIND == "siglip" else None,
"n_labels": None, "n_templates": None, "labels_text": None, "mean_top_score": None, "mean_margin": None,
"template_agreement": None, "n_evaluated": None, "accuracy": None, "macro_f1": None, "balanced_accuracy": None,
"n_queries": None, "recall_at_1": None, "recall_at_5": None, "recall_at_10": None, "median_rank": None,
"clipscore_mean": None, "mean_nn_similarity": None,
}
for j in range(min(5, d)):
values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)
# %% Captions: CLIPScore = 2.5 · max(cos(image, caption), 0) (Hessel et al. 2021), on this model's embeddings
cap_pos = [] if captions is None else [k for k, c in enumerate(captions) if c is not None]
C = model.text_embed([captions[k] for k in cap_pos]) if cap_pos else None
if cap_pos:
values["clipscore_mean"] = float(np.mean(2.5 * np.maximum(np.sum(C * E[cap_pos], axis=1), 0.0)))
out = csml.out_dir("target/academy-parity/run-8142/discover.image_text/text_search_queries/out-python")
tables, charts, statistics, artifacts = [], [], [], []
gallery = {"media": [], "file": [], "group": [], "rank": [], "score": []}
def add_gallery(group, positions, scores):
for r, (k, s) in enumerate(zip(positions, scores), start=1):
gallery["media"].append(ids[k])
gallery["file"].append(files[k])
gallery["group"].append(group)
gallery["rank"].append(r)
gallery["score"].append(float(s))
# %% Text → image search: images ranked by cosine similarity to each text
if QUERIES:
Q = model.text_embed(QUERIES)
sim = Q @ E.T # texts × images
qnames = QUERIES
else:
sim = C @ E.T
qnames = [captions[k] for k in cap_pos]
S = it.scores(sim, "siglip", model.logit_scale, LOGIT_BIAS) if KIND == "siglip" else sim
values["n_queries"] = len(qnames)
match_rows = []
K = min(TOP_K, n)
for q in range(len(qnames)):
best_k = it.top_k(sim[q], K)
for r, k in enumerate(best_k, start=1):
match_rows.append({"query": qnames[q], "rank": r, "row": int(rows[k]) + 1, "file": files[k],
"similarity": float(sim[q, k]), "score": float(S[q, k])})
if q < 10:
values[f"match_row[{q + 1}.{r}]"] = int(rows[k]) + 1
values[f"match_score[{q + 1}.{r}]"] = float(sim[q, k])
add_gallery(qnames[q], best_k, S[q, best_k])
if not QUERIES:
own = np.array([it.rank_of(sim[i], cap_pos[i]) for i in range(len(cap_pos))], dtype=np.int64) # 1-based rank of each caption's own image
values.update({"recall_at_1": it.recall_at(own, 1), "recall_at_5": it.recall_at(own, 5), "recall_at_10": it.recall_at(own, 10),
"median_rank": float(np.median(own))})
statistics += [{"key": "recall_at_1", "label": "Own image first", "value": values["recall_at_1"], "format": "percent"},
{"key": "recall_at_5", "label": "Own image in the top 5", "value": values["recall_at_5"], "format": "percent"},
{"key": "median_rank", "label": "Median rank of the own image", "value": values["median_rank"]}]
charts.append(cs.chart("own_rank", "histogram", "Rank of each caption's own image", {"x": cs.col("Rank", own.astype(float))}))
match_cols = [{"key": "query", "label": "Search text", "type": "string"}, {"key": "rank", "label": "Rank", "type": "integer"},
{"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File", "type": "string"},
{"key": "similarity", "label": "Cosine similarity", "type": "number"}]
if KIND == "siglip":
match_cols.append({"key": "score", "label": "Pair score (sigmoid)", "type": "number"})
SHOWN = match_rows[:500]
tables.append({"key": "matches", "title": "Best images per search text", "columns": match_cols, "rows": SHOWN,
"note": None if len(SHOWN) == len(match_rows) else f"The first {len(SHOWN)} of {len(match_rows)} matches."})
statistics.insert(0, {"key": "n_queries", "label": "Search texts", "value": len(qnames)})
charts.append(cs.chart("similarities", "histogram", "Cosine similarity of every text–image pair", {"x": cs.col("Cosine similarity", sim.reshape(-1))}))
pd.DataFrame(match_rows).to_parquet(os.path.join(out, "matches.parquet"), index=False)
artifacts.append({"key": "matches", "path": os.path.join(out, "matches.parquet"), "format": "parquet"})
summary = f"{n} images ranked for {len(qnames)} search text{'s' if len(qnames) != 1 else ''}" + (
f"; each caption's own image came first for {values['recall_at_1']:.0%} of captions." if not QUERIES else ".")
# %% Ranked thumbnails, the embedding map and the saved embeddings
if gallery["media"]:
charts.insert(0, cs.chart("gallery", "image-ranking", "Top images" if MODE != "image_search" else "Query images and their nearest images", {
"media": cs.col("Image", gallery["media"], kind="categorical"),
"file": cs.col("File", gallery["file"], kind="categorical"),
"group": cs.col("Label" if MODE == "zero_shot" else ("Search text" if MODE == "text_search" else "Query"), gallery["group"], kind="categorical"),
"rank": cs.col("Rank", gallery["rank"]),
"score": cs.col("Score" if MODE != "image_search" else "Cosine similarity", gallery["score"]),
}, controls={"per_group": min(TOP_K + (1 if MODE == "image_search" else 0), 12)}))
if n >= 3:
Z = it.pca2(E)
color = pred if MODE == "zero_shot" else (truth if truth is not None else ["Images"] * n)
charts.append(cs.chart("map", "cluster-scatter", "Image map (first two principal components of the embeddings)", {
"x": cs.col("PC 1", Z[:, 0], "numeric"), "y": cs.col("PC 2", Z[:, 1], "numeric"),
"cluster": cs.col("Zero-shot label" if MODE == "zero_shot" else (TRUTH or "Group"), ["(missing)" if c is None else c for c in color], "categorical"),
}))
emb = pd.DataFrame({"row": rows, **{f"dim_{j + 1}": E[:, j] for j in range(d)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
artifacts.insert(0, {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"})
statistics.insert(0, {"key": "n_images", "label": "Images", "value": n, "format": "integer"})
if values["clipscore_mean"] is not None:
statistics.append({"key": "clipscore_mean", "label": "Mean CLIPScore (captions)", "value": values["clipscore_mean"]})
assumptions = [
{"key": "uncalibrated", "label": "Scores are not probabilities", "status": "info",
"detail": "The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff."},
{"key": "prompt_wording", "label": "Labels depend on wording", "status": ("warn" if values["template_agreement"] is not None and values["template_agreement"] < 0.9 else "info"),
"detail": (f"{values['template_agreement']:.0%} of images get the same label under every template." if values["template_agreement"] is not None
else "Labels and search results change with the words used; try a few wordings or templates.")},
{"key": "web_training", "label": "Learned from web images", "status": "info",
"detail": "The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views."},
]
cs.publish({
"title": "Image–text search and zero-shot labels (CLIP, SigLIP)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": [f"Model: {tower.NAME}. Each image and text is embedded on its own in double precision, so results never depend on what else is in the run."],
"artifacts": artifacts,
})
Check: contrastive alignment
CheckpointCheck yourself
A CLIP training batch holds 32,768 image–caption pairs. For each image, how many wrong captions does the loss compare it against?
Show the answer
Answer: a
Each row of the similarity matrix is a softmax over the whole batch. Larger batches give more, and harder, negatives.
Check yourself
Why does CLIP's loss average two cross-entropies?
Show the answer
Answer: a
Both directions are trained, so text-to-image and image-to-text search both work.
Check yourself
Why can a dual encoder search a million images in a fraction of a second?
Show the answer
Answer: a
The towers never interact, so image vectors can be stored and reused for every query.
Check yourself
Which question is a CLIP-style dual encoder worst at?
Show the answer
Answer: c
Counts, spatial relations and word order get blurred into one vector per side. Fusion models and visual chat models can check them better.
Check yourself
What was ALIGN's main departure from CLIP's recipe?
Show the answer
Answer: a
The architecture stayed a dual encoder with a contrastive loss; the data changed.
Check yourself
Two captions of the same photo land in one training batch. What does the contrastive loss do with them?
Show the answer
Answer: b
In-batch negatives assume every other pair is wrong. Deduplicate by source, or mark same-source pairs as positives.
Recap
Recap- A dual encoder maps images and texts into one space; towers never interact, which makes search fast.
- CLIP's loss is a temperature-scaled softmax over the batch, in both directions.
- In-batch negatives make every other pair a wrong match; duplicates and same-source pairs become false negatives.
- One vector per side blurs counts, relations and word order: a high score isn't a correct caption.
Concepts in this lesson