Skip to content

Transformer and promptable segmentation: SegFormer, Mask2Former, SAM

Three newer ways to make masks: SegFormer's multi-scale Transformer with a tiny decoder, Mask2Former's set of masks with masked attention, and SAM's masks for whatever a click or box points at.

Advanced ~15 min7 steps

What runs in CodeSplash

You will be able to

  • Describe how SegFormer fuses features from several scales
  • Explain mask classification and Mask2Former's masked attention
  • Say why SAM returns several masks for one click
  • Check a promptable mask against the truth instead of its own quality score

Read first

01

SegFormer: a light decoder

Read
Reference · VIS013 · Explained hereSegFormerSegFormer combines a hierarchical vision transformer with a lightweight segmentation decoder. It is useful when multiscale image context and reasonably efficient dense prediction are needed without a heavy decoder;

SegFormer's encoder is a Transformer that works like a CNN pyramid: it merges overlapping patches stage by stage, giving feature maps at four resolutions, and needs no position embeddings, so it handles new image sizes well. The decoder is small: project every scale to the same width, upsample, concatenate and classify each pixel.

In the program, fine features at 4 sites and one coarse site are projected to 2 channels each; the coarse value is copied to all 4 sites and stacked beside the fine ones. The class probability then rises from 0.54 at the first site to 0.88 at the last. Its official weights aren't licensed for commercial use.

02

Mask2Former: a set of masks

Read
Reference · VIS014 · Explained hereMask2FormerMask2Former unifies semantic, instance and panoptic segmentation through mask classification. Its distinctive masked attention restricts query processing to predicted regions, connecting object-level queries with dense…

Mask classificationMask classificationPredicting a set of masks, each with one class, instead of a class per pixel; one design covers semantic and instance masks. borrows DETR's idea: a fixed set of queries, each predicting one mask and one class, matched one-to-one to the labeled regions. One design then covers semantic, instance and panoptic segmentation.

Mask2Former adds masked attention: each query attends only to pixels inside its current mask. In the program, the first query may look at pixels 1 and 3 only, so its weights are 0.574, 0, 0.426 and 0. The second query's mask is empty, so it falls back to attending everywhere.

03

One click, which object?

Predict

Predict first

You click once on a person's shirt and ask a promptable segmenter for a mask. What should a good model return?

One mask: the shirtSeveral masks: the shirt, the person, perhaps the groupNo mask without a class name
Reveal

Several masks. A click on a shirt could mean the shirt, the person or the group of people. SAM returns three candidates, each with its own predicted quality, and lets you add clicks or a box to settle it.

04

SAM: masks on request

Read
Reference · VIS015 · Explained hereSegment Anything Model (SAM, original image model)Original SAM is a promptable image segmentation model: points, boxes or masks condition one or several candidate masks.

Promptable segmentationPromptable segmentation (SAM)Returning a mask for whatever a click, box or rough mask points at, without a fixed class list. needs no class list. SAM runs a large ViT image encoder once per image, then a small decoder turns each prompt (points, a box or a rough mask) into masks in a fraction of a second, which makes it a fast labeling tool.

Its predicted quality score can be wrong. In the program, three candidate masks get predicted qualities and actual IoUs against the truth; the highest predicted quality picks mask 1, whose IoU is 0.500, while mask 0 matched perfectly. Check masks against labels before trusting the score.

05

Scoring masks you made

Read

Masks from any of these models, or from your own labeling, can be scored per class:

Segmentation qualityRecorded · Python and R agreeRecorded 2026-11-25 · 20 values compared
R

Across 10 images and 4 classes, mean IoU = 0.403, mean Dice = 0.513 and pixel accuracy = 0.550.

Mean IoU
0.4027
Mean Dice
0.5126
Pixel accuracy
0.5497

Plots

IoU and Dice by classHow do categories compare on one value — and across up to three groups?
View data
labelMeasureOverlap
bicycleIoU0.4855
bicycleDice0.6537
carIoU0.3607
carDice0.5301
dogIoU0
dogDice0
personIoU0.7645
personDice0.8666

Assumptions

  • The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
  • Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.

Per class (pixels summed over images)

labelReference pixelsPredicted pixelsOverlap (pixels)IoUDice
bicycle9,84414,1967,8570.48550.6537
car64,32226,06723,9590.36070.5301
dog03,012000
person38,22130,92429,9590.76450.8666

Mean IoU per image

media_idMean IoU
img010.4776
img020.4692
img030.2155
img040.3200
img050.6104
img060.5888
img070.3134
img080.8444
img090
img100
  • Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded).
The exact R script · R R version 4.5.1 (2025-06-13)
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec ebc2b9896c4c2c9c
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_eval_seg_* (segmentation scores), cs_eval_det_runs, cs_eval_stacked, cs_rle_* (COCO RLE)

# %% Data
GROUP <- "media_id"
FRAME <- NULL
LABEL <- "label"
SOURCE <- "source"
MASK <- "mask_rle"
WIDTH <- "image_width"
HEIGHT <- "image_height"
CROWD <- NULL
START <- NULL
END <- NULL
SCORE <- NULL
KIND <- "masks"  # masks | intervals
BACKGROUND <- FALSE
THRESHOLDS <- as.numeric(unlist(c(0.1, 0.25, 0.5)))
if (!length(THRESHOLDS)) THRESHOLDS <- 0.5
THRESHOLDS <- sort(unique(THRESHOLDS))
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction")  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (KIND == "masks" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
  cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "time intervals unless the mask, width and height columns are set", value = "masks")
}
if (KIND == "intervals" && (is.null(START) || is.null(END))) {
  cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "masks unless the start and end columns are set", value = "time intervals")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
  # The reference table's rows go above this table's rows under an added source column (twin: with_reference).
  w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.segments/masks-no-background/out-r", "reference_table"),
                              list(group = GROUP, frame = FRAME, label = LABEL, mask = MASK, width = WIDTH, height = HEIGHT, crowd = CROWD,
                                   start = START, end = END, score = SCORE), REF_ROLES,
                              c(list(frame = "Frame"), if (KIND == "masks") list(mask = "Mask", width = "Image width", height = "Image height") else list(start = "Start", end = "End")),
                              SOURCE, REF_LEVEL, c("group", "label", if (KIND == "masks") c("mask", "width", "height") else c("start", "end")))
  df <- w$df
  pre_warnings <- w$warnings
  wc <- w$columns
  GROUP <- wc$group; FRAME <- wc$frame; LABEL <- wc$label; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
  CROWD <- wc$crowd; START <- wc$start; END <- wc$end
  SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
  cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(GROUP, LABEL, SOURCE, if (KIND == "masks") c(MASK, WIDTH, HEIGHT) else c(START, END))
numeric_cols <- if (KIND == "masks") c(WIDTH, HEIGHT) else c(START, END, SCORE)
st <- cs_eval_stacked(df, needed, numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
labels_all <- as.character(df[[LABEL]])
crowd <- if (!is.null(CROWD) && KIND == "masks") cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE
classes <- sort(unique(labels_all[!crowd]), method = "radix")

if (KIND == "masks") {
  # %% Masks -> runs, per image
  ik <- cs_eval_image_keys(df[[GROUP]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
  img_idx <- ik$index
  ws <- as.numeric(df[[WIDTH]])
  hs <- as.numeric(df[[HEIGHT]])
  runs <- lapply(seq_len(nrow(df)), function(i) {
    tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
             error = function(e) NULL)
  })
  n_bad <- sum(vapply(runs, is.null, logical(1)))
  if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
  ims <- lapply(seq_along(ik$media), function(i) list(n = NULL, size = NULL, ref = list(), pred = list(), void = list()))
  for (i in seq_along(runs)) {
    q <- img_idx[i] + 1L
    r <- runs[[i]]
    if (is.null(ims[[q]]$n)) {
      ims[[q]]$n <- as.numeric(r$size[1]) * as.numeric(r$size[2])
      ims[[q]]$size <- r$size
    } else if (!identical(ims[[q]]$size, r$size)) {
      cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
    }
    rr <- list(s = r$s, e = r$e)
    if (crowd[i]) {
      ims[[q]]$void[[length(ims[[q]]$void) + 1L]] <- rr
    } else if (is_ref[i]) {
      lab <- labels_all[i]
      ims[[q]]$ref[[lab]] <- c(if (is.null(ims[[q]]$ref[[lab]])) list() else ims[[q]]$ref[[lab]], list(rr))
    } else {
      lab <- labels_all[i]
      ims[[q]]$pred[[lab]] <- c(if (is.null(ims[[q]]$pred[[lab]])) list() else ims[[q]]$pred[[lab]], list(rr))
    }
  }
  res <- cs_eval_seg_masks(ims, classes, BACKGROUND)
  names_ <- res$classes
  n_ref <- sum(is_ref & !crowd)
  n_pred <- sum(!is_ref)
  unit <- "pixels"
  group_rows <- lapply(seq_along(ik$media), function(i) list(group = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i],
                                                             miou = if (is.null(res$per_image[[i]])) NA_real_ else res$per_image[[i]]))
  n_groups <- length(ik$media)
  has_score <- FALSE
} else {
  # %% Intervals per recording
  s_all <- as.numeric(df[[START]])
  e_all <- as.numeric(df[[END]])
  bad <- e_all < s_all
  if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = END, requirement = sprintf("at least %s", START), count = sum(bad))
  sc_all <- if (!is.null(SCORE)) as.numeric(df[[SCORE]]) else rep(NA_real_, nrow(df))
  has_score <- !is.null(SCORE)
  if (has_score) {
    miss <- !is_ref & is.na(sc_all)
    if (any(miss)) {
      warnings <- c(warnings, sprintf("%d predicted segments have no %s and were left out.", sum(miss), SCORE))
      keep <- !miss
      df <- df[keep, , drop = FALSE]; is_ref <- is_ref[keep]; labels_all <- labels_all[keep]
      s_all <- s_all[keep]; e_all <- e_all[keep]; sc_all <- sc_all[keep]
      classes <- sort(unique(labels_all), method = "radix")
    }
  }
  grp <- as.character(df[[GROUP]])
  groups <- sort(unique(grp), method = "radix")
  recs <- lapply(groups, function(g) {
    rows <- which(grp == g)
    rr <- rows[is_ref[rows]]
    pr <- rows[!is_ref[rows]]
    list(ref = data.frame(start = s_all[rr], end = e_all[rr], label = labels_all[rr], stringsAsFactors = FALSE),
         pred = data.frame(start = s_all[pr], end = e_all[pr], label = labels_all[pr], score = if (has_score) sc_all[pr] else rep(0, length(pr)),
                           row = pr - 1L, stringsAsFactors = FALSE))
  })
  res <- cs_eval_seg_intervals(recs, classes, THRESHOLDS, has_score)
  names_ <- res$classes
  n_ref <- res$n_ref
  n_pred <- res$n_pred
  unit <- "seconds"
  n_groups <- length(groups)
}

# %% Assumptions
assumptions <- list(
  list(key = "complete", label = "The reference is complete", status = "info",
       detail = "Regions or segments missing from the reference turn correct predictions into errors."),
  list(key = "overlap", label = "Reference classes don't overlap", status = "info",
       detail = "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.")
)

# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tkey <- function(t) sprintf("%g", t)
values <- list(kind = KIND, n_groups = n_groups, n_classes = length(names_), n_reference = n_ref, n_predictions = n_pred,
               accuracy = res$accuracy, miou = res$miou, mean_dice = res$mean_dice, fw_iou = res$fw_iou,
               scored = if (!is.null(res$scored)) res$scored else sum(res$gsum), ignored = if (!is.null(res$ignored)) res$ignored else NA_real_,
               map = NA_real_)
for (j in seq_along(names_)) {
  values[[sprintf("iou[%s]", names_[j])]] <- res$iou[j]
  values[[sprintf("dice[%s]", names_[j])]] <- res$dice[j]
}
cls_cols <- list(list(key = "class", label = LABEL, type = "string"), list(key = "ref", label = sprintf("Reference %s", unit), type = "number"),
                 list(key = "pred", label = sprintf("Predicted %s", unit), type = "number"), list(key = "inter", label = sprintf("Overlap (%s)", unit), type = "number"),
                 list(key = "iou", label = "IoU", type = "number"), list(key = "dice", label = "Dice", type = "number"))
cls_rows <- lapply(seq_along(names_), function(j) list(class = names_[j], ref = res$gsum[j], pred = res$psum[j], inter = res$inter[j],
                                                       iou = res$iou[j], dice = res$dice[j]))
tables <- list()
charts <- list()
if (KIND == "intervals") {
  m_rows <- res$matching
  for (r in m_rows) {
    values[[sprintf("f1[%s]", tkey(r$threshold))]] <- r$f1
    values[[sprintf("precision[%s]", tkey(r$threshold))]] <- r$precision
    values[[sprintf("recall[%s]", tkey(r$threshold))]] <- r$recall
    if (has_score) values[[sprintf("ap[%s]", tkey(r$threshold))]] <- r$map
  }
  if (has_score) {
    maps <- vapply(m_rows, function(r) r$map, numeric(1))
    maps <- maps[!is.na(maps)]
    values$map <- if (length(maps)) mean(maps) else NA_real_
    for (r in m_rows) {
      key <- sprintf("ap_%s", tkey(r$threshold))
      cls_cols[[length(cls_cols) + 1L]] <- list(key = key, label = sprintf("AP@%s", tkey(r$threshold)), type = "number")
      for (j in seq_along(cls_rows)) cls_rows[[j]][[key]] <- if (is.null(r$ap[[cls_rows[[j]]$class]])) NA_real_ else r$ap[[cls_rows[[j]]$class]]
    }
  }
  tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (time overlap)", columns = cls_cols, rows = cls_rows)
  mcols <- list(list(key = "threshold", label = "IoU threshold", type = "number"), list(key = "tp", label = "Matched", type = "integer"),
                list(key = "fp", label = "False alarms", type = "integer"), list(key = "fn", label = "Missed", type = "integer"),
                list(key = "precision", label = "Precision", type = "number"), list(key = "recall", label = "Recall", type = "number"),
                list(key = "f1", label = "F1", type = "number"))
  if (has_score) mcols[[length(mcols) + 1L]] <- list(key = "map", label = "mAP", type = "number")
  tables[[length(tables) + 1L]] <- list(key = "matching", title = "Segments matched at each IoU threshold", columns = mcols,
    rows = lapply(m_rows, function(r) r[c("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")]))
  pc <- character(0); pm <- character(0); pv <- numeric(0)
  for (r in m_rows) for (km in list(c("f1", "F1"), c("precision", "Precision"), c("recall", "Recall"))) if (!is.na(r[[km[1]]])) {
    pc <- c(pc, sprintf("IoU %s", tkey(r$threshold))); pm <- c(pm, km[2]); pv <- c(pv, r[[km[1]]])
  }
  if (length(pv)) {
    charts[[length(charts) + 1L]] <- cs_chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", list(
      category = cs_col("IoU threshold", pc, "categorical", levels = vapply(m_rows, function(r) sprintf("IoU %s", tkey(r$threshold)), character(1))),
      value = cs_col("Share", pv, "numeric"),
      group = cs_col("Measure", pm, "categorical", levels = c("F1", "Precision", "Recall"))))
  }
} else {
  tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (pixels summed over images)", columns = cls_cols, rows = cls_rows)
  tables[[length(tables) + 1L]] <- list(key = "images", title = "Mean IoU per image", rows = utils::head(group_rows, 500),
    columns = c(list(list(key = "group", label = GROUP, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
                list(list(key = "miou", label = "Mean IoU", type = "number"))),
    note = if (length(group_rows) > 500) "First 500 images." else NULL)
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (j in seq_along(names_)) for (km in list(c("iou", "IoU"), c("dice", "Dice"))) if (!is.na(res[[km[1]]][j])) {
  dc <- c(dc, names_[j]); dm <- c(dm, km[2]); dv <- c(dv, res[[km[1]]][j])
}
if (length(dv)) {
  charts <- c(list(cs_chart("by-class", "cleveland-dot", "IoU and Dice by class", list(
    category = cs_col(LABEL, dc, "categorical", levels = names_), value = cs_col("Overlap", dv, "numeric"),
    group = cs_col("Measure", dm, "categorical", levels = c("IoU", "Dice"))))), charts)
}
what <- if (KIND == "masks") "pixel accuracy" else "time-weighted accuracy"
summary <- sprintf("Across %d %s and %d classes, mean IoU = %s, mean Dice = %s and %s = %s.", n_groups, if (KIND == "masks") "images" else "recordings",
                   length(names_), f3(res$miou), f3(res$mean_dice), what, f3(res$accuracy))
if (KIND == "intervals") {
  summary <- paste0(summary, " Segment F1: ", paste(vapply(res$matching, function(r) sprintf("%s at IoU %s", f3(r$f1), tkey(r$threshold)), character(1)), collapse = ", "), ".")
  if (has_score && !is.na(values$map)) summary <- paste0(summary, sprintf(" mAP over the thresholds = %s.", f3(values$map)))
}
cs_publish(list(
  method = "evaluate.segments",
  methodVersion = "1.1.0",
  title = "Segmentation quality",
  engine = cs_engine_info("nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = list(list(key = "miou", label = "Mean IoU", value = res$miou), list(key = "mean_dice", label = "Mean Dice", value = res$mean_dice),
                    list(key = "accuracy", label = if (KIND == "masks") "Pixel accuracy" else "Time-weighted accuracy", value = res$accuracy)),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
                      else "Reference rows come from the reference table; this table's rows are the predictions. ",
                      if (KIND == "masks") paste0("Masks are compared on their run lengths (no pixels decoded)", if (BACKGROUND) "; unlabeled pixels form a background class" else "",
                                                  if (!is.null(CROWD)) "; crowd regions are left out of scoring" else "", ".")
                      else paste0("Segments match within a recording and class, ", if (!is.null(SCORE)) "highest score first." else "earliest first."))),
  charts = charts,
  values = values
))
Python

Across 10 images and 4 classes, mean IoU = 0.403, mean Dice = 0.513 and pixel accuracy = 0.550.

Mean IoU
0.4027
Mean Dice
0.5126
Pixel accuracy
0.5497

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

Assumptions

  • The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
  • Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.

Per class (pixels summed over images)

labelReference pixelsPredicted pixelsOverlap (pixels)IoUDice
bicycle9,84414,1967,8570.48550.6537
car64,32226,06723,9590.36070.5301
dog03,012000
person38,22130,92429,9590.76450.8666

Mean IoU per image

media_idMean IoU
img010.4776
img020.4692
img030.2155
img040.3200
img050.6104
img060.5888
img070.3134
img080.8444
img090
img100
  • Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec ebc2b9896c4c2c9c
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.evaluate import detection as det  # RLE runs (twin: cs_eval_det_runs)
from codesplash.evaluate import segmentation as seg  # twin: codesplashr cs_eval_seg_*
from codesplash.evaluate.stacked import flags, image_keys, stacked  # twin: cs_eval_stacked
from codesplash.vision import boxes as vb  # COCO RLE strings (twin: cs_rle_*)

# %% Data
GROUP = "media_id"
FRAME = None
LABEL = "label"
SOURCE = "source"
MASK = "mask_rle"
WIDTH = "image_width"
HEIGHT = "image_height"
CROWD = None
START = None
END = None
SCORE = None
KIND = "masks"  # masks | intervals
BACKGROUND = False
THRESHOLDS = [float(t) for t in [0.1, 0.25, 0.5]] or [0.5]
THRESHOLDS = sorted(set(THRESHOLDS))
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"]  # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if KIND == "masks" and not (MASK and WIDTH and HEIGHT):
    cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="time intervals unless the mask, width and height columns are set", value="masks")
if KIND == "intervals" and not (START and END):
    cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="masks unless the start and end columns are set", value="time intervals")
pre_warnings = []
if REF_ROLES is not None:
    # The reference table's rows go above this table's rows under an added source column (twin: cs_eval_with_reference).
    from codesplash.graph import dataset_option  # the table the host wrote for the option
    from codesplash.evaluate.stacked import with_reference
    w = with_reference(df, dataset_option("target/academy-parity/run-8142/evaluate.segments/masks-no-background/out-python", "reference_table"),
                       {"group": GROUP, "frame": FRAME, "label": LABEL, "mask": MASK, "width": WIDTH, "height": HEIGHT, "crowd": CROWD,
                        "start": START, "end": END, "score": SCORE}, REF_ROLES,
                       {"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if KIND == "masks" else {"start": "Start", "end": "End"})},
                       SOURCE, REF_LEVEL, ["group", "label"] + (["mask", "width", "height"] if KIND == "masks" else ["start", "end"]))
    df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
    GROUP, FRAME, LABEL, MASK, WIDTH, HEIGHT = wc["group"], wc["frame"], wc["label"], wc["mask"], wc["width"], wc["height"]
    CROWD, START, END = wc["crowd"], wc["start"], wc["end"]
    SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [GROUP, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if KIND == "masks" else [START, END])
numeric = [WIDTH, HEIGHT] if KIND == "masks" else [c for c in [START, END, SCORE] if c]
st = stacked(df, needed, numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
    cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
crowd = flags(df[CROWD]) if (CROWD and KIND == "masks") else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False
classes = sorted(set(labels_all[~crowd].tolist()))

if KIND == "masks":
    # %% Masks → runs, per image
    img_idx, images = image_keys(df[GROUP], df[FRAME] if FRAME else None)
    ws, hs = df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)
    runs, n_bad = [], 0
    for s, w, h in zip(df[MASK].tolist(), ws, hs):
        try:
            runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
        except (ValueError, OverflowError):
            runs.append(None)
            n_bad += 1
    if n_bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
    ims = [{"n": None, "ref": {}, "pred": {}, "void": []} for _ in images]
    for i, r in enumerate(runs):
        im = ims[int(img_idx[i])]
        n = float(r[2][0]) * float(r[2][1])
        if im["n"] is None:
            im["n"], im["size"] = n, r[2]
        elif im["size"] != r[2]:
            cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
        if crowd[i]:
            im["void"].append(r[:2])
        else:
            side = im["ref"] if is_ref[i] else im["pred"]
            side.setdefault(labels_all[i], []).append(r[:2])
    res = seg.mask_scores(ims, classes, BACKGROUND)
    names = res["classes"]
    n_ref = int(np.sum(is_ref & ~crowd))
    n_pred = int(np.sum(~is_ref))
    unit = "pixels"
    group_rows = [{"group": m, "frame": None if f == float("-inf") else f, "miou": res["per_image"][i]} for i, (m, f) in enumerate(images)]
    n_groups = len(images)
else:
    # %% Intervals per recording
    s_all, e_all = df[START].to_numpy(dtype=float), df[END].to_numpy(dtype=float)
    bad = e_all < s_all
    if bad.any():
        cs.cs_error("CS_E_INVALID_VALUES", column=END, requirement=f"at least {START}", count=int(bad.sum()))
    sc_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan) if SCORE else np.full(len(df), np.nan)
    has_score = SCORE is not None
    if has_score:
        miss = ~is_ref & np.isnan(sc_all)
        if miss.any():
            warnings.append(f"{int(miss.sum())} predicted segments have no {SCORE} and were left out.")
            keep = ~miss
            df, is_ref, labels_all, s_all, e_all, sc_all = df.loc[keep].reset_index(drop=True), is_ref[keep], labels_all[keep], s_all[keep], e_all[keep], sc_all[keep]
            classes = sorted(set(labels_all.tolist()))
    grp = np.asarray([str(x) for x in df[GROUP].tolist()], dtype=object)
    groups = sorted(set(grp.tolist()))
    recs = []
    for g in groups:
        rows = np.flatnonzero(grp == g)
        recs.append({"ref": [(s_all[i], e_all[i], labels_all[i]) for i in rows if is_ref[i]],
                     "pred": [(s_all[i], e_all[i], labels_all[i], float(sc_all[i]) if has_score else 0.0, int(i)) for i in rows if not is_ref[i]]})
    res = seg.interval_scores(recs, classes, THRESHOLDS, has_score)
    names = res["classes"]
    n_ref, n_pred = res["n_ref"], res["n_pred"]
    unit = "seconds"
    n_groups = len(groups)

# %% Assumptions
assumptions = [
    {"key": "complete", "label": "The reference is complete", "status": "info",
     "detail": "Regions or segments missing from the reference turn correct predictions into errors."},
    {"key": "overlap", "label": "Reference classes don't overlap", "status": "info",
     "detail": "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area."},
]

# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
tkey = lambda t: "%g" % t
values = {"kind": KIND, "n_groups": n_groups, "n_classes": len(names), "n_reference": n_ref, "n_predictions": n_pred,
          "accuracy": res["accuracy"], "miou": res["miou"], "mean_dice": res["mean_dice"], "fw_iou": res["fw_iou"],
          "scored": res.get("scored", float(np.sum(res["gsum"]))), "ignored": res.get("ignored"), "map": None}
for j, c in enumerate(names):
    values[f"iou[{c}]"] = res["iou"][j]
    values[f"dice[{c}]"] = res["dice"][j]
cls_cols = [{"key": "class", "label": LABEL, "type": "string"}, {"key": "ref", "label": f"Reference {unit}", "type": "number"},
            {"key": "pred", "label": f"Predicted {unit}", "type": "number"}, {"key": "inter", "label": f"Overlap ({unit})", "type": "number"},
            {"key": "iou", "label": "IoU", "type": "number"}, {"key": "dice", "label": "Dice", "type": "number"}]
cls_rows = [{"class": c, "ref": float(res["gsum"][j]), "pred": float(res["psum"][j]), "inter": float(res["inter"][j]),
             "iou": res["iou"][j], "dice": res["dice"][j]} for j, c in enumerate(names)]
tables = []
charts = []
if KIND == "intervals":
    m_rows = res["matching"]
    for r in m_rows:
        values[f"f1[{tkey(r['threshold'])}]"] = r["f1"]
        values[f"precision[{tkey(r['threshold'])}]"] = r["precision"]
        values[f"recall[{tkey(r['threshold'])}]"] = r["recall"]
        if has_score:
            values[f"ap[{tkey(r['threshold'])}]"] = r["map"]
    if has_score:
        maps = [r["map"] for r in m_rows if r["map"] is not None]
        values["map"] = float(np.mean(maps)) if maps else None
        for r in m_rows:
            cls_cols.append({"key": f"ap_{tkey(r['threshold'])}", "label": f"AP@{tkey(r['threshold'])}", "type": "number"})
            for row in cls_rows:
                row[f"ap_{tkey(r['threshold'])}"] = r["ap"].get(row["class"])
    tables.append({"key": "classes", "title": "Per class (time overlap)", "columns": cls_cols, "rows": cls_rows})
    tables.append({"key": "matching", "title": "Segments matched at each IoU threshold",
                   "columns": [{"key": "threshold", "label": "IoU threshold", "type": "number"}, {"key": "tp", "label": "Matched", "type": "integer"},
                               {"key": "fp", "label": "False alarms", "type": "integer"}, {"key": "fn", "label": "Missed", "type": "integer"},
                               {"key": "precision", "label": "Precision", "type": "number"}, {"key": "recall", "label": "Recall", "type": "number"},
                               {"key": "f1", "label": "F1", "type": "number"}] + ([{"key": "map", "label": "mAP", "type": "number"}] if has_score else []),
                   "rows": [{k: r[k] for k in ("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")} for r in m_rows]})
    pts = [(f"IoU {tkey(r['threshold'])}", lab, r[key]) for r in m_rows for key, lab in (("f1", "F1"), ("precision", "Precision"), ("recall", "Recall")) if r[key] is not None]
    if pts:
        charts.append(cs.chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", {
            "category": cs.col("IoU threshold", [p[0] for p in pts], "categorical", levels=[f"IoU {tkey(r['threshold'])}" for r in m_rows]),
            "value": cs.col("Share", [p[2] for p in pts], "numeric"),
            "group": cs.col("Measure", [p[1] for p in pts], "categorical", levels=["F1", "Precision", "Recall"])}))
else:
    tables.append({"key": "classes", "title": "Per class (pixels summed over images)", "columns": cls_cols, "rows": cls_rows})
    tables.append({"key": "images", "title": "Mean IoU per image", "rows": group_rows[:500],
                   "columns": [{"key": "group", "label": GROUP, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else [])
                   + [{"key": "miou", "label": "Mean IoU", "type": "number"}], "note": "First 500 images." if len(group_rows) > 500 else None})
dots = [(c, m, res[key][j]) for j, c in enumerate(names) for key, m in (("iou", "IoU"), ("dice", "Dice")) if res[key][j] is not None]
if dots:
    charts.insert(0, cs.chart("by-class", "cleveland-dot", "IoU and Dice by class", {
        "category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=names),
        "value": cs.col("Overlap", [d[2] for d in dots], "numeric"),
        "group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["IoU", "Dice"])}))
what = "pixel accuracy" if KIND == "masks" else "time-weighted accuracy"
summary = (f"Across {n_groups} {'images' if KIND == 'masks' else 'recordings'} and {len(names)} classes, mean IoU = {f3(res['miou'])}, "
           f"mean Dice = {f3(res['mean_dice'])} and {what} = {f3(res['accuracy'])}.")
if KIND == "intervals":
    summary += " Segment F1: " + ", ".join(f"{f3(r['f1'])} at IoU {tkey(r['threshold'])}" for r in res["matching"]) + "."
    if has_score and values["map"] is not None:
        summary += f" mAP over the thresholds = {f3(values['map'])}."
cs.publish({
    "method": "evaluate.segments",
    "methodVersion": "1.1.0",
    "title": "Segmentation quality",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": "miou", "label": "Mean IoU", "value": res["miou"]}, {"key": "mean_dice", "label": "Mean Dice", "value": res["mean_dice"]},
                   {"key": "accuracy", "label": "Pixel accuracy" if KIND == "masks" else "Time-weighted accuracy", "value": res["accuracy"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
               else "Reference rows come from the reference table; this table's rows are the predictions. ")
              + ("Masks are compared on their run lengths (no pixels decoded)" + ("; unlabeled pixels form a background class" if BACKGROUND else "")
                 + ("; crowd regions are left out of scoring" if CROWD else "") + "." if KIND == "masks"
                 else "Segments match within a recording and class, " + ("highest score first." if SCORE else "earliest first."))],
    "charts": charts,
    "values": values,
})

Leaving the background out, mean IoU is 0.403 and mean Dice 0.513. Dice is always at least as high as IoU for the same masks, so never compare a Dice from one paper with an IoU from another.

06

Check: newer segmenters

Checkpoint

Check yourself

What does SegFormer's decoder do with the encoder's four feature maps?

Show the answer

Answer: a

The decoder is deliberately small; the multi-scale encoder does the heavy lifting.

Check yourself

Why does SegFormer handle test images of a new size better than a ViT with fixed position embeddings?

Show the answer

Answer: a

Overlapping patch merging carries position implicitly, so changing the grid size doesn't break a learned position table.

Check yourself

What is "mask classification"?

Show the answer

Answer: b

Predicting whole masks with a class each lets one model do semantic, instance and panoptic segmentation.

Check yourself

In Mask2Former's masked attention, what does a query attend to?

Show the answer

Answer: a

Restricting attention to the query's own region speeds training and sharpens masks; the empty-mask fallback avoids attending to nothing.

Check yourself

Why does SAM return several masks for a single point prompt?

Show the answer

Answer: a

Each candidate has a predicted quality. More clicks or a box remove the ambiguity.

Check yourself

You use SAM to label 2,000 images and keep, for each click, the mask with the highest predicted quality. What should you do before training on them?

Show the answer

Answer: b

The quality head is itself a prediction. Spot checks measure how often it picks wrongly on your images.

07

Recap

Recap
  • SegFormer fuses four scales of Transformer features with a small decoder and no position embeddings.
  • Mask2Former predicts a set of masks with classes and restricts each query's attention to its mask.
  • SAM turns clicks and boxes into several candidate masks; its quality score is a guess, so check samples.
  • Score masks per class with IoU or Dice, and never compare one with the other.

Concepts in this lesson