Skip to content

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.

Applied ~14 min7 steps

What runs in CodeSplash

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

Read first

01

SigLIP: one pair at a time

Read
Reference · MM003 · Partly runs in CodeSplashSigLIP family, including SigLIP 2Uses a pairwise sigmoid alignment loss rather than a global softmax over image-text matches. SigLIP 2 extends the family with additional captioning/self-supervised objectives, data curation and…

SigLIPSigLIPA CLIP-like image–text model trained with a sigmoid loss: it scores each image–text pair on its own instead of across a batch. 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.

02

Labels from your words

Read

Zero-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:

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

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

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

Plots

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

Assumptions

  • Scores are not probabilities — The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff.
  • Labels depend on wording — Labels and search results change with the words used; try a few wordings or templates.
  • Learned from web images — The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.

Labels

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

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

Top labels per image

RowFileLabel 1Score 1Label 2Score 2Label 3Score 3Label 4Score 4Known label
1red_circle_1.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
2red_square_1.pngred1.0000blue7.675e-7yellow4.752e-7green4.568e-7red
3green_circle_1.pnggreen0.9999red3.881e-5blue3.725e-5yellow7.679e-6green
4green_square_1.pnggreen1.0000red1.266e-5blue1.134e-5yellow2.463e-6green
5blue_circle_1.pngblue1.0000red4.510e-5yellow2.744e-6green2.041e-6blue
6blue_square_1.pngblue1.0000red1.483e-5green1.156e-6yellow9.401e-7blue
7yellow_circle_1.pngyellow1.0000red1.210e-5blue7.562e-6green3.706e-6yellow
8yellow_square_1.pngyellow1.0000green1.652e-6red1.530e-6blue5.983e-7yellow
9red_circle_2.pngred0.9999yellow5.776e-5blue3.343e-5green7.213e-6red
10red_square_2.pngred1.0000yellow7.082e-7blue6.591e-7green3.169e-7red
11green_circle_2.pnggreen0.9995red0.0003blue0.0001yellow8.919e-5green
12green_square_2.pnggreen0.9999red8.516e-5blue3.818e-5yellow2.244e-5green
13blue_circle_2.pngblue0.9992red0.0007yellow7.249e-5green3.616e-5blue
14blue_square_2.pngblue0.9999red0.0001yellow2.006e-5green5.698e-6blue
15yellow_circle_2.pngyellow0.9999red4.148e-5green1.243e-5blue7.390e-6yellow
16yellow_square_2.pngyellow1.0000red2.760e-6green1.148e-6blue8.616e-7yellow
17red_circle_1_copy.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
  • 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
  • Model: CLIP ViT-B/32 (DataComp-1B). Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.
The exact R script · R R version 4.5.1 (2025-06-13)
# Image–text search and zero-shot labels (CLIP, SigLIP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_text 1.0.0 · spec 85dbfef898a61423
# Dataset: clip_images (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_clip_* / cs_siglip_* (towers on R torch), cs_imagetext_* (twins of codesplash.imagetext.discover)

# %% Data (rows with an image path; known labels and captions may be missing)
IMAGE <- "path"
TRUTH <- "color"
CAPTION <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clip_images.parquet", col_select = c("path", "color")))
n_input <- nrow(df)
df <- df[!is.na(df[[IMAGE]]), , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"catmull_rom\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.48145466,0.4578275,0.40821073],\"std\":[0.26862954,0.26130258,0.27577711]},\"size\":[224,224]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-r", df,
                        "tests/parity/fixtures/clip_images.parquet")
media_ids <- cs_media_ids(media, df)

# %% Images the host could decode (unreadable files are left out)
status <- cs_media_status(media, media_ids)
ok <- which(is.na(status))
bad <- which(!is.na(status))
n_unreadable <- length(bad)
if (!length(ok)) cs_error("CS_E_MEDIA_DECODE", file = as.character(df[[IMAGE]][bad[1]]), reason = as.character(status[bad[1]]))
if (length(bad)) {
  warnings <- c(warnings, sprintf("%d image file(s) couldn't be read and are left out (first: %s).", length(bad), as.character(df[[IMAGE]][bad[1]])))
}
input_pos <- as.integer(rownames(df)) - 1L
df <- df[ok, , drop = FALSE]
ids <- media_ids[ok]
rows <- input_pos[ok]  # 0-based positions in the analysis input
n <- length(rows)
files <- basename(as.character(df[[IMAGE]]))
truth <- if (is.null(TRUTH)) NULL else as.character(df[[TRUTH]])
captions <- if (is.null(CAPTION)) NULL else as.character(df[[CAPTION]])
truth_levels <- if (is.null(truth)) character(0) else sort(unique(truth[!is.na(truth)]), method = "radix")

# %% Task settings (checked before the model loads)
MODE <- "zero_shot"
KIND <- "clip"
TOP_K <- as.integer(5)
LABELS <- character(0); TEMPLATES <- character(0); QUERIES <- character(0); QPOS <- integer(0)
if (MODE == "zero_shot") {
  LABELS <- cs_search_split_labels("red, green, blue, yellow")
  if (!length(LABELS) && length(truth_levels)) LABELS <- truth_levels
  if (length(LABELS) < 2) {
    cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "at least two labels separated by commas",
             value = if (length(LABELS)) paste(LABELS, collapse = ", ") else "(empty)")
  }
  if (anyDuplicated(LABELS)) cs_error("CS_E_INVALID_OPTION", option = "Labels", allowed = "distinct labels", value = paste(LABELS, collapse = ", "))
  TEMPLATES <- cs_search_split_list("a photo of a {label}.")
  if (!length(TEMPLATES) || !all(grepl("{label}", TEMPLATES, fixed = TRUE))) {
    cs_error("CS_E_INVALID_OPTION", option = "Prompt templates", allowed = "sentences that each contain {label}",
             value = if (length(TEMPLATES)) paste(TEMPLATES, collapse = "; ") else "(empty)")
  }
} else if (MODE == "text_search") {
  QUERIES <- cs_search_split_list("")
  if (!length(QUERIES) && (is.null(captions) || all(is.na(captions)))) {
    cs_error("CS_E_INVALID_OPTION", option = "Search texts", allowed = "at least one text, or a caption column", value = "(empty)")
  }
} else {
  if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Finding similar images", min = 2, n = n)
  QROWS <- cs_imagetext_parse_rows("")
  if (is.null(QROWS)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers separated by commas", value = "")
  for (q in QROWS) {
    hit <- which(rows + 1L == q)
    if (!length(hit)) cs_error("CS_E_INVALID_OPTION", option = "Query rows", allowed = "row numbers of readable images", value = as.character(q))
    QPOS <- c(QPOS, hit[1])
  }
  if (!length(QPOS)) QPOS <- seq_len(n)
}

# %% Image embeddings (CLIP ViT-B/32, double precision, one image at a time)
if (!cs_clip_available()) cs_error("CS_WEIGHTS_MISSING", model = "CLIP ViT-B/32 (DataComp-1B)")
model <- cs_clip_load()
NAME <- "CLIP ViT-B/32 (DataComp-1B)"
embed_images <- function(x) cs_clip_image_embed(model, x)
embed_texts <- function(t) cs_clip_text_embed(model, t)
LOGIT_BIAS <- 0
d <- model$dim
E <- matrix(0, n, d)  # unit rows, one image at a time; files read 32 at a time from the host's decoded tensors
for (i in seq(1L, n, by = 32L)) {
  idx <- i:min(n, i + 31L)
  E[idx, ] <- embed_images(cs_media_load(media, ids[idx]))  # (b, 3, 224, 224), the host's float32 values
}
values <- list(
  n_rows = n_input, n_images = n, n_unreadable = n_unreadable, encoder = NAME, mode = MODE, dim = d,
  logit_scale = model$logit_scale, logit_bias = if (KIND == "siglip") LOGIT_BIAS else NA,
  n_labels = NA, n_templates = NA, labels_text = NA, mean_top_score = NA, mean_margin = NA,
  template_agreement = NA, n_evaluated = NA, accuracy = NA, macro_f1 = NA, balanced_accuracy = NA,
  n_queries = NA, recall_at_1 = NA, recall_at_5 = NA, recall_at_10 = NA, median_rank = NA,
  clipscore_mean = NA, mean_nn_similarity = NA
)
for (j in seq_len(min(5L, d))) values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(E[, j], rows)

# %% Captions: CLIPScore = 2.5 * max(cos(image, caption), 0) (Hessel et al. 2021), on this model's embeddings
cap_pos <- if (is.null(captions)) integer(0) else which(!is.na(captions))
C <- if (length(cap_pos)) embed_texts(captions[cap_pos]) else NULL
if (length(cap_pos)) values$clipscore_mean <- mean(2.5 * pmax(rowSums(C * E[cap_pos, , drop = FALSE]), 0))

out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-r")
tables <- list(); charts <- list(); statistics <- list(); artifacts <- list()
gallery <- list(media = character(0), file = character(0), group = character(0), rank = integer(0), score = numeric(0))
add_gallery <- function(group, positions, scores) {
  gallery$media <<- c(gallery$media, ids[positions])
  gallery$file <<- c(gallery$file, files[positions])
  gallery$group <<- c(gallery$group, rep(group, length(positions)))
  gallery$rank <<- c(gallery$rank, seq_along(positions))
  gallery$score <<- c(gallery$score, as.numeric(scores))
}

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

# %% Ranked thumbnails, the embedding map and the saved embeddings
if (length(gallery$media)) {
  charts <- c(list(cs_chart("gallery", "image-ranking", if (MODE != "image_search") "Top images" else "Query images and their nearest images", list(
    media = cs_col("Image", gallery$media, kind = "categorical"),
    file = cs_col("File", gallery$file, kind = "categorical"),
    group = cs_col(if (MODE == "zero_shot") "Label" else if (MODE == "text_search") "Search text" else "Query", gallery$group, kind = "categorical"),
    rank = cs_col("Rank", as.numeric(gallery$rank)),
    score = cs_col(if (MODE != "image_search") "Score" else "Cosine similarity", gallery$score)
  ), controls = list(per_group = min(TOP_K + (if (MODE == "image_search") 1L else 0L), 12L)))), charts)
}
if (n >= 3) {
  Z <- cs_imagetext_pca2(E)
  color <- if (MODE == "zero_shot") pred else if (!is.null(truth)) truth else rep("Images", n)
  charts[[length(charts) + 1]] <- cs_chart("map", "cluster-scatter", "Image map (first two principal components of the embeddings)", list(
    x = cs_col("PC 1", Z[, 1], "numeric"), y = cs_col("PC 2", Z[, 2], "numeric"),
    cluster = cs_col(if (MODE == "zero_shot") "Zero-shot label" else if (!is.null(TRUTH)) TRUTH else "Group", ifelse(is.na(color), "(missing)", color), "categorical")
  ))
}
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(d)) emb[[sprintf("dim_%d", j)]] <- E[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
artifacts <- c(list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet")), artifacts)
statistics <- c(list(list(key = "n_images", label = "Images", value = n, format = "integer")), statistics)
if (!is.na(values$clipscore_mean)) statistics[[length(statistics) + 1]] <- list(key = "clipscore_mean", label = "Mean CLIPScore (captions)", value = values$clipscore_mean)
ta <- values$template_agreement
assumptions <- list(
  list(key = "uncalibrated", label = "Scores are not probabilities", status = "info",
       detail = "The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff."),
  list(key = "prompt_wording", label = "Labels depend on wording", status = if (!is.na(ta) && ta < 0.9) "warn" else "info",
       detail = if (!is.na(ta)) sprintf("%.0f%% of images get the same label under every template.", 100 * ta)
                else "Labels and search results change with the words used; try a few wordings or templates."),
  list(key = "web_training", label = "Learned from web images", status = "info",
       detail = "The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.")
)
cs_publish(list(
  title = "Image–text search and zero-shot labels (CLIP, SigLIP)",
  engine = cs_engine_info("torch", "stringi", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  notes = list(sprintf("Model: %s. Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.", NAME)),
  artifacts = artifacts
))
Python

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

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

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Scores are not probabilities — The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff.
  • Labels depend on wording — Labels and search results change with the words used; try a few wordings or templates.
  • Learned from web images — The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views.

Labels

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

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

Top labels per image

RowFileLabel 1Score 1Label 2Score 2Label 3Score 3Label 4Score 4Known label
1red_circle_1.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
2red_square_1.pngred1.0000blue7.675e-7yellow4.752e-7green4.568e-7red
3green_circle_1.pnggreen0.9999red3.881e-5blue3.725e-5yellow7.679e-6green
4green_square_1.pnggreen1.0000red1.266e-5blue1.134e-5yellow2.463e-6green
5blue_circle_1.pngblue1.0000red4.510e-5yellow2.744e-6green2.041e-6blue
6blue_square_1.pngblue1.0000red1.483e-5green1.156e-6yellow9.401e-7blue
7yellow_circle_1.pngyellow1.0000red1.210e-5blue7.562e-6green3.706e-6yellow
8yellow_square_1.pngyellow1.0000green1.652e-6red1.530e-6blue5.983e-7yellow
9red_circle_2.pngred0.9999yellow5.776e-5blue3.343e-5green7.213e-6red
10red_square_2.pngred1.0000yellow7.082e-7blue6.591e-7green3.169e-7red
11green_circle_2.pnggreen0.9995red0.0003blue0.0001yellow8.919e-5green
12green_square_2.pnggreen0.9999red8.516e-5blue3.818e-5yellow2.244e-5green
13blue_circle_2.pngblue0.9992red0.0007yellow7.249e-5green3.616e-5blue
14blue_square_2.pngblue0.9999red0.0001yellow2.006e-5green5.698e-6blue
15yellow_circle_2.pngyellow0.9999red4.148e-5green1.243e-5blue7.390e-6yellow
16yellow_square_2.pngyellow1.0000red2.760e-6green1.148e-6blue8.616e-7yellow
17red_circle_1_copy.pngred1.0000blue2.575e-5yellow4.918e-6green1.101e-6red
  • 1 image file(s) couldn't be read and are left out (first: clip_images/not_there.png).
  • Model: CLIP ViT-B/32 (DataComp-1B). Each image and text is embedded on its own in double precision, so results never depend on what else is in the run.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image–text search and zero-shot labels (CLIP, SigLIP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.image_text 1.0.0 · spec 85dbfef898a61423
# Dataset: clip_images (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.imagetext import discover as it  # prompts, scores, rankings (twin: codesplashr cs_imagetext_*)
from codesplash.ml import embed as csembed  # order-sensitive checksums (twin: cs_ml_checksum)
from codesplash.text import search as zs  # label lists and agreement figures (twin: cs_search_* / cs_zero_shot_classification)
from codesplash.imagetext import clip as tower  # CLIP ViT-B/32 written out on torch (twin: cs_clip_*)

# %% Data (rows with an image path; known labels and captions may be missing)
IMAGE = "path"
TRUTH = "color"
CAPTION = None
df = pd.read_parquet("tests/parity/fixtures/clip_images.parquet", columns=["path", "color"])
n_input = len(df)
df = df[df[IMAGE].notna()]
warnings = []
if n_input - len(df):
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"catmull_rom\",\"fit\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":{\"mean\":[0.48145466,0.4578275,0.40821073],\"std\":[0.26862954,0.26130258,0.27577711]},\"size\":[224,224]}}"), "target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-python", df, "tests/parity/fixtures/clip_images.parquet")
media_ids = cs_media.ids_of(media, df)

# %% Images the host could decode (unreadable files are left out)
status = cs_media.status(media, media_ids)
ok = [k for k, s in enumerate(status) if s is None]
bad = [k for k, s in enumerate(status) if s is not None]
n_unreadable = len(bad)
if not ok:
    cs.cs_error("CS_E_MEDIA_DECODE", file=str(df[IMAGE].iloc[bad[0]]), reason=str(status[bad[0]]))
if bad:
    warnings.append(f"{len(bad)} image file(s) couldn't be read and are left out (first: {df[IMAGE].iloc[bad[0]]}).")
df = df.iloc[ok]
ids = [media_ids[k] for k in ok]
rows = df.index.to_numpy().astype(np.int64)  # 0-based positions in the analysis input
n = len(rows)
files = [os.path.basename(str(p)) for p in df[IMAGE].tolist()]
truth = None if TRUTH is None else [None if pd.isna(v) else str(v) for v in df[TRUTH].tolist()]
captions = None if CAPTION is None else [None if pd.isna(v) else str(v) for v in df[CAPTION].tolist()]
truth_levels = [] if truth is None else sorted(set(t for t in truth if t is not None))

# %% Task settings (checked before the model loads)
MODE = "zero_shot"
KIND = "clip"
TOP_K = int(5)
LABELS, TEMPLATES, QUERIES, QPOS = [], [], [], []
if MODE == "zero_shot":
    LABELS = zs.split_labels("red, green, blue, yellow")
    if not LABELS and truth_levels:
        LABELS = list(truth_levels)
    if len(LABELS) < 2:
        cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="at least two labels separated by commas", value=", ".join(LABELS) or "(empty)")
    if len(set(LABELS)) < len(LABELS):
        cs.cs_error("CS_E_INVALID_OPTION", option="Labels", allowed="distinct labels", value=", ".join(LABELS))
    TEMPLATES = zs.split_list("a photo of a {label}.")
    if not TEMPLATES or any(zs.LABEL_SLOT not in t for t in TEMPLATES):
        cs.cs_error("CS_E_INVALID_OPTION", option="Prompt templates", allowed="sentences that each contain {label}", value="; ".join(TEMPLATES) or "(empty)")
elif MODE == "text_search":
    QUERIES = zs.split_list("")
    if not QUERIES and (captions is None or not any(c is not None for c in captions)):
        cs.cs_error("CS_E_INVALID_OPTION", option="Search texts", allowed="at least one text, or a caption column", value="(empty)")
else:
    if n < 2:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what="Finding similar images", min=2, n=n)
    QROWS = it.parse_rows("")
    if QROWS is None:
        cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers separated by commas", value="")
    for q in QROWS:
        hit = np.nonzero(rows + 1 == q)[0]
        if not len(hit):
            cs.cs_error("CS_E_INVALID_OPTION", option="Query rows", allowed="row numbers of readable images", value=str(q))
        QPOS.append(int(hit[0]))
    if not QPOS:
        QPOS = list(range(n))

# %% Image embeddings (CLIP ViT-B/32, double precision, one image at a time)
if not tower.available():
    cs.cs_error("CS_WEIGHTS_MISSING", model=tower.NAME)
model = tower.Model()
LOGIT_BIAS = float(getattr(model, "logit_bias", 0.0))
d = model.dim
E = np.zeros((n, d))  # unit rows, one image at a time; files read 32 at a time from the host's decoded tensors
for i in range(0, n, 32):
    E[i:i + 32] = model.image_embed(cs_media.load(media, ids[i:i + 32]))  # float32 (b, 3, 224, 224)
values = {
    "n_rows": n_input, "n_images": n, "n_unreadable": n_unreadable, "encoder": tower.NAME, "mode": MODE, "dim": d,
    "logit_scale": model.logit_scale, "logit_bias": LOGIT_BIAS if KIND == "siglip" else None,
    "n_labels": None, "n_templates": None, "labels_text": None, "mean_top_score": None, "mean_margin": None,
    "template_agreement": None, "n_evaluated": None, "accuracy": None, "macro_f1": None, "balanced_accuracy": None,
    "n_queries": None, "recall_at_1": None, "recall_at_5": None, "recall_at_10": None, "median_rank": None,
    "clipscore_mean": None, "mean_nn_similarity": None,
}
for j in range(min(5, d)):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(E[:, j], rows)

# %% Captions: CLIPScore = 2.5 · max(cos(image, caption), 0) (Hessel et al. 2021), on this model's embeddings
cap_pos = [] if captions is None else [k for k, c in enumerate(captions) if c is not None]
C = model.text_embed([captions[k] for k in cap_pos]) if cap_pos else None
if cap_pos:
    values["clipscore_mean"] = float(np.mean(2.5 * np.maximum(np.sum(C * E[cap_pos], axis=1), 0.0)))

out = csml.out_dir("target/academy-parity/run-8142/discover.image_text/colors_zero_shot/out-python")
tables, charts, statistics, artifacts = [], [], [], []
gallery = {"media": [], "file": [], "group": [], "rank": [], "score": []}


def add_gallery(group, positions, scores):
    for r, (k, s) in enumerate(zip(positions, scores), start=1):
        gallery["media"].append(ids[k])
        gallery["file"].append(files[k])
        gallery["group"].append(group)
        gallery["rank"].append(r)
        gallery["score"].append(float(s))


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

# %% Ranked thumbnails, the embedding map and the saved embeddings
if gallery["media"]:
    charts.insert(0, cs.chart("gallery", "image-ranking", "Top images" if MODE != "image_search" else "Query images and their nearest images", {
        "media": cs.col("Image", gallery["media"], kind="categorical"),
        "file": cs.col("File", gallery["file"], kind="categorical"),
        "group": cs.col("Label" if MODE == "zero_shot" else ("Search text" if MODE == "text_search" else "Query"), gallery["group"], kind="categorical"),
        "rank": cs.col("Rank", gallery["rank"]),
        "score": cs.col("Score" if MODE != "image_search" else "Cosine similarity", gallery["score"]),
    }, controls={"per_group": min(TOP_K + (1 if MODE == "image_search" else 0), 12)}))
if n >= 3:
    Z = it.pca2(E)
    color = pred if MODE == "zero_shot" else (truth if truth is not None else ["Images"] * n)
    charts.append(cs.chart("map", "cluster-scatter", "Image map (first two principal components of the embeddings)", {
        "x": cs.col("PC 1", Z[:, 0], "numeric"), "y": cs.col("PC 2", Z[:, 1], "numeric"),
        "cluster": cs.col("Zero-shot label" if MODE == "zero_shot" else (TRUTH or "Group"), ["(missing)" if c is None else c for c in color], "categorical"),
    }))
emb = pd.DataFrame({"row": rows, **{f"dim_{j + 1}": E[:, j] for j in range(d)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
artifacts.insert(0, {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"})
statistics.insert(0, {"key": "n_images", "label": "Images", "value": n, "format": "integer"})
if values["clipscore_mean"] is not None:
    statistics.append({"key": "clipscore_mean", "label": "Mean CLIPScore (captions)", "value": values["clipscore_mean"]})
assumptions = [
    {"key": "uncalibrated", "label": "Scores are not probabilities", "status": "info",
     "detail": "The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff."},
    {"key": "prompt_wording", "label": "Labels depend on wording", "status": ("warn" if values["template_agreement"] is not None and values["template_agreement"] < 0.9 else "info"),
     "detail": (f"{values['template_agreement']:.0%} of images get the same label under every template." if values["template_agreement"] is not None
                else "Labels and search results change with the words used; try a few wordings or templates.")},
    {"key": "web_training", "label": "Learned from web images", "status": "info",
     "detail": "The model learned from web images and alt text; it can repeat their stereotypes and miss specialized images such as scans, documents or satellite views."},
]
cs.publish({
    "title": "Image–text search and zero-shot labels (CLIP, SigLIP)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "notes": [f"Model: {tower.NAME}. Each image and text is embedded on its own in double precision, so results never depend on what else is in the run."],
    "artifacts": artifacts,
})

The 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.

03

Two templates, two labels

Read

Here SigLIP labels shapes with two templates per label and keeps the top 2 labels per image:

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

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

Top imagesWhich images fit a label or a search text best, and which images look most alike?
View data
FileLabelImageRankScore
blue_circle_2.pngcircle727f2dc4b0383e83cb77fb364b8a04e06695160ddfaf71a979346cb38448a80810.4804
red_circle_2.pngcircle5fa652ab46822e575326d94ba482a845383141f4a34132c22d95b069024f632120.2761
blue_square_2.pngsquare77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d910.8803
green_square_2.pngsquaref0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a2120.5243
blue_square_2.pngtriangle77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d910.0003
green_square_2.pngtrianglef0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a2120.0002
Images per labelWhich words or phrases appear most in a text column, overall or by group?
View data
ImagesLabel
9circle
8square
0triangle
Score of the chosen labelHow is one numeric variable distributed?
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
Zero-shot labels against shapeHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?
View data
shapeZero-shot label
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
Image map (first two principal components of the embeddings)Which rows group together, and how well separated are the groups?
View data
Zero-shot labelPC 1PC 2
circle0.19380.2588
square−0.30560.2213
circle0.2188−0.0500
square−0.2924−0.0631
circle0.2235−0.0702
square−0.2789−0.0740
circle0.19480.0895
square−0.29950.1123
circle0.24140.0708
square−0.24590.1037
circle0.2612−0.1872
square−0.2162−0.1907
circle0.2560−0.1994
square−0.2027−0.2231
circle0.2685−0.0402
square−0.2106−0.0174
circle0.19380.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

LabelImagesShare of imagesMean score (labeled images)KnownPrecisionRecallF1
circle90.52940.21239111
square80.47060.35848111
triangle00—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

RowFileLabel 1Score 1Label 2Score 2Known label
1red_circle_1.pngcircle0.1498square0.0010circle
2red_square_1.pngsquare0.0775triangle9.148e-6square
3green_circle_1.pngcircle0.0857square0.0002circle
4green_square_1.pngsquare0.2186triangle2.133e-5square
5blue_circle_1.pngcircle0.2737square0.0009circle
6blue_square_1.pngsquare0.3542circle2.780e-5square
7yellow_circle_1.pngcircle0.1506square0.0007circle
8yellow_square_1.pngsquare0.0229triangle7.739e-6square
9red_circle_2.pngcircle0.2761square0.0033circle
10red_square_2.pngsquare0.4894triangle7.280e-5square
11green_circle_2.pngcircle0.2624square0.0017circle
12green_square_2.pngsquare0.5243triangle0.0002square
13blue_circle_2.pngcircle0.4804square0.0034circle
14blue_square_2.pngsquare0.8803circle0.0004square
15yellow_circle_2.pngcircle0.0823square0.0005circle
16yellow_square_2.pngsquare0.2998circle0.0001square
17red_circle_1_copy.pngcircle0.1498square0.0010circle
  • 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
))
Python

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

LabelImagesShare of imagesMean score (labeled images)KnownPrecisionRecallF1
circle90.52940.21239111
square80.47060.35848111
triangle00—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

RowFileLabel 1Score 1Label 2Score 2Known label
1red_circle_1.pngcircle0.1498square0.0010circle
2red_square_1.pngsquare0.0775triangle9.148e-6square
3green_circle_1.pngcircle0.0857square0.0002circle
4green_square_1.pngsquare0.2186triangle2.133e-5square
5blue_circle_1.pngcircle0.2737square0.0009circle
6blue_square_1.pngsquare0.3542circle2.780e-5square
7yellow_circle_1.pngcircle0.1506square0.0007circle
8yellow_square_1.pngsquare0.0229triangle7.739e-6square
9red_circle_2.pngcircle0.2761square0.0033circle
10red_square_2.pngsquare0.4894triangle7.280e-5square
11green_circle_2.pngcircle0.2624square0.0017circle
12green_square_2.pngsquare0.5243triangle0.0002square
13blue_circle_2.pngcircle0.4804square0.0034circle
14blue_square_2.pngsquare0.8803circle0.0004square
15yellow_circle_2.pngcircle0.0823square0.0005circle
16yellow_square_2.pngsquare0.2998circle0.0001square
17red_circle_1_copy.pngcircle0.1498square0.0010circle
  • 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.

04

The closed-label trap

Predict

Predict first

You ask CLIP to label a photo of a bicycle with only two labels: "cat" and "dog". What do the scores look like?

Low scores for both labelsOne label gets most of the score anywayAn error
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.

05

Check before you trust

Read

Zero-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:

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

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

Top imagesWhich images fit a label or a search text best, and which images look most alike?
View data
FileLabelImageRankScore
green_circle_1.pngcircle33a634b9fb3326da6edf75bc17755bbf236a4cf0e7b2349a6dbbd4790ad909e110.9970
yellow_circle_1.pngcircled7650e4851900cbbd716ef730decc1f99ed2da6e97b937bf8ce0a7bf5a6a64e420.9931
red_circle_1.pngcircle9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb30.9926
red_circle_1_copy.pngcircle9a3e76d2849e45190bae64fd1b648905c4eab576a5511c82985daa44ff7a25eb40.9926
blue_circle_1.pngcircleac9b3dde099f3243d0b992fc9bac26d3384e28638afc7a82efa35c622ce9c12f50.9925
blue_square_2.pngsquare77c412ebdfceb00bc8213a6cd85286eb2bc53778a6822bc3ef09293ffec249d910.9999
green_square_2.pngsquaref0eb0253e1fbd26b61ce7c9415da8fc11b7af80d1ba096256ce92f1afb3a2a2120.9999
red_square_2.pngsquare434e2ec8acd8699a94f5db3be0f41ab8101c8157f523a05e1db05a7ea975a55f30.9998
blue_square_1.pngsquarebcf2583948f23afadb9eedbe7ed773103107e11d79522ae2bd5a1b8062fa738040.9998
yellow_square_2.pngsquarefa76bf14a0ba2ef56e8166402e88d235460ce6ea91d115ad87bbc8ec9a500ed050.9997
Images per labelWhich words or phrases appear most in a text column, overall or by group?
View data
ImagesLabel
9circle
8square
Score of the chosen labelHow is one numeric variable distributed?
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
Zero-shot labels against shapeHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?
View data
shapeZero-shot label
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
squaresquare
circlecircle
Image map (first two principal components of the embeddings)Which rows group together, and how well separated are the groups?
View data
Zero-shot labelPC 1PC 2
circle0.33470.2984
square−0.28390.2952
circle0.17210.1685
square−0.30150.1529
circle0.24750.0618
square−0.28080.0773
circle0.17690.1547
square−0.33990.1976
circle0.3175−0.1227
square−0.2224−0.0265
circle0.2007−0.2935
square−0.2048−0.2399
circle0.2314−0.3410
square−0.2016−0.2745
circle0.1155−0.2591
square−0.2960−0.1475
circle0.33470.2984

Assumptions

  • Scores are not probabilities — The scores rank images and labels well but aren't calibrated; check them against known labels before acting on a cutoff.
  • Labels depend on wording — 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

LabelImagesShare of imagesMean score (labeled images)KnownPrecisionRecallF1
circle90.52940.98389111
square80.47060.99958111

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

RowFileLabel 1Score 1Label 2Score 2Known label
1red_circle_1.pngcircle0.9926square0.0074circle
2red_square_1.pngsquare0.9988circle0.0012square
3green_circle_1.pngcircle0.9970square0.0030circle
4green_square_1.pngsquare0.9997circle0.0003square
5blue_circle_1.pngcircle0.9925square0.0075circle
6blue_square_1.pngsquare0.9998circle0.0002square
7yellow_circle_1.pngcircle0.9931square0.0069circle
8yellow_square_1.pngsquare0.9984circle0.0016square
9red_circle_2.pngcircle0.9723square0.0277circle
10red_square_2.pngsquare0.9998circle0.0002square
11green_circle_2.pngcircle0.9816square0.0184circle
12green_square_2.pngsquare0.9999circle7.638e-5square
13blue_circle_2.pngcircle0.9783square0.0217circle
14blue_square_2.pngsquare0.9999circle6.617e-5square
15yellow_circle_2.pngcircle0.9543square0.0457circle
16yellow_square_2.pngsquare0.9997circle0.0003square
17red_circle_1_copy.pngcircle0.9926square0.0074circle
  • 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
))
Python

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

LabelImagesShare of imagesMean score (labeled images)KnownPrecisionRecallF1
circle90.52940.98389111
square80.47060.99958111

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

RowFileLabel 1Score 1Label 2Score 2Known label
1red_circle_1.pngcircle0.9926square0.0074circle
2red_square_1.pngsquare0.9988circle0.0012square
3green_circle_1.pngcircle0.9970square0.0030circle
4green_square_1.pngsquare0.9997circle0.0003square
5blue_circle_1.pngcircle0.9925square0.0075circle
6blue_square_1.pngsquare0.9998circle0.0002square
7yellow_circle_1.pngcircle0.9931square0.0069circle
8yellow_square_1.pngsquare0.9984circle0.0016square
9red_circle_2.pngcircle0.9723square0.0277circle
10red_square_2.pngsquare0.9998circle0.0002square
11green_circle_2.pngcircle0.9816square0.0184circle
12green_square_2.pngsquare0.9999circle7.638e-5square
13blue_circle_2.pngcircle0.9783square0.0217circle
14blue_square_2.pngsquare0.9999circle6.617e-5square
15yellow_circle_2.pngcircle0.9543square0.0457circle
16yellow_square_2.pngsquare0.9997circle0.0003square
17red_circle_1_copy.pngcircle0.9926square0.0074circle
  • 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.

06

Check: SigLIP and zero-shot

Checkpoint

Check 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.

07

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