SigLIP and zero-shot labels in practice
SigLIP's per-pair sigmoid loss and what it changes, then labeling images from your own words: label sentences, prompt ensembles, the closed-label trap of softmax scores, and checking against known labels.
What runs in CodeSplash
- MM003SigLIP family, including SigLIP 2 Partly runs in CodeSplash (Experimental)
- Image–text search and zero-shot labels (CLIP, SigLIP) Experimental
You will be able to
- Contrast SigLIP's sigmoid loss with CLIP's batch softmax
- Write label sentences and use several templates per label
- Explain why softmax scores always pick one of your labels
- Check zero-shot labels against a sample of known ones before using them
SigLIP: one pair at a time
ReadSigLIPSigLIPA CLIP-like image–text model trained with a sigmoid loss: it scores each image–text pair on its own instead of across a batch. keeps CLIP's two towers but changes the loss. Instead of a softmax over the whole batch, every image–text pair becomes its own yes-or-no question, scored with a sigmoid: matched pairs should score high, all others low, each judged alone.
In the program a 2 × 2 batch has its matched pairs labeled +1 and the rest −1; the average logistic loss is 0.339. No pair's score depends on the others, so the loss needs no batch-wide normalization: huge batches are cheaper, and small ones still train well. SigLIP 2 adds captioning and self-distillation objectives and more languages.
Labels from your words
ReadZero-shot labelsZero-shot image labelsEach image gets the label whose sentence, like 'a photo of a {label}.', fits it best; no labeled training images are needed. need no training images. Write each label into a sentence ("a photo of a red apple"), embed the sentences once, and give each image the label whose sentence is most similar:
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
View data
| File | Label | Image | Rank | Score |
|---|---|---|---|---|
| red_square_2.png | red | 434e2ec8acd8699a94f5db3be0f41ab8101c8157f523a05e1db05a7ea975a55f | 1 | 1.0000 |
| red_square_1.png | red | c2da9720dabe35c5e764c0a9e57df8638d67b65ccc85bc35c96446af38526376 | 2 | 1.0000 |
| red_circle_1.png | red | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 3 | 1.0000 |
| red_circle_1_copy.png | red | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 4 | 1.0000 |
| red_circle_2.png | red | 5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f6321 | 5 | 0.9999 |
| green_square_1.png | green | 8ca99c38a1f6c433614960aff2a8d7432eeeebd3654348c9988b0f9ba30e32c7 | 1 | 1.0000 |
| green_circle_1.png | green | 33a634b9fb3326da6edf75bc17755bbf236a4cf0e7b2349a6dbbd4790ad909e1 | 2 | 0.9999 |
| green_square_2.png | green | f0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a21 | 3 | 0.9999 |
| green_circle_2.png | green | c125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f13 | 4 | 0.9995 |
| blue_circle_2.png | green | 727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a808 | 5 | 3.616e-5 |
| blue_square_1.png | blue | bcf2583948f23afadb9eedbe7ed773103107e11d79522ae2bd5a1b8062fa7380 | 1 | 1.0000 |
| blue_circle_1.png | blue | ac9b3dde099f3243d0b992fc9bac26d3384e28638afc7a82efa35c622ce9c12f | 2 | 1.0000 |
| blue_square_2.png | blue | 77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d9 | 3 | 0.9999 |
| blue_circle_2.png | blue | 727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a808 | 4 | 0.9992 |
| green_circle_2.png | blue | c125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f13 | 5 | 0.0001 |
| yellow_square_1.png | yellow | c37818ace5a34c68b5903a7aee70236022e599dc89a78dea4f5cbfa8cf53d3d3 | 1 | 1.0000 |
| yellow_square_2.png | yellow | fa76bf14a0ba2ef56e8166402e88d235460ce6ea91d115ad87bbc8ec9a500ed0 | 2 | 1.0000 |
| yellow_circle_1.png | yellow | d7650e4851900cbbd716ef730decc1f99ed2da6e97b937bf8ce0a7bf5a6a64e4 | 3 | 1.0000 |
| yellow_circle_2.png | yellow | 604a35801ef2627525250e1f7dd474fa9f79e7f5e8ca8452de2cceb6ee67040f | 4 | 0.9999 |
| green_circle_2.png | yellow | c125e99541f94beca9d2d051595926fe9131dcab8e707e6fa273c7785cc88f13 | 5 | 8.919e-5 |
View data
| Images | Label |
|---|---|
| 5 | red |
| 4 | green |
| 4 | blue |
| 4 | yellow |
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 |
View data
| color | Zero-shot label |
|---|---|
| red | red |
| red | red |
| green | green |
| green | green |
| blue | blue |
| blue | blue |
| yellow | yellow |
| yellow | yellow |
| red | red |
| red | red |
| green | green |
| green | green |
| blue | blue |
| blue | blue |
| yellow | yellow |
| yellow | yellow |
| red | red |
View data
| Zero-shot label | PC 1 | PC 2 |
|---|---|---|
| red | 0.3347 | 0.2984 |
| red | −0.2839 | 0.2952 |
| green | 0.1721 | 0.1685 |
| green | −0.3015 | 0.1529 |
| blue | 0.2475 | 0.0618 |
| blue | −0.2808 | 0.0773 |
| yellow | 0.1769 | 0.1547 |
| yellow | −0.3399 | 0.1976 |
| red | 0.3175 | −0.1227 |
| red | −0.2224 | −0.0265 |
| green | 0.2007 | −0.2935 |
| green | −0.2048 | −0.2399 |
| blue | 0.2314 | −0.3410 |
| blue | −0.2016 | −0.2745 |
| yellow | 0.1155 | −0.2591 |
| yellow | −0.2960 | −0.1475 |
| red | 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.
Labels
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| red | 5 | 0.2941 | 1.0000 | 5 | 1 | 1 | 1 |
| green | 4 | 0.2353 | 0.9998 | 4 | 1 | 1 | 1 |
| blue | 4 | 0.2353 | 0.9997 | 4 | 1 | 1 | 1 |
| yellow | 4 | 0.2353 | 1.0000 | 4 | 1 | 1 | 1 |
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
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Label 3 | Score 3 | Label 4 | Score 4 | Known label |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
| 2 | red_square_1.png | red | 1.0000 | blue | 7.675e-7 | yellow | 4.752e-7 | green | 4.568e-7 | red |
| 3 | green_circle_1.png | green | 0.9999 | red | 3.881e-5 | blue | 3.725e-5 | yellow | 7.679e-6 | green |
| 4 | green_square_1.png | green | 1.0000 | red | 1.266e-5 | blue | 1.134e-5 | yellow | 2.463e-6 | green |
| 5 | blue_circle_1.png | blue | 1.0000 | red | 4.510e-5 | yellow | 2.744e-6 | green | 2.041e-6 | blue |
| 6 | blue_square_1.png | blue | 1.0000 | red | 1.483e-5 | green | 1.156e-6 | yellow | 9.401e-7 | blue |
| 7 | yellow_circle_1.png | yellow | 1.0000 | red | 1.210e-5 | blue | 7.562e-6 | green | 3.706e-6 | yellow |
| 8 | yellow_square_1.png | yellow | 1.0000 | green | 1.652e-6 | red | 1.530e-6 | blue | 5.983e-7 | yellow |
| 9 | red_circle_2.png | red | 0.9999 | yellow | 5.776e-5 | blue | 3.343e-5 | green | 7.213e-6 | red |
| 10 | red_square_2.png | red | 1.0000 | yellow | 7.082e-7 | blue | 6.591e-7 | green | 3.169e-7 | red |
| 11 | green_circle_2.png | green | 0.9995 | red | 0.0003 | blue | 0.0001 | yellow | 8.919e-5 | green |
| 12 | green_square_2.png | green | 0.9999 | red | 8.516e-5 | blue | 3.818e-5 | yellow | 2.244e-5 | green |
| 13 | blue_circle_2.png | blue | 0.9992 | red | 0.0007 | yellow | 7.249e-5 | green | 3.616e-5 | blue |
| 14 | blue_square_2.png | blue | 0.9999 | red | 0.0001 | yellow | 2.006e-5 | green | 5.698e-6 | blue |
| 15 | yellow_circle_2.png | yellow | 0.9999 | red | 4.148e-5 | green | 1.243e-5 | blue | 7.390e-6 | yellow |
| 16 | yellow_square_2.png | yellow | 1.0000 | red | 2.760e-6 | green | 1.148e-6 | blue | 8.616e-7 | yellow |
| 17 | red_circle_1_copy.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
- 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
))
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
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| red | 5 | 0.2941 | 1.0000 | 5 | 1 | 1 | 1 |
| green | 4 | 0.2353 | 0.9998 | 4 | 1 | 1 | 1 |
| blue | 4 | 0.2353 | 0.9997 | 4 | 1 | 1 | 1 |
| yellow | 4 | 0.2353 | 1.0000 | 4 | 1 | 1 | 1 |
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
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Label 3 | Score 3 | Label 4 | Score 4 | Known label |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
| 2 | red_square_1.png | red | 1.0000 | blue | 7.675e-7 | yellow | 4.752e-7 | green | 4.568e-7 | red |
| 3 | green_circle_1.png | green | 0.9999 | red | 3.881e-5 | blue | 3.725e-5 | yellow | 7.679e-6 | green |
| 4 | green_square_1.png | green | 1.0000 | red | 1.266e-5 | blue | 1.134e-5 | yellow | 2.463e-6 | green |
| 5 | blue_circle_1.png | blue | 1.0000 | red | 4.510e-5 | yellow | 2.744e-6 | green | 2.041e-6 | blue |
| 6 | blue_square_1.png | blue | 1.0000 | red | 1.483e-5 | green | 1.156e-6 | yellow | 9.401e-7 | blue |
| 7 | yellow_circle_1.png | yellow | 1.0000 | red | 1.210e-5 | blue | 7.562e-6 | green | 3.706e-6 | yellow |
| 8 | yellow_square_1.png | yellow | 1.0000 | green | 1.652e-6 | red | 1.530e-6 | blue | 5.983e-7 | yellow |
| 9 | red_circle_2.png | red | 0.9999 | yellow | 5.776e-5 | blue | 3.343e-5 | green | 7.213e-6 | red |
| 10 | red_square_2.png | red | 1.0000 | yellow | 7.082e-7 | blue | 6.591e-7 | green | 3.169e-7 | red |
| 11 | green_circle_2.png | green | 0.9995 | red | 0.0003 | blue | 0.0001 | yellow | 8.919e-5 | green |
| 12 | green_square_2.png | green | 0.9999 | red | 8.516e-5 | blue | 3.818e-5 | yellow | 2.244e-5 | green |
| 13 | blue_circle_2.png | blue | 0.9992 | red | 0.0007 | yellow | 7.249e-5 | green | 3.616e-5 | blue |
| 14 | blue_square_2.png | blue | 0.9999 | red | 0.0001 | yellow | 2.006e-5 | green | 5.698e-6 | blue |
| 15 | yellow_circle_2.png | yellow | 0.9999 | red | 4.148e-5 | green | 1.243e-5 | blue | 7.390e-6 | yellow |
| 16 | yellow_square_2.png | yellow | 1.0000 | red | 2.760e-6 | green | 1.148e-6 | blue | 8.616e-7 | yellow |
| 17 | red_circle_1_copy.png | red | 1.0000 | blue | 2.575e-5 | yellow | 4.918e-6 | green | 1.101e-6 | red |
- 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 wording matters. "red" alone is a weak caption; "a photo of a red object" reads like the web captions the model learned from. A prompt ensemblePrompt ensembleEach label is written into several sentences; their unit embeddings are averaged into one label vector, which steadies the labels. averages several templates per label and usually beats any single one.
Two templates, two labels
ReadHere SigLIP labels shapes with two templates per label and keeps the top 2 labels per image:
17 images into 3 labels; most common circle (53%); accuracy 100% against shape.
- Images
- 17
- Labels
- 3
- Mean score of the chosen label
- 0.2810
- Same label under every template
- 100.0%
- Accuracy
- 100.0%
- Macro F1
- 1
Plots
View data
| File | Label | Image | Rank | Score |
|---|---|---|---|---|
| blue_circle_2.png | circle | 727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a808 | 1 | 0.4804 |
| red_circle_2.png | circle | 5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f6321 | 2 | 0.2761 |
| blue_square_2.png | square | 77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d9 | 1 | 0.8803 |
| green_square_2.png | square | f0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a21 | 2 | 0.5243 |
| blue_square_2.png | triangle | 77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d9 | 1 | 0.0003 |
| green_square_2.png | triangle | f0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a21 | 2 | 0.0002 |
View data
| Images | Label |
|---|---|
| 9 | circle |
| 8 | square |
| 0 | triangle |
View data
| Score |
|---|
| 0.1498 |
| 0.0775 |
| 0.0857 |
| 0.2186 |
| 0.2737 |
| 0.3542 |
| 0.1506 |
| 0.0229 |
| 0.2761 |
| 0.4894 |
| 0.2624 |
| 0.5243 |
| 0.4804 |
| 0.8803 |
| 0.0823 |
| 0.2998 |
| 0.1498 |
View data
| shape | Zero-shot label |
|---|---|
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
View data
| Zero-shot label | PC 1 | PC 2 |
|---|---|---|
| circle | 0.1938 | 0.2588 |
| square | −0.3056 | 0.2213 |
| circle | 0.2188 | −0.0500 |
| square | −0.2924 | −0.0631 |
| circle | 0.2235 | −0.0702 |
| square | −0.2789 | −0.0740 |
| circle | 0.1948 | 0.0895 |
| square | −0.2995 | 0.1123 |
| circle | 0.2414 | 0.0708 |
| square | −0.2459 | 0.1037 |
| circle | 0.2612 | −0.1872 |
| square | −0.2162 | −0.1907 |
| circle | 0.2560 | −0.1994 |
| square | −0.2027 | −0.2231 |
| circle | 0.2685 | −0.0402 |
| square | −0.2106 | −0.0174 |
| circle | 0.1938 | 0.2588 |
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 — 100% of images get the same label under every template.
- 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
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| circle | 9 | 0.5294 | 0.2123 | 9 | 1 | 1 | 1 |
| square | 8 | 0.4706 | 0.3584 | 8 | 1 | 1 | 1 |
| triangle | 0 | 0 | — | 0 | — | — | — |
Each label is embedded as a {label}.; a drawing of a {label}. with the label filled in and the sentences averaged. Scores are SigLIP's pair scores (sigmoid); each label is scored on its own.
Top labels per image
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Known label |
|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | circle | 0.1498 | square | 0.0010 | circle |
| 2 | red_square_1.png | square | 0.0775 | triangle | 9.148e-6 | square |
| 3 | green_circle_1.png | circle | 0.0857 | square | 0.0002 | circle |
| 4 | green_square_1.png | square | 0.2186 | triangle | 2.133e-5 | square |
| 5 | blue_circle_1.png | circle | 0.2737 | square | 0.0009 | circle |
| 6 | blue_square_1.png | square | 0.3542 | circle | 2.780e-5 | square |
| 7 | yellow_circle_1.png | circle | 0.1506 | square | 0.0007 | circle |
| 8 | yellow_square_1.png | square | 0.0229 | triangle | 7.739e-6 | square |
| 9 | red_circle_2.png | circle | 0.2761 | square | 0.0033 | circle |
| 10 | red_square_2.png | square | 0.4894 | triangle | 7.280e-5 | square |
| 11 | green_circle_2.png | circle | 0.2624 | square | 0.0017 | circle |
| 12 | green_square_2.png | square | 0.5243 | triangle | 0.0002 | square |
| 13 | blue_circle_2.png | circle | 0.4804 | square | 0.0034 | circle |
| 14 | blue_square_2.png | square | 0.8803 | circle | 0.0004 | square |
| 15 | yellow_circle_2.png | circle | 0.0823 | square | 0.0005 | circle |
| 16 | yellow_square_2.png | square | 0.2998 | circle | 0.0001 | square |
| 17 | red_circle_1_copy.png | circle | 0.1498 | square | 0.0010 | circle |
- 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
- No image was given triangle.
- Model: SigLIP base/16 (WebLI). 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 a202496df135026d
# 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 <- "shape"
CAPTION <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clip_images.parquet", col_select = c("path", "shape")))
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\":\"stretch\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.5,0.5,0.5],\"std\":[0.5,0.5,0.5]},\"size\":[224,224]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/discover.image_text/shapes_two_templates_siglip/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 <- "siglip"
TOP_K <- as.integer(2)
LABELS <- character(0); TEMPLATES <- character(0); QUERIES <- character(0); QPOS <- integer(0)
if (MODE == "zero_shot") {
LABELS <- cs_search_split_labels("circle; square; triangle")
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 {label}.; a drawing 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 (SigLIP base/16, double precision, one image at a time)
if (!cs_siglip_available()) cs_error("CS_WEIGHTS_MISSING", model = "SigLIP base/16 (WebLI)")
model <- cs_siglip_load()
NAME <- "SigLIP base/16 (WebLI)"
embed_images <- function(x) cs_siglip_image_embed(model, x)
embed_texts <- function(t) cs_siglip_text_embed(model, t)
LOGIT_BIAS <- model$logit_bias
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/shapes_two_templates_siglip/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
))
17 images into 3 labels; most common circle (53%); accuracy 100% against shape.
- Images
- 17
- Labels
- 3
- Mean score of the chosen label
- 0.2810
- Same label under every template
- 100.0%
- 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 — 100% of images get the same label under every template.
- 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
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| circle | 9 | 0.5294 | 0.2123 | 9 | 1 | 1 | 1 |
| square | 8 | 0.4706 | 0.3584 | 8 | 1 | 1 | 1 |
| triangle | 0 | 0 | — | 0 | — | — | — |
Each label is embedded as a {label}.; a drawing of a {label}. with the label filled in and the sentences averaged. Scores are SigLIP's pair scores (sigmoid); each label is scored on its own.
Top labels per image
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Known label |
|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | circle | 0.1498 | square | 0.0010 | circle |
| 2 | red_square_1.png | square | 0.0775 | triangle | 9.148e-6 | square |
| 3 | green_circle_1.png | circle | 0.0857 | square | 0.0002 | circle |
| 4 | green_square_1.png | square | 0.2186 | triangle | 2.133e-5 | square |
| 5 | blue_circle_1.png | circle | 0.2737 | square | 0.0009 | circle |
| 6 | blue_square_1.png | square | 0.3542 | circle | 2.780e-5 | square |
| 7 | yellow_circle_1.png | circle | 0.1506 | square | 0.0007 | circle |
| 8 | yellow_square_1.png | square | 0.0229 | triangle | 7.739e-6 | square |
| 9 | red_circle_2.png | circle | 0.2761 | square | 0.0033 | circle |
| 10 | red_square_2.png | square | 0.4894 | triangle | 7.280e-5 | square |
| 11 | green_circle_2.png | circle | 0.2624 | square | 0.0017 | circle |
| 12 | green_square_2.png | square | 0.5243 | triangle | 0.0002 | square |
| 13 | blue_circle_2.png | circle | 0.4804 | square | 0.0034 | circle |
| 14 | blue_square_2.png | square | 0.8803 | circle | 0.0004 | square |
| 15 | yellow_circle_2.png | circle | 0.0823 | square | 0.0005 | circle |
| 16 | yellow_square_2.png | square | 0.2998 | circle | 0.0001 | square |
| 17 | red_circle_1_copy.png | circle | 0.1498 | square | 0.0010 | circle |
- 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
- No image was given triangle.
- Model: SigLIP base/16 (WebLI). 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 a202496df135026d
# 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 siglip as tower # SigLIP base/16 written out on torch (twin: cs_siglip_*)
# %% Data (rows with an image path; known labels and captions may be missing)
IMAGE = "path"
TRUTH = "shape"
CAPTION = None
df = pd.read_parquet("tests/parity/fixtures/clip_images.parquet", columns=["path", "shape"])
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\":\"stretch\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.5,0.5,0.5],\"std\":[0.5,0.5,0.5]},\"size\":[224,224]}}"), "target/academy-parity/run-8142/discover.image_text/shapes_two_templates_siglip/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 = "siglip"
TOP_K = int(2)
LABELS, TEMPLATES, QUERIES, QPOS = [], [], [], []
if MODE == "zero_shot":
LABELS = zs.split_labels("circle; square; triangle")
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 {label}.; a drawing 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 (SigLIP base/16, 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/shapes_two_templates_siglip/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,
})
With CLIP, an image's scores across your labels sum to 1, because they come from a softmax. With SigLIP each label gets its own sigmoid score, so two labels can both fit and none may fit at all.
The closed-label trap
PredictPredict first
You ask CLIP to label a photo of a bicycle with only two labels: "cat" and "dog". What do the scores look like?
Reveal
One label gets most of the score anyway. Softmax scores always sum to 1 across the labels you give, so the bicycle becomes a confident cat or dog. Add an "other" label, look at the raw similarity, or use SigLIP's independent scores to catch it.
Check before you trust
ReadZero-shot labels are a model's guess with the model's habits. Label a sample by hand, or use a column you already have, and measure agreement before relying on the rest:
17 images into 2 labels; most common circle (53%); accuracy 100% against shape.
- Images
- 17
- Labels
- 2
- Mean score of the chosen label
- 0.9912
- Same label under every template
- 100.0%
- Accuracy
- 100.0%
- Macro F1
- 1
- Mean CLIPScore (captions)
- 0.7502
Plots
View data
| File | Label | Image | Rank | Score |
|---|---|---|---|---|
| green_circle_1.png | circle | 33a634b9fb3326da6edf75bc17755bbf236a4cf0e7b2349a6dbbd4790ad909e1 | 1 | 0.9970 |
| yellow_circle_1.png | circle | d7650e4851900cbbd716ef730decc1f99ed2da6e97b937bf8ce0a7bf5a6a64e4 | 2 | 0.9931 |
| red_circle_1.png | circle | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 3 | 0.9926 |
| red_circle_1_copy.png | circle | 9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb | 4 | 0.9926 |
| blue_circle_1.png | circle | ac9b3dde099f3243d0b992fc9bac26d3384e28638afc7a82efa35c622ce9c12f | 5 | 0.9925 |
| blue_square_2.png | square | 77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d9 | 1 | 0.9999 |
| green_square_2.png | square | f0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a21 | 2 | 0.9999 |
| red_square_2.png | square | 434e2ec8acd8699a94f5db3be0f41ab8101c8157f523a05e1db05a7ea975a55f | 3 | 0.9998 |
| blue_square_1.png | square | bcf2583948f23afadb9eedbe7ed773103107e11d79522ae2bd5a1b8062fa7380 | 4 | 0.9998 |
| yellow_square_2.png | square | fa76bf14a0ba2ef56e8166402e88d235460ce6ea91d115ad87bbc8ec9a500ed0 | 5 | 0.9997 |
View data
| Images | Label |
|---|---|
| 9 | circle |
| 8 | square |
View data
| Score |
|---|
| 0.9926 |
| 0.9988 |
| 0.9970 |
| 0.9997 |
| 0.9925 |
| 0.9998 |
| 0.9931 |
| 0.9984 |
| 0.9723 |
| 0.9998 |
| 0.9816 |
| 0.9999 |
| 0.9783 |
| 0.9999 |
| 0.9543 |
| 0.9997 |
| 0.9926 |
View data
| shape | Zero-shot label |
|---|---|
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
| square | square |
| circle | circle |
View data
| Zero-shot label | PC 1 | PC 2 |
|---|---|---|
| circle | 0.3347 | 0.2984 |
| square | −0.2839 | 0.2952 |
| circle | 0.1721 | 0.1685 |
| square | −0.3015 | 0.1529 |
| circle | 0.2475 | 0.0618 |
| square | −0.2808 | 0.0773 |
| circle | 0.1769 | 0.1547 |
| square | −0.3399 | 0.1976 |
| circle | 0.3175 | −0.1227 |
| square | −0.2224 | −0.0265 |
| circle | 0.2007 | −0.2935 |
| square | −0.2048 | −0.2399 |
| circle | 0.2314 | −0.3410 |
| square | −0.2016 | −0.2745 |
| circle | 0.1155 | −0.2591 |
| square | −0.2960 | −0.1475 |
| circle | 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 — 100% of images get the same label under every template.
- 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
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| circle | 9 | 0.5294 | 0.9838 | 9 | 1 | 1 | 1 |
| square | 8 | 0.4706 | 0.9995 | 8 | 1 | 1 | 1 |
Each label is embedded as a photo of a {label}.; a {label} shape. with the label filled in and the sentences averaged. Scores are softmax probabilities across the labels (they sum to 1).
Top labels per image
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Known label |
|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | circle | 0.9926 | square | 0.0074 | circle |
| 2 | red_square_1.png | square | 0.9988 | circle | 0.0012 | square |
| 3 | green_circle_1.png | circle | 0.9970 | square | 0.0030 | circle |
| 4 | green_square_1.png | square | 0.9997 | circle | 0.0003 | square |
| 5 | blue_circle_1.png | circle | 0.9925 | square | 0.0075 | circle |
| 6 | blue_square_1.png | square | 0.9998 | circle | 0.0002 | square |
| 7 | yellow_circle_1.png | circle | 0.9931 | square | 0.0069 | circle |
| 8 | yellow_square_1.png | square | 0.9984 | circle | 0.0016 | square |
| 9 | red_circle_2.png | circle | 0.9723 | square | 0.0277 | circle |
| 10 | red_square_2.png | square | 0.9998 | circle | 0.0002 | square |
| 11 | green_circle_2.png | circle | 0.9816 | square | 0.0184 | circle |
| 12 | green_square_2.png | square | 0.9999 | circle | 7.638e-5 | square |
| 13 | blue_circle_2.png | circle | 0.9783 | square | 0.0217 | circle |
| 14 | blue_square_2.png | square | 0.9999 | circle | 6.617e-5 | square |
| 15 | yellow_circle_2.png | circle | 0.9543 | square | 0.0457 | circle |
| 16 | yellow_square_2.png | square | 0.9997 | circle | 0.0003 | square |
| 17 | red_circle_1_copy.png | circle | 0.9926 | square | 0.0074 | circle |
- 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 b3d0e15cbfe0900f
# 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 <- "shape"
CAPTION <- "caption"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clip_images.parquet", col_select = c("path", "shape", "caption")))
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/labels_from_known_levels/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("")
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}.; a {label} shape.")
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/labels_from_known_levels/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
))
17 images into 2 labels; most common circle (53%); accuracy 100% against shape.
- Images
- 17
- Labels
- 2
- Mean score of the chosen label
- 0.9912
- Same label under every template
- 100.0%
- Accuracy
- 100.0%
- Macro F1
- 1
- Mean CLIPScore (captions)
- 0.7502
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 — 100% of images get the same label under every template.
- 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
| Label | Images | Share of images | Mean score (labeled images) | Known | Precision | Recall | F1 |
|---|---|---|---|---|---|---|---|
| circle | 9 | 0.5294 | 0.9838 | 9 | 1 | 1 | 1 |
| square | 8 | 0.4706 | 0.9995 | 8 | 1 | 1 | 1 |
Each label is embedded as a photo of a {label}.; a {label} shape. with the label filled in and the sentences averaged. Scores are softmax probabilities across the labels (they sum to 1).
Top labels per image
| Row | File | Label 1 | Score 1 | Label 2 | Score 2 | Known label |
|---|---|---|---|---|---|---|
| 1 | red_circle_1.png | circle | 0.9926 | square | 0.0074 | circle |
| 2 | red_square_1.png | square | 0.9988 | circle | 0.0012 | square |
| 3 | green_circle_1.png | circle | 0.9970 | square | 0.0030 | circle |
| 4 | green_square_1.png | square | 0.9997 | circle | 0.0003 | square |
| 5 | blue_circle_1.png | circle | 0.9925 | square | 0.0075 | circle |
| 6 | blue_square_1.png | square | 0.9998 | circle | 0.0002 | square |
| 7 | yellow_circle_1.png | circle | 0.9931 | square | 0.0069 | circle |
| 8 | yellow_square_1.png | square | 0.9984 | circle | 0.0016 | square |
| 9 | red_circle_2.png | circle | 0.9723 | square | 0.0277 | circle |
| 10 | red_square_2.png | square | 0.9998 | circle | 0.0002 | square |
| 11 | green_circle_2.png | circle | 0.9816 | square | 0.0184 | circle |
| 12 | green_square_2.png | square | 0.9999 | circle | 7.638e-5 | square |
| 13 | blue_circle_2.png | circle | 0.9783 | square | 0.0217 | circle |
| 14 | blue_square_2.png | square | 0.9999 | circle | 6.617e-5 | square |
| 15 | yellow_circle_2.png | circle | 0.9543 | square | 0.0457 | circle |
| 16 | yellow_square_2.png | square | 0.9997 | circle | 0.0003 | square |
| 17 | red_circle_1_copy.png | circle | 0.9926 | square | 0.0074 | circle |
- 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 b3d0e15cbfe0900f
# 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 = "shape"
CAPTION = "caption"
df = pd.read_parquet("tests/parity/fixtures/clip_images.parquet", columns=["path", "shape", "caption"])
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/labels_from_known_levels/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("")
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}.; a {label} shape.")
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/labels_from_known_levels/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,
})
Agreement often varies by label: common, photographable concepts do well; rare, technical or abstract ones ("hairline fracture", "early blight") do poorly. Web-trained models also carry the web's skews about people, places and objects.
Check: SigLIP and zero-shot
CheckpointCheck yourself
What does SigLIP's loss do differently from CLIP's?
Show the answer
Answer: a
Pairs are independent yes-or-no questions, so the loss needs no normalization across the batch.
Check yourself
A photo shows a dog on a beach. Labels: "dog", "beach", "cat". Which encoder's scores can rate both "dog" and "beach" high at once?
Show the answer
Answer: b
CLIP's softmax makes labels compete; SigLIP's sigmoids let several labels fit, or none.
Check yourself
Why does the sigmoid loss make very large training batches cheaper?
Show the answer
Answer: a
A softmax needs every score in a row before normalizing; independent sigmoids don't.
Check yourself
Zero-shot accuracy with the bare labels "rust", "dent", "scratch" is poor. What is the cheapest thing to try first?
Show the answer
Answer: a
Captions the model learned from are sentences. Better sentences and template averaging often help a lot at no training cost.
Check yourself
Some of your images show none of your labels. How do you keep CLIP from forcing a label on them?
Show the answer
Answer: b
Softmax scores always pick something. A catch-all label or a similarity floor gives the model a way out.
Recap
Recap- SigLIP scores each pair with a sigmoid: no batch normalization, cheap large batches, independent label scores.
- Zero-shot labels come from label sentences; good wording and template ensembles matter.
- CLIP's softmax scores always pick one of your labels; add "other" or check raw similarity.
- Measure agreement on known labels, label by label, before trusting zero-shot output.
Concepts in this lesson