Skip to content

Labeling and searching images with words

Use a pretrained image–text model (CLIP or SigLIP) to label images with words you choose, rank images for a search text and find look-alike images, then check how much the result depends on the wording.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Explain how one shared space lets an image be compared with any text
  • Label images zero-shot and judge the labels against known ones and across prompt templates
  • Search images by text or by image and read recall at k

Read first

01

One space for pictures and words

Read

An image–text model has two networks. One turns an image into a vector, the other turns a sentence into a vector, and training on web pictures with their captions pulls each picture close to its own caption. CLIPCLIPA 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. and SigLIPSigLIPA CLIP-like image–text model trained with a sigmoid loss: it scores each image–text pair on its own instead of across a batch. both work this way.

Because pictures and sentences now live in one space, you can compare an image with any words you type. Nothing is trained on your data, and the model runs on this computer after a download you approve.

The folder here holds 17 simple drawings: colored circles and squares.

02

Labels from your words

Predict

Predict first

Each label is written into the sentence "a photo of a {label}." for red, green, blue and yellow, and each drawing takes the label that fits it best. How many get the right color?

Most images get the right colorAbout a quarter, like guessingNone, because the model never saw these files
Reveal

The answer: Most images get the right color

The labels agree with the known colors for 100.0% of the drawings. Colors and simple shapes are easy; real photos of near-identical classes are much harder.

03

Run it

In the app
Image–text search and zero-shot labels (CLIP, SigLIP)Recorded · Python and R agreeRecorded 2026-11-25 · 46 values compared
R

17 images into 4 labels; most common red (29%); accuracy 100% against color.

Images
17
Labels
4
Mean score of the chosen label
0.9999
Accuracy
100.0%
Macro F1
1

Plots

Top imagesWhich images fit a label or a search text best, and which images look most alike?
View data
FileLabelImageRankScore
red_square_2.pngred434e2ec8acd8699a94f5db3be0f41ab8101c8157f523a05e1db05a7ea975a55f11.0000
red_square_1.pngredc2da9720dabe35c5e764c0a9e57df8638d67b65ccc85bc35c96446af3852637621.0000
red_circle_1.pngred9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb31.0000
red_circle_1_copy.pngred9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb41.0000
red_circle_2.pngred5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f632150.9999
green_square_1.pnggreen8ca99c38a1f6c433614960aff2a8d7432eeeebd3654348c9988b0f9ba30e32c711.0000
green_circle_1.pnggreen33a634b9fb3326da6edf75bc17755bbf236a4cf0e7b2349a6dbbd4790ad909e120.9999
green_square_2.pnggreenf0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a2130.9999
green_circle_2.pnggreenc125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f1340.9995
blue_circle_2.pnggreen727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a80853.616e-5
blue_square_1.pngbluebcf2583948f23afadb9eedbe7ed773103107e11d79522ae2bd5a1b8062fa738011.0000
blue_circle_1.pngblueac9b3dde099f3243d0b992fc9bac26d3384e28638afc7a82efa35c622ce9c12f21.0000
blue_square_2.pngblue77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d930.9999
blue_circle_2.pngblue727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a80840.9992
green_circle_2.pngbluec125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f1350.0001
yellow_square_1.pngyellowc37818ace5a34c68b5903a7aee70236022e599dc89a78dea4f5cbfa8cf53d3d311.0000
yellow_square_2.pngyellowfa76bf14a0ba2ef56e8166402e88d235460ce6ea91d115ad87bbc8ec9a500ed021.0000
yellow_circle_1.pngyellowd7650e4851900cbbd716ef730decc1f99ed2da6e97b937bf8ce0a7bf5a6a64e431.0000
yellow_circle_2.pngyellow604a35801ef2627525250e1f7dd474fa9f79e7f5e8ca8452de2cceb6ee67040f40.9999
green_circle_2.pngyellowc125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f1358.919e-5
Images per labelWhich words or phrases appear most in a text column, overall or by group?
View data
ImagesLabel
5red
4green
4blue
4yellow
Score of the chosen labelHow is one numeric variable distributed?
View data
Score
1.0000
1.0000
0.9999
1.0000
1.0000
1.0000
1.0000
1.0000
0.9999
1.0000
0.9995
0.9999
0.9992
0.9999
0.9999
1.0000
1.0000
Zero-shot labels against colorHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?
View data
colorZero-shot label
redred
redred
greengreen
greengreen
blueblue
blueblue
yellowyellow
yellowyellow
redred
redred
greengreen
greengreen
blueblue
blueblue
yellowyellow
yellowyellow
redred
Image map (first two principal components of the embeddings)Which rows group together, and how well separated are the groups?
View data
Zero-shot labelPC 1PC 2
red0.33470.2984
red−0.28390.2952
green0.17210.1685
green−0.30150.1529
blue0.24750.0618
blue−0.28080.0773
yellow0.17690.1547
yellow−0.33990.1976
red0.3175−0.1227
red−0.2224−0.0265
green0.2007−0.2935
green−0.2048−0.2399
blue0.2314−0.3410
blue−0.2016−0.2745
yellow0.1155−0.2591
yellow−0.2960−0.1475
red0.33470.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.

Labels

LabelImagesShare of imagesMean score (labeled images)KnownPrecisionRecallF1
red50.29411.00005111
green40.23530.99984111
blue40.23530.99974111
yellow40.23531.00004111

Each label is embedded as a photo of a {label}. with the label filled in. Scores are softmax probabilities across the labels (they sum to 1).

Top labels per image

RowFileLabel 1Score 1Label 2Score 2Label 3Score 3Label 4Score 4Known label
1red_circle_1.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
2red_square_1.pngred1.0000blue7.675e-7yellow4.752e-7green4.568e-7red
3green_circle_1.pnggreen0.9999red3.881e-5blue3.725e-5yellow7.679e-6green
4green_square_1.pnggreen1.0000red1.266e-5blue1.134e-5yellow2.463e-6green
5blue_circle_1.pngblue1.0000red4.510e-5yellow2.744e-6green2.041e-6blue
6blue_square_1.pngblue1.0000red1.483e-5green1.156e-6yellow9.401e-7blue
7yellow_circle_1.pngyellow1.0000red1.210e-5blue7.562e-6green3.706e-6yellow
8yellow_square_1.pngyellow1.0000green1.652e-6red1.530e-6blue5.983e-7yellow
9red_circle_2.pngred0.9999yellow5.776e-5blue3.343e-5green7.213e-6red
10red_square_2.pngred1.0000yellow7.082e-7blue6.591e-7green3.169e-7red
11green_circle_2.pnggreen0.9995red0.0003blue0.0001yellow8.919e-5green
12green_square_2.pnggreen0.9999red8.516e-5blue3.818e-5yellow2.244e-5green
13blue_circle_2.pngblue0.9992red0.0007yellow7.249e-5green3.616e-5blue
14blue_square_2.pngblue0.9999red0.0001yellow2.006e-5green5.698e-6blue
15yellow_circle_2.pngyellow0.9999red4.148e-5green1.243e-5blue7.390e-6yellow
16yellow_square_2.pngyellow1.0000red2.760e-6green1.148e-6blue8.616e-7yellow
17red_circle_1_copy.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
  • 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 85dbfef898a61423
# 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 <- "color"
CAPTION <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clip_images.parquet", col_select = c("path", "color")))
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/colors_zero_shot/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 <- "zero_shot"
KIND <- "clip"
TOP_K <- as.integer(5)
LABELS <- character(0); TEMPLATES <- character(0); QUERIES <- character(0); QPOS <- integer(0)
if (MODE == "zero_shot") {
  LABELS <- cs_search_split_labels("red, green, blue, yellow")
  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("")
  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/colors_zero_shot/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))
}

# %% Zero-shot labels: each label's template sentences averaged (prompt ensemble)
L <- length(LABELS); NT <- length(TEMPLATES)
P <- embed_texts(cs_imagetext_prompts(LABELS, TEMPLATES))  # (T*L x d), template-major
V <- cs_imagetext_label_vectors(P, L, NT)
S <- cs_imagetext_scores(E %*% t(V), KIND, model$logit_scale, LOGIT_BIAS)  # images x labels
pred_idx <- cs_imagetext_best(S)
pred <- LABELS[pred_idx]
top <- S[cbind(seq_len(n), pred_idx)]
margin <- cs_imagetext_margins(S)
per_template <- lapply(seq_len(NT), function(tt) {
  Vt <- cs_imagetext_unit_rows(P[(tt - 1) * L + seq_len(L), , drop = FALSE])
  cs_imagetext_best(cs_imagetext_scores(E %*% t(Vt), KIND, model$logit_scale, LOGIT_BIAS))
})
agree <- cs_imagetext_agreement(per_template)
values$n_labels <- L; values$n_templates <- NT; values$labels_text <- paste(LABELS, collapse = ", ")
values$mean_top_score <- mean(top); values$mean_margin <- mean(margin)
values$template_agreement <- if (is.null(agree)) NA else agree
counts <- vapply(LABELS, function(l) sum(pred == l), numeric(1), USE.NAMES = FALSE)
names(counts) <- LABELS
for (j in seq_len(L)) {
  m <- pred_idx == j
  values[[sprintf("n[%s]", LABELS[j])]] <- counts[[j]]
  values[[sprintf("share[%s]", LABELS[j])]] <- counts[[j]] / n
  values[[sprintf("mean_score[%s]", LABELS[j])]] <- if (any(m)) mean(S[m, j]) else NA
}
ev <- NULL
if (!is.null(truth)) {
  keep <- which(!is.na(truth) & truth %in% LABELS)
  n_not_in <- sum(!is.na(truth) & !(truth %in% LABELS))
  if (n_not_in > 0) warnings <- c(warnings, sprintf("%d known label(s) are not among the labels and are left out of the agreement figures.", n_not_in))
  if (length(keep)) {
    ev <- cs_zero_shot_classification(truth[keep], pred[keep], LABELS)
    values$n_evaluated <- ev$n; values$accuracy <- ev$accuracy; values$macro_f1 <- ev$macro_f1; values$balanced_accuracy <- ev$balanced_accuracy
    for (r in ev$rows) values[[sprintf("f1[%s]", r$label)]] <- r$f1
    if (NT > 1) for (tt in seq_len(NT)) values[[sprintf("accuracy_template[%d]", tt)]] <- mean(LABELS[per_template[[tt]][keep]] == truth[keep])
  } else {
    warnings <- c(warnings, "No image has a known label that is one of the labels, so agreement can't be computed.")
  }
}
never <- LABELS[counts == 0]
if (length(never)) warnings <- c(warnings, sprintf("No image was given %s.", paste(never, collapse = ", ")))
label_cols <- list(list(key = "label", label = "Label", type = "string"), list(key = "images", label = "Images", type = "integer"),
                   list(key = "share", label = "Share of images", type = "number"), list(key = "score", label = "Mean score (labeled images)", type = "number"))
label_rows <- lapply(seq_len(L), function(j) list(label = LABELS[j], images = counts[[j]], share = counts[[j]] / n,
                                                  score = values[[sprintf("mean_score[%s]", LABELS[j])]]))
if (!is.null(ev)) {
  label_cols <- c(label_cols, list(list(key = "support", label = "Known", type = "integer"), list(key = "precision", label = "Precision", type = "number"),
                                   list(key = "recall", label = "Recall", type = "number"), list(key = "f1", label = "F1", type = "number")))
  for (j in seq_along(label_rows)) {
    r <- ev$rows[[j]]
    label_rows[[j]] <- c(label_rows[[j]], list(support = r$support, precision = r$precision, recall = r$recall, f1 = r$f1))
  }
}
K <- min(TOP_K, L)
img_cols <- list(list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File", type = "string"))
for (r in seq_len(K)) img_cols <- c(img_cols, list(list(key = sprintf("label_%d", r), label = sprintf("Label %d", r), type = "string"),
                                                list(key = sprintf("score_%d", r), label = sprintf("Score %d", r), type = "number")))
if (!is.null(truth)) img_cols <- c(img_cols, list(list(key = "known", label = "Known label", type = "string")))
SHOW <- min(n, 100L)
img_rows <- lapply(seq_len(SHOW), function(k) {
  rec <- list(row = rows[k] + 1L, file = files[k])
  tk <- cs_imagetext_top_k(S[k, ], K)
  for (r in seq_along(tk)) {
    rec[[sprintf("label_%d", r)]] <- LABELS[tk[r]]
    rec[[sprintf("score_%d", r)]] <- S[k, tk[r]]
  }
  if (!is.null(truth)) rec$known <- truth[k]
  rec
})
note <- if (KIND == "clip") "Scores are softmax probabilities across the labels (they sum to 1)." else "Scores are SigLIP's pair scores (sigmoid); each label is scored on its own."
tables <- c(tables, list(
  list(key = "labels", title = "Labels", columns = label_cols, rows = label_rows,
       note = paste0("Each label is embedded as ", paste(TEMPLATES, collapse = "; "), " with the label filled in",
                     if (NT > 1) " and the sentences averaged. " else ". ", note)),
  list(key = "images", title = "Top labels per image", columns = img_cols, rows = img_rows,
       note = if (SHOW == n) NULL else sprintf("The first %d of %d images.", SHOW, n))
))
for (j in seq_len(L)) {
  best_k <- cs_imagetext_top_k(S[, j], min(TOP_K, n))
  add_gallery(LABELS[j], best_k, S[best_k, j])
}
charts <- c(charts, list(
  cs_chart("labels", "ngram-bars", "Images per label",
           list(term = cs_col("Label", LABELS, kind = "categorical"), count = cs_col("Images", unname(counts))), controls = list(top = min(L, 50L))),
  cs_chart("top_scores", "histogram", "Score of the chosen label", list(x = cs_col("Score", top)))
))
if (!is.null(ev)) {
  keep <- which(!is.na(truth) & truth %in% LABELS)
  charts[[length(charts) + 1]] <- cs_chart("confusion", "confusion-matrix", sprintf("Zero-shot labels against %s", TRUTH),
    list(actual = cs_col(TRUTH, truth[keep], kind = "categorical", levels = LABELS),
         predicted = cs_col("Zero-shot label", pred[keep], kind = "categorical", levels = LABELS)))
}
statistics <- c(statistics, list(list(key = "n_labels", label = "Labels", value = L),
                                 list(key = "mean_top_score", label = "Mean score of the chosen label", value = values$mean_top_score)))
if (!is.na(values$template_agreement)) {
  statistics[[length(statistics) + 1]] <- list(key = "template_agreement", label = "Same label under every template", value = values$template_agreement, format = "percent")
}
if (!is.null(ev)) statistics <- c(statistics, list(list(key = "accuracy", label = "Accuracy", value = values$accuracy, format = "percent"),
                                                  list(key = "macro_f1", label = "Macro F1", value = values$macro_f1)))
nanoparquet::write_parquet(data.frame(row = as.integer(rows), cluster = as.integer(pred_idx - 1L), label = pred, score = top, margin = margin),
                           file.path(out, "labels.parquet"))
score_frame <- data.frame(row = as.integer(rows))
for (j in seq_len(L)) score_frame[[LABELS[j]]] <- S[, j]
nanoparquet::write_parquet(score_frame, file.path(out, "scores.parquet"))
artifacts <- c(artifacts, list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
                               list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet")))
top_label <- LABELS[which.max(counts)]
summary <- paste0(sprintf("%d images into %d labels; most common %s (%s)", n, L, top_label, sprintf("%.0f%%", 100 * counts[[top_label]] / n)),
                  if (!is.null(ev)) sprintf("; accuracy %.0f%% against %s.", 100 * values$accuracy, TRUTH) 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
))
Python

17 images into 4 labels; most common red (29%); accuracy 100% against color.

Images
17
Labels
4
Mean score of the chosen label
0.9999
Accuracy
100.0%
Macro F1
1

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.

Labels

LabelImagesShare of imagesMean score (labeled images)KnownPrecisionRecallF1
red50.29411.00005111
green40.23530.99984111
blue40.23530.99974111
yellow40.23531.00004111

Each label is embedded as a photo of a {label}. with the label filled in. Scores are softmax probabilities across the labels (they sum to 1).

Top labels per image

RowFileLabel 1Score 1Label 2Score 2Label 3Score 3Label 4Score 4Known label
1red_circle_1.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
2red_square_1.pngred1.0000blue7.675e-7yellow4.752e-7green4.568e-7red
3green_circle_1.pnggreen0.9999red3.881e-5blue3.725e-5yellow7.679e-6green
4green_square_1.pnggreen1.0000red1.266e-5blue1.134e-5yellow2.463e-6green
5blue_circle_1.pngblue1.0000red4.510e-5yellow2.744e-6green2.041e-6blue
6blue_square_1.pngblue1.0000red1.483e-5green1.156e-6yellow9.401e-7blue
7yellow_circle_1.pngyellow1.0000red1.210e-5blue7.562e-6green3.706e-6yellow
8yellow_square_1.pngyellow1.0000green1.652e-6red1.530e-6blue5.983e-7yellow
9red_circle_2.pngred0.9999yellow5.776e-5blue3.343e-5green7.213e-6red
10red_square_2.pngred1.0000yellow7.082e-7blue6.591e-7green3.169e-7red
11green_circle_2.pnggreen0.9995red0.0003blue0.0001yellow8.919e-5green
12green_square_2.pnggreen0.9999red8.516e-5blue3.818e-5yellow2.244e-5green
13blue_circle_2.pngblue0.9992red0.0007yellow7.249e-5green3.616e-5blue
14blue_square_2.pngblue0.9999red0.0001yellow2.006e-5green5.698e-6blue
15yellow_circle_2.pngyellow0.9999red4.148e-5green1.243e-5blue7.390e-6yellow
16yellow_square_2.pngyellow1.0000red2.760e-6green1.148e-6blue8.616e-7yellow
17red_circle_1_copy.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
  • 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 85dbfef898a61423
# 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 = "color"
CAPTION = None
df = pd.read_parquet("tests/parity/fixtures/clip_images.parquet", columns=["path", "color"])
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/colors_zero_shot/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 = "zero_shot"
KIND = "clip"
TOP_K = int(5)
LABELS, TEMPLATES, QUERIES, QPOS = [], [], [], []
if MODE == "zero_shot":
    LABELS = zs.split_labels("red, green, blue, yellow")
    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("")
    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/colors_zero_shot/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))


# %% Zero-shot labels: each label's template sentences averaged (prompt ensemble)
L, T = len(LABELS), len(TEMPLATES)
P = model.text_embed(it.prompts(LABELS, TEMPLATES))  # (T·L, d), template-major
V = it.label_vectors(P, L, T)
S = it.scores(E @ V.T, KIND, model.logit_scale, LOGIT_BIAS)  # images × labels
pred_idx = it.best(S)
pred = [LABELS[j] for j in pred_idx]
top = S[np.arange(n), pred_idx]
margin = it.margins(S)
per_template = [it.best(it.scores(E @ it.unit_rows(P[t * L:(t + 1) * L]).T, KIND, model.logit_scale, LOGIT_BIAS)) for t in range(T)]
values.update({"n_labels": L, "n_templates": T, "labels_text": ", ".join(LABELS), "mean_top_score": float(np.mean(top)),
               "mean_margin": float(np.mean(margin)), "template_agreement": it.agreement(per_template)})
counts = {lab: sum(1 for p in pred if p == lab) for lab in LABELS}
for j, lab in enumerate(LABELS):
    m = pred_idx == j
    values[f"n[{lab}]"] = counts[lab]
    values[f"share[{lab}]"] = counts[lab] / n
    values[f"mean_score[{lab}]"] = float(np.mean(S[m, j])) if m.any() else None
ev = None
if truth is not None:
    keep = [k for k, t in enumerate(truth) if t is not None and t in LABELS]
    n_not_in = sum(1 for t in truth if t is not None and t not in LABELS)
    if n_not_in:
        warnings.append(f"{n_not_in} known label(s) are not among the labels and are left out of the agreement figures.")
    if keep:
        ev = zs.classification([truth[k] for k in keep], [pred[k] for k in keep], LABELS)
        values.update({"n_evaluated": ev["n"], "accuracy": ev["accuracy"], "macro_f1": ev["macro_f1"], "balanced_accuracy": ev["balanced_accuracy"]})
        for r in ev["rows"]:
            values[f"f1[{r['label']}]"] = r["f1"]
        if T > 1:
            for t in range(T):
                values[f"accuracy_template[{t + 1}]"] = float(np.mean([LABELS[per_template[t][k]] == truth[k] for k in keep]))
    else:
        warnings.append("No image has a known label that is one of the labels, so agreement can't be computed.")
never = [lab for lab in LABELS if counts[lab] == 0]
if never:
    warnings.append(f"No image was given {', '.join(never)}.")
label_cols = [{"key": "label", "label": "Label", "type": "string"}, {"key": "images", "label": "Images", "type": "integer"},
              {"key": "share", "label": "Share of images", "type": "number"}, {"key": "score", "label": "Mean score (labeled images)", "type": "number"}]
label_rows = [{"label": lab, "images": counts[lab], "share": counts[lab] / n, "score": values[f"mean_score[{lab}]"]} for lab in LABELS]
if ev:
    label_cols += [{"key": "support", "label": "Known", "type": "integer"}, {"key": "precision", "label": "Precision", "type": "number"},
                   {"key": "recall", "label": "Recall", "type": "number"}, {"key": "f1", "label": "F1", "type": "number"}]
    for row, r in zip(label_rows, ev["rows"]):
        row.update({"support": r["support"], "precision": r["precision"], "recall": r["recall"], "f1": r["f1"]})
K = min(TOP_K, L)
img_cols = [{"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File", "type": "string"}]
for r in range(K):
    img_cols += [{"key": f"label_{r + 1}", "label": f"Label {r + 1}", "type": "string"}, {"key": f"score_{r + 1}", "label": f"Score {r + 1}", "type": "number"}]
if truth is not None:
    img_cols.append({"key": "known", "label": "Known label", "type": "string"})
SHOW = min(n, 100)
img_rows = []
for k in range(SHOW):
    rec = {"row": int(rows[k]) + 1, "file": files[k]}
    for r, j in enumerate(it.top_k(S[k], K)):
        rec[f"label_{r + 1}"] = LABELS[int(j)]
        rec[f"score_{r + 1}"] = float(S[k, j])
    if truth is not None:
        rec["known"] = truth[k]
    img_rows.append(rec)
note = "Scores are softmax probabilities across the labels (they sum to 1)." if KIND == "clip" else "Scores are SigLIP's pair scores (sigmoid); each label is scored on its own."
tables += [
    {"key": "labels", "title": "Labels", "columns": label_cols, "rows": label_rows,
     "note": f"Each label is embedded as {'; '.join(TEMPLATES)} with the label filled in" + (" and the sentences averaged. " if T > 1 else ". ") + note},
    {"key": "images", "title": "Top labels per image", "columns": img_cols, "rows": img_rows,
     "note": None if SHOW == n else f"The first {SHOW} of {n} images."},
]
for j, lab in enumerate(LABELS):
    best_k = it.top_k(S[:, j], min(TOP_K, n))
    add_gallery(lab, best_k, S[best_k, j])
charts.append(cs.chart("labels", "ngram-bars", "Images per label", {
    "term": cs.col("Label", LABELS, kind="categorical"), "count": cs.col("Images", [counts[lab] for lab in LABELS])}, controls={"top": min(L, 50)}))
charts.append(cs.chart("top_scores", "histogram", "Score of the chosen label", {"x": cs.col("Score", top)}))
if ev:
    keep = [k for k, t in enumerate(truth) if t is not None and t in LABELS]
    charts.append(cs.chart("confusion", "confusion-matrix", f"Zero-shot labels against {TRUTH}", {
        "actual": cs.col(TRUTH, [truth[k] for k in keep], kind="categorical", levels=LABELS),
        "predicted": cs.col("Zero-shot label", [pred[k] for k in keep], kind="categorical", levels=LABELS)}))
statistics += [{"key": "n_labels", "label": "Labels", "value": L}, {"key": "mean_top_score", "label": "Mean score of the chosen label", "value": values["mean_top_score"]}]
if values["template_agreement"] is not None:
    statistics.append({"key": "template_agreement", "label": "Same label under every template", "value": values["template_agreement"], "format": "percent"})
if ev:
    statistics += [{"key": "accuracy", "label": "Accuracy", "value": values["accuracy"], "format": "percent"},
                   {"key": "macro_f1", "label": "Macro F1", "value": values["macro_f1"]}]
lab_frame = pd.DataFrame({"row": rows, "cluster": pred_idx.astype(np.int64), "label": pred, "score": top, "margin": margin})
lab_frame.to_parquet(os.path.join(out, "labels.parquet"), index=False)
score_frame = pd.DataFrame({"row": rows, **{lab: S[:, j] for j, lab in enumerate(LABELS)}})
score_frame.to_parquet(os.path.join(out, "scores.parquet"), index=False)
artifacts += [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
              {"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}]
top_label = max(LABELS, key=lambda lab: (counts[lab], -LABELS.index(lab)))
summary = f"{n} images into {L} labels; most common {top_label} ({counts[top_label] / n:.0%})" + (f"; accuracy {values['accuracy']:.0%} against {TRUTH}." if ev 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,
})

The ranked thumbnails show, for each label, the images it fits best. Type your own labels, separated by commas, and watch which images move.

Ranked imagesWhich images fit a label or a search text best, and which images look most alike?
View data
imagefilelabelrankscore
demo:square:redred_square_1.pngred10.9340
demo:triangle:redred_triangle_2.pngred20.8660
demo:circle:redred_circle_3.pngred30.8320
demo:square:redred_square_4.pngred40.7410
demo:triangle:greengreen_triangle_1.pnggreen10.9530
demo:circle:greengreen_circle_2.pnggreen20.8600
demo:square:greengreen_square_3.pnggreen30.8100
demo:triangle:greengreen_triangle_4.pnggreen40.7560
demo:circle:blueblue_circle_1.pngblue10.9200
demo:square:blueblue_square_2.pngblue20.9020
demo:triangle:blueblue_triangle_3.pngblue30.8030
demo:circle:blueblue_circle_4.pngblue40.7300
demo:square:orangeorange_square_1.pngorange10.9370
demo:triangle:orangeorange_triangle_2.pngorange20.8950
demo:circle:orangeorange_circle_3.pngorange30.7910
demo:square:orangeorange_square_4.pngorange40.7780
04

Wording matters

Reflect

A prompt ensemblePrompt ensembleEach label is written into several sentences; their unit embeddings are averaged into one label vector, which steadies the labels. writes each label into several sentences and averages their vectors. It steadies the labels, and it also lets you measure how much the wording matters.

With two templates for the shapes, SigLIP gives 100.0% of the images the same label under each template on its own. When that share drops, the words you chose are driving the result, not the pictures.

Confusion matrixHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?
View data
churnedchurn_probability
no0.1130
no0.1960
no0.0150
no0.4510
no0.0820
no0.0180
yes0.9500
no0.5490
no0.1550
no0.5380
no0.2070
no0.1630
no0.0720
no0.4190
yes0.8590
no0.0530
no0.2970
no0.0430
no0.0910
no0.0760
no0.0610
no0.4490
no0.0870
no0.1210
no0.0970
no0.7310
no0.3160
no0.1260
no0.1460
no0.1380
no0.0600
no0.0700
no0.0640
no0.5060
no0.7570
no0.0910
no0.0910
no0.1450
no0.0850
yes0.9210
yes0.9000
no0.3470
no0.1580
no0.0060
no0.0520
no0.2120
no0.2060
no0.1880
yes0.8940
no0.5160
no0.0660
no0.0320
yes0.8820
no0.1710
no0.6350
no0.1400
no0.1350
no0.0600
no0.4720
no0.1760

First 60 of 1000 rows.

05

CLIP or SigLIP

Read

CLIP turns similarities into a softmax across your labels, so the scores of one image sum to one: it always picks a winner. SigLIP scores each image–label pair on its own, so an image can fit several labels, or none.

06

Search by text, or by image

Read

Text → image searchText → image searchEvery image is ranked by the cosine similarity of its embedding to a search text's embedding, best match first. ranks every image for a sentence. For "a red circle", the first image is row 9.

With a caption for each image, the app ranks every image for each caption and asks where the caption's own image lands. SigLIP puts it first for 47.1% of captions. Identical captions on look-alike drawings explain most of the misses: recall at kRecall at k (captions)Share of captions whose own image ranks in the top k when every image is ranked for that caption; the median rank sums it up. punishes ties the model can't break.

Image → image search ranks the look-alikesSimilar images (image → image)The other images ranked by the cosine similarity of their embeddings to a query image's; identical files score 1. of a query image. An exact copy of a file always comes first.

Image–text search and zero-shot labels (CLIP, SigLIP)Recorded · Python and R agreeRecorded 2026-11-25 · 46 values compared
R

The 4 most similar images of 2 query images among 17; mean similarity to the nearest other image 0.908.

Images
17
Query images
2
Mean similarity to the nearest other image
0.9077

Plots

Query images and their nearest imagesWhich images fit a label or a search text best, and which images look most alike?
View data
FileQueryImageRankCosine similarity
red_circle_1.pngRow 1: red_circle_1.png9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb11
red_circle_1_copy.pngRow 1: red_circle_1.png9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb21
red_circle_2.pngRow 1: red_circle_1.png5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f632130.8794
blue_circle_1.pngRow 1: red_circle_1.pngac9b3dde099f3243d0b992fc9bac26d3384e28638afc7a82efa35c622ce9c12f40.8703
yellow_circle_1.pngRow 1: red_circle_1.pngd7650e4851900cbbd716ef730decc1f99ed2da6e97b937bf8ce0a7bf5a6a64e450.8576
blue_square_1.pngRow 6: blue_square_1.pngbcf2583948f23afadb9eedbe7ed773103107e11d79522ae2bd5a1b8062fa738011
blue_square_2.pngRow 6: blue_square_1.png77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d920.9014
green_square_1.pngRow 6: blue_square_1.png8ca99c38a1f6c433614960aff2a8d7432eeeebd3654348c9988b0f9ba30e32c730.8785
red_square_1.pngRow 6: blue_square_1.pngc2da9720dabe35c5e764c0a9e57df8638d67b65ccc85bc35c96446af3852637640.8717
yellow_square_1.pngRow 6: blue_square_1.pngc37818ace5a34c68b5903a7aee70236022e599dc89a78dea4f5cbfa8cf53d3d350.8590
Similarity of each image to its nearest other imageHow is one numeric variable distributed?
View data
Cosine similarity
1
0.9034
0.8878
0.8827
0.8878
0.9014
0.8636
0.8937
0.8794
0.9034
0.9262
0.9069
0.9262
0.9069
0.8679
0.8937
1
Image map (first two principal components of the embeddings)Which rows group together, and how well separated are the groups?
View data
colorPC 1PC 2
red0.33470.2984
red−0.28390.2952
green0.17210.1685
green−0.30150.1529
blue0.24750.0618
blue−0.28080.0773
yellow0.17690.1547
yellow−0.33990.1976
red0.3175−0.1227
red−0.2224−0.0265
green0.2007−0.2935
green−0.2048−0.2399
blue0.2314−0.3410
blue−0.2016−0.2745
yellow0.1155−0.2591
yellow−0.2960−0.1475
red0.33470.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.

Most similar images

Query rowQuery fileRankRowFileCosine similarity
1red_circle_1.png117red_circle_1_copy.png1
1red_circle_1.png29red_circle_2.png0.8794
1red_circle_1.png35blue_circle_1.png0.8703
1red_circle_1.png47yellow_circle_1.png0.8576
6blue_square_1.png114blue_square_2.png0.9014
6blue_square_1.png24green_square_1.png0.8785
6blue_square_1.png32red_square_1.png0.8717
6blue_square_1.png48yellow_square_1.png0.8590
  • 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 3438fe2dbda1d0f0
# 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 <- "color"
CAPTION <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clip_images.parquet", col_select = c("path", "color")))
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/image_query_rows/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 <- "image_search"
KIND <- "clip"
TOP_K <- as.integer(4)
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("")
  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("1, 6")
  if (is.null(QROWS)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers separated by commas", value = "1, 6")
  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/image_query_rows/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))
}

# %% Image -> image similarity: the other images ranked by cosine similarity to each query image
sim <- E %*% t(E)
nn <- vapply(seq_len(n), function(i) sim[i, cs_imagetext_top_k(sim[i, ], 1, exclude = i)[1]], 0)
values$n_queries <- length(QPOS); values$mean_nn_similarity <- mean(nn)
K <- min(TOP_K, n - 1L)
b_qrow <- integer(0); b_qfile <- character(0); b_rank <- integer(0); b_row <- integer(0); b_file <- character(0); b_sim <- numeric(0)
for (qi in seq_along(QPOS)) {
  i <- QPOS[qi]
  best_k <- cs_imagetext_top_k(sim[i, ], K, exclude = i)
  b_qrow <- c(b_qrow, rep(rows[i] + 1L, length(best_k))); b_qfile <- c(b_qfile, rep(files[i], length(best_k)))
  b_rank <- c(b_rank, seq_along(best_k)); b_row <- c(b_row, rows[best_k] + 1L); b_file <- c(b_file, files[best_k]); b_sim <- c(b_sim, sim[i, best_k])
  if (qi <= 10) for (r in seq_along(best_k)) {
    values[[sprintf("neighbor_row[%d.%d]", qi, r)]] <- rows[best_k[r]] + 1L
    values[[sprintf("neighbor_similarity[%d.%d]", qi, r)]] <- sim[i, best_k[r]]
  }
  if (qi <= 20) add_gallery(sprintf("Row %d: %s", rows[i] + 1L, files[i]), c(i, best_k), c(1, sim[i, best_k]))
}
nb_cols <- list(list(key = "query_row", label = "Query row", type = "integer"), list(key = "query_file", label = "Query file", 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"))
n_nb <- length(b_rank)
shown <- seq_len(min(n_nb, 500L))
nb_rows <- lapply(shown, function(i) list(query_row = b_qrow[i], query_file = b_qfile[i], rank = b_rank[i], row = b_row[i], file = b_file[i], similarity = b_sim[i]))
tables[[length(tables) + 1]] <- list(key = "neighbors", title = "Most similar images", columns = nb_cols, rows = nb_rows,
                                     note = if (length(shown) == n_nb) NULL else sprintf("The first %d of %d neighbors.", length(shown), n_nb))
statistics <- c(statistics, list(list(key = "n_queries", label = "Query images", value = length(QPOS)),
                                 list(key = "mean_nn_similarity", label = "Mean similarity to the nearest other image", value = values$mean_nn_similarity)))
charts[[length(charts) + 1]] <- cs_chart("nearest", "histogram", "Similarity of each image to its nearest other image", list(x = cs_col("Cosine similarity", nn)))
nanoparquet::write_parquet(data.frame(query_row = b_qrow, query_file = b_qfile, rank = b_rank, row = b_row, file = b_file, similarity = b_sim),
                           file.path(out, "neighbors.parquet"))
artifacts[[length(artifacts) + 1]] <- list(key = "neighbors", path = file.path(out, "neighbors.parquet"), format = "parquet")
summary <- sprintf("The %d most similar images of %d query image%s among %d; mean similarity to the nearest other image %.3f.",
                   K, length(QPOS), if (length(QPOS) != 1) "s" else "", n, values$mean_nn_similarity)

# %% 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
))
Python

The 4 most similar images of 2 query images among 17; mean similarity to the nearest other image 0.908.

Images
17
Query images
2
Mean similarity to the nearest other image
0.9077

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.

Most similar images

Query rowQuery fileRankRowFileCosine similarity
1red_circle_1.png117red_circle_1_copy.png1.000
1red_circle_1.png29red_circle_2.png0.8794
1red_circle_1.png35blue_circle_1.png0.8703
1red_circle_1.png47yellow_circle_1.png0.8576
6blue_square_1.png114blue_square_2.png0.9014
6blue_square_1.png24green_square_1.png0.8785
6blue_square_1.png32red_square_1.png0.8717
6blue_square_1.png48yellow_square_1.png0.8590
  • 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 3438fe2dbda1d0f0
# 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 = "color"
CAPTION = None
df = pd.read_parquet("tests/parity/fixtures/clip_images.parquet", columns=["path", "color"])
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/image_query_rows/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 = "image_search"
KIND = "clip"
TOP_K = int(4)
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("")
    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("1, 6")
    if QROWS is None:
        cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers separated by commas", value="1, 6")
    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/image_query_rows/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))


# %% Image → image similarity: the other images ranked by cosine similarity to each query image
sim = E @ E.T
nn = np.array([float(sim[i, it.top_k(sim[i], 1, exclude=i)[0]]) for i in range(n)])
values.update({"n_queries": len(QPOS), "mean_nn_similarity": float(np.mean(nn))})
K = min(TOP_K, n - 1)
nb_rows = []
for qi, i in enumerate(QPOS):
    best_k = it.top_k(sim[i], K, exclude=i)
    for r, k in enumerate(best_k, start=1):
        nb_rows.append({"query_row": int(rows[i]) + 1, "query_file": files[i], "rank": r, "row": int(rows[k]) + 1, "file": files[k],
                        "similarity": float(sim[i, k])})
        if qi < 10:
            values[f"neighbor_row[{qi + 1}.{r}]"] = int(rows[k]) + 1
            values[f"neighbor_similarity[{qi + 1}.{r}]"] = float(sim[i, k])
    if qi < 20:
        add_gallery(f"Row {int(rows[i]) + 1}: {files[i]}", [i] + [int(k) for k in best_k], [1.0] + [float(sim[i, k]) for k in best_k])
nb_cols = [{"key": "query_row", "label": "Query row", "type": "integer"}, {"key": "query_file", "label": "Query file", "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"}]
SHOWN = nb_rows[:500]
tables.append({"key": "neighbors", "title": "Most similar images", "columns": nb_cols, "rows": SHOWN,
               "note": None if len(SHOWN) == len(nb_rows) else f"The first {len(SHOWN)} of {len(nb_rows)} neighbors."})
statistics += [{"key": "n_queries", "label": "Query images", "value": len(QPOS)},
               {"key": "mean_nn_similarity", "label": "Mean similarity to the nearest other image", "value": values["mean_nn_similarity"]}]
charts.append(cs.chart("nearest", "histogram", "Similarity of each image to its nearest other image", {"x": cs.col("Cosine similarity", nn)}))
pd.DataFrame(nb_rows).to_parquet(os.path.join(out, "neighbors.parquet"), index=False)
artifacts.append({"key": "neighbors", "path": os.path.join(out, "neighbors.parquet"), "format": "parquet"})
summary = f"The {K} most similar images of {len(QPOS)} query image{'s' if len(QPOS) != 1 else ''} among {n}; mean similarity to the nearest other image {values['mean_nn_similarity']:.3f}."

# %% 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,
})
07

Check your understanding

Checkpoint

Check yourself

A photo shows a dog and a cat. With CLIP and the labels "dog" and "cat", the scores are close to one half each. What would SigLIP be able to say that CLIP can't?

Show the answer

Answer: a

CLIP's softmax shares one unit of score across the labels, so two good labels split it. SigLIP's sigmoid scores each image–label pair separately, so both can be high.

Check yourself

Many of your images change label from one template to another. What's the best next step?

Show the answer

Answer: a

Low agreement means the wording, not the picture, decides many labels. Averaging hides the disagreement but doesn't remove it; looking at the images that flip shows which label or template is unclear.

Check yourself

Recall at 1 for your captions is low, but recall at 5 is high. What's the most likely reading?

Show the answer

Answer: a

When the own image is in the top five but rarely first, near-duplicates or generic captions are crowding the first place. Read the matches before blaming the model.

08

Recap

Recap
  • CLIP and SigLIP put images and texts in one space, so any words can label or search images without training.
  • The wording of labels and templates changes the result: compare templates and read the images that flip.
  • CLIP's scores split across labels; SigLIP's don't. Neither is calibrated.
  • Text search, caption recall and look-alike search all rank by cosine similarity, and ties keep row order.

Concepts in this lesson