use std::cell::{Cell, OnceCell};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use eyre::{Result, ensure};
use crate::detector::{BoxPrompt, Detector, DetectorImage, QUERIES};
use crate::gpu::{Arg, Gpu, Precision, Tensor, launch};
use crate::image::{RgbImage, preprocess};
use crate::masks::{MaskBuffer, MaskPool};
use crate::nvtx::range;
use crate::ops::{B256, ew, upload_i32};
use crate::point::{
LOW_RES, MaskResize, PointDecoder, PointImage, PointPrompt, argmax, clamped_masks, fill_holes, pick_masks,
};
use crate::text::{TextEncoder, TextFeatures};
use crate::tokenizer::Tokenizer;
use crate::video::Tracker;
use crate::vision::{Backbone, Neck, Trunk};
use crate::weights::Weights;
pub const SCORE_THRESHOLD: f32 = 0.5;
pub const VISUAL_PROMPT: &str = "visual";
static NEXT_MODEL_ID: AtomicU64 = AtomicU64::new(0);
pub struct Embedding {
model: u64,
width: usize,
height: usize,
detector: DetectorImage,
point: PointImage,
}
impl Embedding {
pub fn width(&self) -> usize {
self.width
}
pub fn height(&self) -> usize {
self.height
}
}
#[derive(Clone, Debug)]
pub struct Detection {
pub score: f32,
pub bbox: [f32; 4],
pub query: usize,
}
#[derive(Clone, Debug, Default)]
pub struct Detections {
instances: Vec<Detection>,
masks: MaskBuffer,
}
impl Detections {
pub fn len(&self) -> usize {
self.instances.len()
}
pub fn is_empty(&self) -> bool {
self.instances.is_empty()
}
pub fn iter(&self) -> std::slice::Iter<'_, Detection> {
self.instances.iter()
}
pub fn mask(&self, i: usize) -> &[u8] {
assert!(i < self.len(), "mask {i} of {} detections", self.len());
let pixels = self.masks.len() / self.len();
&self.masks[i * pixels..][..pixels]
}
pub fn masks(&self) -> &[u8] {
&self.masks
}
pub fn into_parts(self) -> (Vec<Detection>, MaskBuffer) {
(self.instances, self.masks)
}
}
impl IntoIterator for Detections {
type Item = Detection;
type IntoIter = std::vec::IntoIter<Detection>;
fn into_iter(self) -> Self::IntoIter {
self.instances.into_iter()
}
}
impl<'a> IntoIterator for &'a Detections {
type Item = &'a Detection;
type IntoIter = std::slice::Iter<'a, Detection>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Clone, Debug)]
pub struct PointMask {
pub score: f32,
pub mask: MaskBuffer,
}
const HOLE_AREA: usize = 256;
pub const POINT_BATCH: usize = 16;
#[derive(Clone, Debug, Default)]
pub struct PointMasks {
scores: Vec<f32>,
masks: MaskBuffer,
}
impl PointMasks {
pub fn len(&self) -> usize {
self.scores.len()
}
pub fn is_empty(&self) -> bool {
self.scores.is_empty()
}
pub fn scores(&self) -> &[f32] {
&self.scores
}
pub fn mask(&self, i: usize) -> &[u8] {
assert!(i < self.len(), "mask {i} of {} prompts", self.len());
let pixels = self.masks.len() / self.len();
&self.masks[i * pixels..][..pixels]
}
pub fn masks(&self) -> &[u8] {
&self.masks
}
pub fn into_parts(self) -> (Vec<f32>, MaskBuffer) {
(self.scores, self.masks)
}
}
pub struct Sam3 {
id: u64,
tokenizer: Tokenizer,
pub(crate) backbone: Backbone,
neck: Neck,
pub(crate) tracker_neck: Neck,
text: TextEncoder,
detector: Detector,
pub(crate) point: PointDecoder,
pub(crate) tracker: Tracker,
visual: OnceCell<TextFeatures>,
last_kept: Cell<usize>,
masks: MaskPool,
pub(crate) gpu: Gpu,
}
impl Sam3 {
pub fn load(dir: &Path, device: usize, precision: Precision) -> Result<Self> {
Self::load_onto(Gpu::new(device, precision)?, dir)
}
#[cfg(feature = "online")]
pub fn from_pretrained(device: usize, precision: Precision) -> Result<Self> {
let gpu = Gpu::new(device, precision)?;
Self::load_onto(gpu, &crate::download_model()?)
}
fn load_onto(gpu: Gpu, dir: &Path) -> Result<Self> {
let tokenizer = Tokenizer::open(dir)?;
let wts = Weights::open(&dir.join("model.safetensors"))?;
let model = Self {
id: NEXT_MODEL_ID.fetch_add(1, Ordering::Relaxed),
tokenizer,
backbone: Backbone::load(&gpu, &wts)?,
neck: Neck::load(&gpu, &wts, "detector_model.vision_encoder.neck")?,
tracker_neck: Neck::load(&gpu, &wts, "tracker_neck")?,
text: TextEncoder::load(&gpu, &wts)?,
detector: Detector::load(&gpu, &wts)?,
point: PointDecoder::load(&gpu, &wts)?,
tracker: Tracker::load(&gpu, &wts)?,
visual: OnceCell::new(),
last_kept: Cell::new(0),
masks: MaskPool::default(),
gpu,
};
model.gpu.synchronize()?;
Ok(model)
}
pub fn precision(&self) -> Precision {
self.gpu.precision()
}
fn check(&self, emb: &Embedding) -> Result<()> {
ensure!(emb.model == self.id, "the embedding was encoded by a different Sam3 model");
self.gpu.bind()
}
pub fn encode(&self, img: &RgbImage) -> Result<Embedding> {
let gpu = &self.gpu;
gpu.bind()?;
let _r = range(c"encode");
let pixels = {
let _r = range(c"preprocess");
preprocess(gpu, img)?
};
let trunk = {
let _r = range(c"backbone");
self.backbone.forward(gpu, &pixels)?
};
drop(pixels);
let _r = range(c"necks");
let trunk = Trunk::new(gpu, trunk)?;
let point = self.point.prepare_image(gpu, &self.tracker_neck.forward(gpu, &trunk)?)?;
let detector = self.detector.prepare_image(gpu, self.neck.forward(gpu, &trunk)?)?;
gpu.synchronize()?;
Ok(Embedding { model: self.id, width: img.width(), height: img.height(), detector, point })
}
pub fn detect(&self, emb: &Embedding, text: &str, boxes: &[BoxPrompt]) -> Result<Detections> {
self.check(emb)?;
let gpu = &self.gpu;
let _r = range(c"detect");
let (w, h) = (emb.width, emb.height);
let reserved = self.masks.reserve((self.last_kept.get() + 1) * w * h);
let encode = || {
let _r = range(c"text");
self.text.forward(gpu, &self.tokenizer.tokenize(text)?)
};
let encoded;
let feats = if text == VISUAL_PROMPT {
match self.visual.get() {
Some(feats) => feats,
None => {
let feats = encode()?;
self.visual.get_or_init(|| feats)
}
}
} else {
encoded = encode()?;
&encoded
};
let out = self.detector.forward(gpu, &emb.detector, feats, boxes)?;
let _r = range(c"postprocess");
let presence = gpu.download(&out.presence)?[0];
let logits = gpu.download(&out.logits)?;
let boxes = gpu.download(&out.boxes)?;
let sigmoid = |x: f32| 1.0 / (1.0 + (-x).exp());
let presence = sigmoid(presence);
let kept: Vec<(usize, f32)> =
(0..QUERIES).map(|i| (i, sigmoid(logits[i]) * presence)).filter(|(_, p)| *p > SCORE_THRESHOLD).collect();
self.last_kept.set(kept.len());
if kept.is_empty() {
self.masks.release(reserved);
return Ok(Detections::default());
}
let side = LOW_RES * LOW_RES;
let idx: Vec<i32> = kept.iter().map(|(i, _)| *i as i32).collect();
let idx = upload_i32(gpu, idx)?;
let picked = gpu.empty(&[kept.len(), side])?;
launch!(gpu, "gather_rows", ew(picked.len()), B256, 0; &picked, &out.masks, idx.slice::<i32>(), side)?;
let mask = MaskResize::new(gpu, kept.len(), w, h)?.all(gpu, &picked)?;
let mut masks = self.masks.take(reserved, kept.len() * h * w)?;
gpu.download_into(&mask, &mut masks)?;
let instances = kept
.iter()
.map(|&(i, score)| {
let [cx, cy, bw, bh] = [boxes[i * 4], boxes[i * 4 + 1], boxes[i * 4 + 2], boxes[i * 4 + 3]];
let (wf, hf) = (w as f32, h as f32);
Detection {
score,
bbox: [(cx - bw / 2.0) * wf, (cy - bh / 2.0) * hf, (cx + bw / 2.0) * wf, (cy + bh / 2.0) * hf],
query: i,
}
})
.collect();
Ok(Detections { instances, masks })
}
pub fn segment_points(&self, emb: &Embedding, points: &[PointPrompt]) -> Result<PointMask> {
ensure!(!points.is_empty(), "segment_points needs at least one point");
let (mut scores, mask) = self.segment_points_batch(emb, &[points])?.into_parts();
Ok(PointMask { score: scores.remove(0), mask })
}
pub fn segment_points_batch(&self, emb: &Embedding, prompts: &[&[PointPrompt]]) -> Result<PointMasks> {
ensure!(prompts.iter().all(|p| !p.is_empty()), "every point prompt needs at least one point");
self.check(emb)?;
if prompts.is_empty() {
return Ok(PointMasks::default());
}
let gpu = &self.gpu;
let _r = range(c"segment_points");
let (w, h) = (emb.width, emb.height);
let plane = w * h;
let reserved = self.masks.reserve(prompts.len() * plane);
let mut order: Vec<usize> = (0..prompts.len()).collect();
order.sort_by_key(|&i| prompts[i].len());
let mut scores = vec![f32::NAN; prompts.len()];
let mut reserved = Some(reserved);
let mut masks = MaskBuffer::default();
for batch in
order.chunk_by(|&a, &b| prompts[a].len() == prompts[b].len()).flat_map(|run| run.chunks(POINT_BATCH))
{
let points: Vec<&[PointPrompt]> = batch.iter().map(|&i| prompts[i]).collect();
let (best, ious) = self.decode_points(emb, &points)?;
for (&i, iou) in batch.iter().zip(ious) {
scores[i] = iou;
}
let _r = range(c"postprocess");
fill_holes(gpu, &best, HOLE_AREA)?;
let resize = MaskResize::new(gpu, batch.len(), w, h)?;
let group = gpu.alloc_bytes(resize.group() * plane)?;
for part in resize.groups() {
resize.run(gpu, &best, part.clone(), Arg::slice(group.ptr(), part.len() * plane))?;
if let Some(reserved) = reserved.take() {
masks = self.masks.take(reserved, prompts.len() * plane)?;
}
let ids = &batch[part];
let mut j = 0;
for run in ids.chunk_by(|&a, &b| b == a + 1) {
let dst = &mut masks[run[0] * plane..][..run.len() * plane];
gpu.download_range_into(&group, j * plane, dst)?;
j += run.len();
}
}
}
Ok(PointMasks { scores, masks })
}
fn decode_points(&self, emb: &Embedding, prompts: &[&[PointPrompt]]) -> Result<(Tensor, Vec<f32>)> {
let gpu = &self.gpu;
let size = (emb.width, emb.height);
let img = &emb.point;
let best = |iou: &[f32]| -> Vec<usize> { iou.chunks(4).map(|c| argmax(&c[1..])).collect() };
let first = self.point.decode_batch(gpu, &img.embed, img, prompts, size, None, 1)?;
let mask_input = clamped_masks(gpu, &first.low_res, &best(&gpu.download(&first.iou)?))?;
let second = self.point.decode_batch(gpu, &img.embed, img, prompts, size, Some(&mask_input), 1)?;
let iou = gpu.download(&second.iou)?;
let picks = best(&iou);
let scores = picks.iter().enumerate().map(|(b, &i)| iou[b * 4 + 1 + i]).collect();
Ok((pick_masks(gpu, &second.low_res, &picks)?, scores))
}
}