1use crate::{
10 DType, Error, Matrix, OpAttribute, Result,
11 runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
12};
13
14pub fn box_iou(left: &Matrix, right: &Matrix) -> Result<Matrix> {
29 let rows_a = box_rows(left, "boxes_a")?;
30 let rows_b = box_rows(right, "boxes_b")?;
31 let runtime = left.runtime();
32 if !runtime.same_as(right.runtime()) {
33 return Err(Error::invalid_argument(
34 "vision::box_iou inputs must belong to the same runtime",
35 ));
36 }
37 let pair_count = rows_a
38 .checked_mul(rows_b)
39 .ok_or_else(|| Error::out_of_range("vision::box_iou pair count exceeds u32"))?;
40 let output_elements = usize::try_from(pair_count)
41 .map_err(|_| Error::out_of_range("vision::box_iou pair count exceeds usize"))?;
42 let output = Matrix::allocate(
43 runtime,
44 vec![rows_a as usize, rows_b as usize],
45 output_elements,
46 DType::F32,
47 )?;
48 let buffers = [
49 BufferBinding::read(left.storage()),
50 BufferBinding::read(right.storage()),
51 BufferBinding::write(output.storage()),
52 ];
53 let push_constants = [PushConstant::U32(rows_a), PushConstant::U32(rows_b)];
54 let inputs = [left, right];
55 let outputs = [&output];
56 runtime.record_semantic(
57 ComputeDispatch {
58 kernel: KernelId::VisionBoxIouF32,
59 buffers: &buffers,
60 push_constants: &push_constants,
61 workgroups: KernelId::VisionBoxIouF32.linear_workgroups(pair_count),
62 indirect: None,
63 },
64 SemanticDispatch {
65 contract: crate::core::operation::vision::BOX_IOU,
66 inputs: &inputs,
67 outputs: &outputs,
68 attributes: &[],
69 },
70 )?;
71 Ok(output)
72}
73
74#[derive(Clone, Copy, Debug, PartialEq)]
76pub struct NmsConfig {
77 pub iou_threshold: f32,
79 pub score_threshold: f32,
81 pub max_detections: i32,
83 pub class_agnostic: bool,
85}
86
87impl Default for NmsConfig {
88 fn default() -> Self {
89 Self {
90 iou_threshold: 0.45,
91 score_threshold: 0.0,
92 max_detections: 100,
93 class_agnostic: false,
94 }
95 }
96}
97
98pub struct NmsResult {
100 pub indices: Matrix,
102 pub count: Matrix,
104}
105
106pub fn nms(
118 boxes: &Matrix,
119 scores: &Matrix,
120 classes: &Matrix,
121 config: NmsConfig,
122) -> Result<NmsResult> {
123 let count = box_rows(boxes, "boxes")?;
124 vector(scores, "scores", count as usize, DType::F32)?;
125 vector(classes, "classes", count as usize, DType::I32)?;
126 validate_same_runtime(boxes, &[scores, classes], "vision::nms")?;
127 if !config.iou_threshold.is_finite() || !(0.0..=1.0).contains(&config.iou_threshold) {
128 return Err(Error::invalid_argument(
129 "vision::nms iou_threshold must be finite and in [0, 1]",
130 ));
131 }
132 if !config.score_threshold.is_finite() {
133 return Err(Error::invalid_argument(
134 "vision::nms score_threshold must be finite",
135 ));
136 }
137 let maximum = u32::try_from(config.max_detections)
138 .map_err(|_| Error::invalid_argument("vision::nms max_detections must be positive"))?
139 .min(count);
140 if maximum == 0 {
141 return Err(Error::invalid_argument(
142 "vision::nms max_detections must be positive",
143 ));
144 }
145 let runtime = boxes.runtime();
146 let indices = Matrix::allocate(
147 runtime,
148 vec![maximum as usize],
149 maximum as usize,
150 DType::I32,
151 )?;
152 let selected_count = Matrix::allocate(runtime, vec![1], 1, DType::U32)?;
153 let buffers = [
154 BufferBinding::read(boxes.storage()),
155 BufferBinding::read(scores.storage()),
156 BufferBinding::read(classes.storage()),
157 BufferBinding::write(indices.storage()),
158 BufferBinding::write(selected_count.storage()),
159 ];
160 let push_constants = [
161 PushConstant::U32(count),
162 PushConstant::U32(maximum),
163 PushConstant::U32(u32::from(config.class_agnostic)),
164 PushConstant::F32(config.iou_threshold),
165 PushConstant::F32(config.score_threshold),
166 ];
167 let inputs = [boxes, scores, classes];
168 let outputs = [&indices, &selected_count];
169 let attributes = [
170 OpAttribute::Float {
171 name: "iouThreshold".into(),
172 value: f64::from(config.iou_threshold),
173 },
174 OpAttribute::Float {
175 name: "scoreThreshold".into(),
176 value: f64::from(config.score_threshold),
177 },
178 OpAttribute::SignedInteger {
179 name: "maxDetections".into(),
180 value: i64::from(config.max_detections),
181 },
182 OpAttribute::Boolean {
183 name: "classAgnostic".into(),
184 value: config.class_agnostic,
185 },
186 ];
187 runtime.record_semantic(
188 ComputeDispatch {
189 kernel: KernelId::VisionNmsF32,
190 buffers: &buffers,
191 push_constants: &push_constants,
192 workgroups: [1, 1, 1],
193 indirect: None,
194 },
195 SemanticDispatch {
196 contract: crate::core::operation::vision::NMS,
197 inputs: &inputs,
198 outputs: &outputs,
199 attributes: &attributes,
200 },
201 )?;
202 Ok(NmsResult {
203 indices,
204 count: selected_count,
205 })
206}
207
208pub fn confusion_matrix(predicted: &Matrix, target: &Matrix, class_count: i32) -> Result<Matrix> {
218 let element_count = equal_nonempty(predicted, target, DType::I32, "vision::confusion_matrix")?;
219 if predicted.shape().len() != 1 {
220 return Err(Error::invalid_argument(format!(
221 "vision::confusion_matrix inputs must be vectors; received {:?}",
222 predicted.shape()
223 )));
224 }
225 let classes = positive_class_count(class_count, "vision::confusion_matrix")?;
226 let output_elements = classes
227 .checked_mul(classes)
228 .ok_or_else(|| Error::out_of_range("vision::confusion_matrix output exceeds u32"))?;
229 let output = Matrix::allocate(
230 predicted.runtime(),
231 vec![classes as usize, classes as usize],
232 output_elements as usize,
233 DType::U32,
234 )?;
235 let clear_count = output_elements;
236 let clear_buffers = [BufferBinding::write(output.storage())];
237 let clear_push = [PushConstant::U32(clear_count)];
238 let count_buffers = [
239 BufferBinding::read(predicted.storage()),
240 BufferBinding::read(target.storage()),
241 BufferBinding::read_write(output.storage()),
242 ];
243 let count_push = [PushConstant::U32(element_count), PushConstant::U32(classes)];
244 let dispatches = [
245 ComputeDispatch {
246 kernel: KernelId::VisionConfusionMatrixClearU32,
247 buffers: &clear_buffers,
248 push_constants: &clear_push,
249 workgroups: KernelId::VisionConfusionMatrixClearU32.linear_workgroups(clear_count),
250 indirect: None,
251 },
252 ComputeDispatch {
253 kernel: KernelId::VisionConfusionMatrixI32,
254 buffers: &count_buffers,
255 push_constants: &count_push,
256 workgroups: KernelId::VisionConfusionMatrixI32.linear_workgroups(element_count),
257 indirect: None,
258 },
259 ];
260 let inputs = [predicted, target];
261 let outputs = [&output];
262 let attributes = [OpAttribute::SignedInteger {
263 name: "classCount".into(),
264 value: i64::from(classes),
265 }];
266 predicted.runtime().record_split_semantic(
267 &dispatches,
268 SemanticDispatch {
269 contract: crate::core::operation::vision::CONFUSION_MATRIX,
270 inputs: &inputs,
271 outputs: &outputs,
272 attributes: &attributes,
273 },
274 )?;
275 Ok(output)
276}
277
278pub fn binary_mask_counts(predicted: &Matrix, target: &Matrix) -> Result<Matrix> {
286 let element_count = equal_nonempty(predicted, target, DType::U8, "vision::binary_mask_counts")?;
287 let output = Matrix::allocate(predicted.runtime(), vec![4], 4, DType::U32)?;
288 let clear_buffers = [BufferBinding::write(output.storage())];
289 let clear_push = [PushConstant::U32(4)];
290 let count_buffers = [
291 BufferBinding::read(predicted.storage()),
292 BufferBinding::read(target.storage()),
293 BufferBinding::read_write(output.storage()),
294 ];
295 let count_push = [PushConstant::U32(element_count)];
296 let dispatches = [
297 ComputeDispatch {
298 kernel: KernelId::VisionBinaryMaskCountsClearU32,
299 buffers: &clear_buffers,
300 push_constants: &clear_push,
301 workgroups: KernelId::VisionBinaryMaskCountsClearU32.linear_workgroups(4),
302 indirect: None,
303 },
304 ComputeDispatch {
305 kernel: KernelId::VisionBinaryMaskCountsU8,
306 buffers: &count_buffers,
307 push_constants: &count_push,
308 workgroups: KernelId::VisionBinaryMaskCountsU8.linear_workgroups(element_count),
309 indirect: None,
310 },
311 ];
312 let inputs = [predicted, target];
313 let outputs = [&output];
314 predicted.runtime().record_split_semantic(
315 &dispatches,
316 SemanticDispatch {
317 contract: crate::core::operation::vision::BINARY_MASK_COUNTS,
318 inputs: &inputs,
319 outputs: &outputs,
320 attributes: &[],
321 },
322 )?;
323 Ok(output)
324}
325
326pub struct DetectionMetricsResult {
328 pub counts: Matrix,
330 pub per_class: Matrix,
332 pub mean_average_precision_by_threshold: Matrix,
334 pub mean_average_precision: Matrix,
336}
337
338#[allow(clippy::too_many_arguments)]
349pub fn evaluate(
350 predicted_boxes: &Matrix,
351 predicted_scores: &Matrix,
352 predicted_classes: &Matrix,
353 predicted_image_ids: &Matrix,
354 target_boxes: &Matrix,
355 target_classes: &Matrix,
356 target_image_ids: &Matrix,
357 iou_thresholds: &Matrix,
358 class_count: i32,
359 score_threshold: f32,
360) -> Result<DetectionMetricsResult> {
361 let predicted = box_rows(predicted_boxes, "predicted_boxes")?;
362 let targets = box_rows(target_boxes, "target_boxes")?;
363 vector(
364 predicted_scores,
365 "predicted_scores",
366 predicted as usize,
367 DType::F32,
368 )?;
369 vector(
370 predicted_classes,
371 "predicted_classes",
372 predicted as usize,
373 DType::I32,
374 )?;
375 vector(
376 predicted_image_ids,
377 "predicted_image_ids",
378 predicted as usize,
379 DType::I32,
380 )?;
381 vector(
382 target_classes,
383 "target_classes",
384 targets as usize,
385 DType::I32,
386 )?;
387 vector(
388 target_image_ids,
389 "target_image_ids",
390 targets as usize,
391 DType::I32,
392 )?;
393 let threshold_count = nonempty_vector(iou_thresholds, "iou_thresholds", DType::F32)?;
394 let classes = positive_class_count(class_count, "vision::evaluate")?;
395 if !score_threshold.is_finite() {
396 return Err(Error::invalid_argument(
397 "vision::evaluate score_threshold must be finite",
398 ));
399 }
400 validate_same_runtime(
401 predicted_boxes,
402 &[
403 predicted_scores,
404 predicted_classes,
405 predicted_image_ids,
406 target_boxes,
407 target_classes,
408 target_image_ids,
409 iou_thresholds,
410 ],
411 "vision::evaluate",
412 )?;
413 let pair_count = threshold_count
414 .checked_mul(classes)
415 .ok_or_else(|| Error::out_of_range("vision::evaluate threshold-class pairs exceed u32"))?;
416 let state_stride = predicted
417 .checked_add(targets)
418 .ok_or_else(|| Error::out_of_range("vision::evaluate state stride exceeds u32"))?;
419 let state_elements = pair_count
420 .checked_mul(state_stride)
421 .ok_or_else(|| Error::out_of_range("vision::evaluate state scratch exceeds u32"))?;
422 let curve_elements = pair_count
423 .checked_mul(predicted)
424 .and_then(|value| value.checked_mul(2))
425 .ok_or_else(|| Error::out_of_range("vision::evaluate curve scratch exceeds u32"))?;
426 let counts_elements = pair_count
427 .checked_mul(3)
428 .ok_or_else(|| Error::out_of_range("vision::evaluate counts output exceeds u32"))?;
429 let metrics_elements = pair_count
430 .checked_mul(4)
431 .ok_or_else(|| Error::out_of_range("vision::evaluate metrics output exceeds u32"))?;
432 let runtime = predicted_boxes.runtime();
433 let state = allocate(
434 runtime,
435 &[pair_count, state_stride],
436 state_elements,
437 DType::U32,
438 )?;
439 let curve = allocate(
440 runtime,
441 &[pair_count, predicted, 2],
442 curve_elements,
443 DType::F32,
444 )?;
445 let counts = allocate(
446 runtime,
447 &[threshold_count, classes, 3],
448 counts_elements,
449 DType::U32,
450 )?;
451 let per_class = allocate(
452 runtime,
453 &[threshold_count, classes, 4],
454 metrics_elements,
455 DType::F32,
456 )?;
457 let map_by_threshold = allocate(runtime, &[threshold_count], threshold_count, DType::F32)?;
458 let mean_average_precision = allocate(runtime, &[1], 1, DType::F32)?;
459
460 let curves_buffers = [
461 BufferBinding::read(predicted_boxes.storage()),
462 BufferBinding::read(predicted_scores.storage()),
463 BufferBinding::read(predicted_classes.storage()),
464 BufferBinding::read(predicted_image_ids.storage()),
465 BufferBinding::read(target_boxes.storage()),
466 BufferBinding::read(target_classes.storage()),
467 BufferBinding::read(target_image_ids.storage()),
468 BufferBinding::read(iou_thresholds.storage()),
469 BufferBinding::write(state.storage()),
470 BufferBinding::write(curve.storage()),
471 BufferBinding::write(counts.storage()),
472 BufferBinding::write(per_class.storage()),
473 ];
474 let curves_push = [
475 PushConstant::U32(predicted),
476 PushConstant::U32(targets),
477 PushConstant::U32(threshold_count),
478 PushConstant::U32(classes),
479 PushConstant::U32(state_stride),
480 PushConstant::F32(score_threshold),
481 ];
482 let ap_buffers = [
483 BufferBinding::read(curve.storage()),
484 BufferBinding::read(counts.storage()),
485 BufferBinding::read_write(per_class.storage()),
486 ];
487 let ap_push = [PushConstant::U32(predicted), PushConstant::U32(pair_count)];
488 let mean_buffers = [
489 BufferBinding::read(counts.storage()),
490 BufferBinding::read(per_class.storage()),
491 BufferBinding::write(map_by_threshold.storage()),
492 BufferBinding::write(mean_average_precision.storage()),
493 ];
494 let mean_push = [
495 PushConstant::U32(threshold_count),
496 PushConstant::U32(classes),
497 ];
498 let dispatches = [
499 ComputeDispatch {
500 kernel: KernelId::VisionDetectionMetricCurvesF32,
501 buffers: &curves_buffers,
502 push_constants: &curves_push,
503 workgroups: [pair_count, 1, 1],
504 indirect: None,
505 },
506 ComputeDispatch {
507 kernel: KernelId::VisionDetectionAveragePrecisionF32,
508 buffers: &ap_buffers,
509 push_constants: &ap_push,
510 workgroups: [pair_count, 1, 1],
511 indirect: None,
512 },
513 ComputeDispatch {
514 kernel: KernelId::VisionDetectionMeanAveragePrecisionF32,
515 buffers: &mean_buffers,
516 push_constants: &mean_push,
517 workgroups: [1, 1, 1],
518 indirect: None,
519 },
520 ];
521 let inputs = [
522 predicted_boxes,
523 predicted_scores,
524 predicted_classes,
525 predicted_image_ids,
526 target_boxes,
527 target_classes,
528 target_image_ids,
529 iou_thresholds,
530 ];
531 let outputs = [
532 &counts,
533 &per_class,
534 &map_by_threshold,
535 &mean_average_precision,
536 ];
537 let attributes = [
538 OpAttribute::SignedInteger {
539 name: "classCount".into(),
540 value: i64::from(class_count),
541 },
542 OpAttribute::Float {
543 name: "scoreThreshold".into(),
544 value: f64::from(score_threshold),
545 },
546 ];
547 runtime.record_split_semantic(
548 &dispatches,
549 SemanticDispatch {
550 contract: crate::core::operation::vision::EVALUATE,
551 inputs: &inputs,
552 outputs: &outputs,
553 attributes: &attributes,
554 },
555 )?;
556 Ok(DetectionMetricsResult {
557 counts,
558 per_class,
559 mean_average_precision_by_threshold: map_by_threshold,
560 mean_average_precision,
561 })
562}
563
564pub struct SegmentationMetricsResult {
566 pub confusion: Matrix,
568 pub per_class: Matrix,
570 pub mean_iou: Matrix,
572 pub pixel_accuracy: Matrix,
574}
575
576pub fn evaluate_segmentation(
587 predicted: &Matrix,
588 target: &Matrix,
589 class_count: i32,
590) -> Result<SegmentationMetricsResult> {
591 let element_count = equal_nonempty(
592 predicted,
593 target,
594 DType::I32,
595 "vision::evaluate_segmentation",
596 )?;
597 let classes = positive_class_count(class_count, "vision::evaluate_segmentation")?;
598 let confusion_elements = classes
599 .checked_mul(classes)
600 .ok_or_else(|| Error::out_of_range("vision::evaluate_segmentation confusion exceeds u32"))?;
601 let per_class_elements = classes
602 .checked_mul(4)
603 .ok_or_else(|| Error::out_of_range("vision::evaluate_segmentation metrics exceed u32"))?;
604 let runtime = predicted.runtime();
605 let confusion = allocate(runtime, &[classes, classes], confusion_elements, DType::U32)?;
606 let per_class = allocate(runtime, &[classes, 4], per_class_elements, DType::F32)?;
607 let mean_iou = allocate(runtime, &[1], 1, DType::F32)?;
608 let pixel_accuracy = allocate(runtime, &[1], 1, DType::F32)?;
609 let confusion_buffers = [
610 BufferBinding::read(predicted.storage()),
611 BufferBinding::read(target.storage()),
612 BufferBinding::read_write(confusion.storage()),
613 ];
614 let confusion_push = [PushConstant::U32(element_count), PushConstant::U32(classes)];
615 let clear_buffers = [BufferBinding::write(confusion.storage())];
616 let clear_push = [PushConstant::U32(confusion_elements)];
617 let metrics_buffers = [
618 BufferBinding::read(confusion.storage()),
619 BufferBinding::write(per_class.storage()),
620 BufferBinding::write(mean_iou.storage()),
621 BufferBinding::write(pixel_accuracy.storage()),
622 ];
623 let metrics_push = [PushConstant::U32(classes)];
624 let dispatches = [
625 ComputeDispatch {
626 kernel: KernelId::VisionSegmentationConfusionClearU32,
627 buffers: &clear_buffers,
628 push_constants: &clear_push,
629 workgroups: KernelId::VisionSegmentationConfusionClearU32
630 .linear_workgroups(confusion_elements),
631 indirect: None,
632 },
633 ComputeDispatch {
634 kernel: KernelId::VisionSegmentationConfusionI32,
635 buffers: &confusion_buffers,
636 push_constants: &confusion_push,
637 workgroups: KernelId::VisionSegmentationConfusionI32.linear_workgroups(element_count),
638 indirect: None,
639 },
640 ComputeDispatch {
641 kernel: KernelId::VisionSegmentationMetricsF32,
642 buffers: &metrics_buffers,
643 push_constants: &metrics_push,
644 workgroups: [1, 1, 1],
645 indirect: None,
646 },
647 ];
648 let inputs = [predicted, target];
649 let outputs = [&confusion, &per_class, &mean_iou, &pixel_accuracy];
650 let attributes = [OpAttribute::SignedInteger {
651 name: "classCount".into(),
652 value: i64::from(class_count),
653 }];
654 runtime.record_split_semantic(
655 &dispatches,
656 SemanticDispatch {
657 contract: crate::core::operation::vision::EVALUATE_SEGMENTATION,
658 inputs: &inputs,
659 outputs: &outputs,
660 attributes: &attributes,
661 },
662 )?;
663 Ok(SegmentationMetricsResult {
664 confusion,
665 per_class,
666 mean_iou,
667 pixel_accuracy,
668 })
669}
670
671fn box_rows(boxes: &Matrix, label: &str) -> Result<u32> {
672 if boxes.dtype() != DType::F32 {
673 return Err(Error::invalid_argument(format!(
674 "vision box input {label} must use f32 storage; received {}",
675 boxes.dtype().token()
676 )));
677 }
678 let [rows, columns] = boxes.shape() else {
679 return Err(Error::invalid_argument(format!(
680 "vision box input {label} must have shape [N, 4]; received {:?}",
681 boxes.shape()
682 )));
683 };
684 if *rows == 0 || *columns != 4 {
685 return Err(Error::invalid_argument(format!(
686 "vision box input {label} must have nonempty shape [N, 4]; received {:?}",
687 boxes.shape()
688 )));
689 }
690 u32::try_from(*rows)
691 .map_err(|_| Error::out_of_range(format!("vision box input {label} row count exceeds u32")))
692}
693
694fn vector(matrix: &Matrix, label: &str, length: usize, dtype: DType) -> Result<()> {
695 if matrix.shape() != [length] || matrix.dtype() != dtype {
696 return Err(Error::invalid_argument(format!(
697 "vision input {label} must have shape [{length}] and dtype {}; received {:?} {}",
698 dtype.token(),
699 matrix.shape(),
700 matrix.dtype().token()
701 )));
702 }
703 Ok(())
704}
705
706fn nonempty_vector(matrix: &Matrix, label: &str, dtype: DType) -> Result<u32> {
707 let [length] = matrix.shape() else {
708 return Err(Error::invalid_argument(format!(
709 "vision input {label} must be a nonempty {} vector; received {:?}",
710 dtype.token(),
711 matrix.shape()
712 )));
713 };
714 if *length == 0 || matrix.dtype() != dtype {
715 return Err(Error::invalid_argument(format!(
716 "vision input {label} must be a nonempty {} vector; received {:?} {}",
717 dtype.token(),
718 matrix.shape(),
719 matrix.dtype().token()
720 )));
721 }
722 u32::try_from(*length)
723 .map_err(|_| Error::out_of_range(format!("vision input {label} length exceeds u32")))
724}
725
726fn equal_nonempty(left: &Matrix, right: &Matrix, dtype: DType, operation: &str) -> Result<u32> {
727 if left.shape() != right.shape() || left.dtype() != dtype || right.dtype() != dtype {
728 return Err(Error::invalid_argument(format!(
729 "{operation} requires equal-shaped {} inputs; received {:?} {} and {:?} {}",
730 dtype.token(),
731 left.shape(),
732 left.dtype().token(),
733 right.shape(),
734 right.dtype().token()
735 )));
736 }
737 if left.num_elements() == 0 {
738 return Err(Error::invalid_argument(format!(
739 "{operation} inputs must be nonempty"
740 )));
741 }
742 validate_same_runtime(left, &[right], operation)?;
743 u32::try_from(left.num_elements())
744 .map_err(|_| Error::out_of_range(format!("{operation} element count exceeds u32")))
745}
746
747fn validate_same_runtime(reference: &Matrix, others: &[&Matrix], operation: &str) -> Result<()> {
748 if others
749 .iter()
750 .any(|matrix| !reference.runtime().same_as(matrix.runtime()))
751 {
752 return Err(Error::invalid_argument(format!(
753 "{operation} inputs must belong to the same runtime"
754 )));
755 }
756 Ok(())
757}
758
759fn positive_class_count(class_count: i32, operation: &str) -> Result<u32> {
760 u32::try_from(class_count)
761 .ok()
762 .filter(|count| *count != 0)
763 .ok_or_else(|| Error::invalid_argument(format!("{operation} class_count must be positive")))
764}
765
766fn allocate(
767 runtime: &crate::runtime::RuntimeHandle,
768 shape: &[u32],
769 element_count: u32,
770 dtype: DType,
771) -> Result<Matrix> {
772 Matrix::allocate(
773 runtime,
774 shape.iter().map(|value| *value as usize).collect(),
775 element_count as usize,
776 dtype,
777 )
778}