martinzink commented on code in PR #2258: URL: https://github.com/apache/nifi-minifi-cpp/pull/2258#discussion_r3989491722
########## minifi_rust/extensions/minifi_tensor/src/low_level_processors/filter_bounding_boxes.rs: ########## @@ -0,0 +1,566 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +mod filter_bounding_boxes_def; + +use crate::low_level_processors::image_to_tensor::ResizeMode; +use crate::utils::bounding_box::BoundingBox; +use crate::utils::dimensions::Dimensions; +use crate::utils::score_activation::ScoreActivation; +use crate::utils::tensor_helpers::{deserialize_tensors, tensor_as_f32}; +use filter_bounding_boxes_def::SUCCESS; +pub(crate) use filter_bounding_boxes_def::{ + BACKGROUND_CLASS_INDEX, BOX_FORMAT, BOX_OUTPUT_INDEX, CLASS_OUTPUT_INDEX, CONFIDENCE_THRESHOLD, + IOU_THRESHOLD, OUTPUT_ATTRIBUTE_NAME, SCORE_ACTIVATION, SCORE_OUTPUT_INDEX, +}; +use minifi_native::macros::{ComponentIdentifier, PropertyType}; +use minifi_native::{ + Content, FlowFileTransform, GetAttribute, GetId, GetProperty, InputStream, Logger, MinifiError, + ProcessError, RouteErrorExt, Schedule, TransformedFlowFile, debug, +}; +use strum_macros::{Display, EnumString, IntoStaticStr, VariantNames}; +use tract::Tensor; + +#[derive( + Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, IntoStaticStr, PropertyType, +)] +#[strum(serialize_all = "PascalCase", const_into_str)] +pub(crate) enum BoxFormat { + /// `[x_min, y_min, x_max, y_max]` — SSD, MobileNet-SSD, most PyTorch models. + Xyxy, + /// `[y_min, x_min, y_max, x_max]` — TensorFlow Object Detection API. + Yxyx, + /// `[cx, cy, w, h]` — YOLOv3/5/8 raw output (center + size). + Cxcywh, +} + +/// Convert the four floats at `box_floats[offset..offset+4]` into a canonical +/// `(x_min, y_min, x_max, y_max)` tuple, regardless of the source layout. +fn decode_box(box_floats: &[f32], offset: usize, format: BoxFormat) -> (f32, f32, f32, f32) { + let a = box_floats[offset]; + let b = box_floats[offset + 1]; + let c = box_floats[offset + 2]; + let d = box_floats[offset + 3]; + match format { + BoxFormat::Xyxy => (a, b, c, d), + BoxFormat::Yxyx => (b, a, d, c), + BoxFormat::Cxcywh => { + let (cx, cy, w, h) = (a, b, c, d); + (cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0) + } + } +} + +struct ScoredClass { + class_id: usize, + confidence: f32, +} + +fn score_box( + logits: &[f32], + activation: ScoreActivation, + background_class_index: Option<usize>, +) -> ScoredClass { + let num_classes = logits.len(); + + let best_valid = logits + .iter() + .enumerate() + .filter(|&(_, &logit)| logit.is_finite()) + .filter(|&(id, _)| match background_class_index { + Some(bg_idx) => !(num_classes > 1 && id == bg_idx), + None => true, + }) + .max_by(|a, b| a.1.total_cmp(b.1)); + + let (class_id, &best_logit) = match best_valid { + Some(val) => val, + None => { + return ScoredClass { + class_id: 0, + confidence: f32::NEG_INFINITY, + }; + } + }; + + let confidence = match activation { + ScoreActivation::Softmax => { + let max_logit = logits + .iter() + .copied() + .filter(|l| l.is_finite()) + .reduce(f32::max) + .unwrap_or(f32::NEG_INFINITY); + let sum_exp: f32 = logits + .iter() + .filter(|l| l.is_finite()) + .map(|&l| (l - max_logit).exp()) + .sum(); + + (best_logit - max_logit).exp() / sum_exp + } + ScoreActivation::Sigmoid => 1.0 / (1.0 + (-best_logit).exp()), + ScoreActivation::None => best_logit, + }; + + ScoredClass { + class_id, + confidence, + } +} + +/// Turn a single per-box score into a confidence for the "separate class-id +/// tensor" path. +/// Sigmoid maps a raw logit to a probability; +/// Softmax has no meaning over a single scalar, thus pass-through. +/// None passes the score through. +fn activate_scalar(score: f32, activation: ScoreActivation) -> f32 { + match activation { + ScoreActivation::Sigmoid => 1.0 / (1.0 + (-score).exp()), + ScoreActivation::Softmax | ScoreActivation::None => score, + } +} + +#[derive(ComponentIdentifier)] +pub(crate) struct FilterBoundingBoxes { + confidence_threshold: f32, + iou_threshold: f32, + score_output_index: usize, + box_output_index: usize, + box_format: BoxFormat, + score_activation: ScoreActivation, + background_class_index: Option<usize>, + class_output_index: Option<usize>, +} + +impl Schedule for FilterBoundingBoxes { + fn schedule<Ctx: GetProperty, L: Logger>( + context: &Ctx, + _logger: &L, + ) -> Result<Self, MinifiError> { + let confidence_threshold = context.get_property(&CONFIDENCE_THRESHOLD)?; + let iou_threshold = context.get_property(&IOU_THRESHOLD)?; + let score_output_index = context.get_property(&SCORE_OUTPUT_INDEX)?; + let box_output_index = context.get_property(&BOX_OUTPUT_INDEX)?; + let box_format = context.get_property(&BOX_FORMAT)?; + let score_activation = context.get_property(&SCORE_ACTIVATION)?; + let background_class_index = context.get_property(&BACKGROUND_CLASS_INDEX)?; + let class_output_index = context.get_property(&CLASS_OUTPUT_INDEX)?; + + Ok(Self { + confidence_threshold, + iou_threshold, + score_output_index, + box_output_index, + box_format, + score_activation, + background_class_index, + class_output_index, + }) + } +} + +impl FilterBoundingBoxes { + pub(crate) fn filter<'a, Context: GetProperty, LoggerImpl: Logger>( + &self, + context: &Context, + logger: &LoggerImpl, + tensors: Vec<Tensor>, + orig_dim: Dimensions, + target_dim: Dimensions, + resize_mode: ResizeMode, + ) -> Result<TransformedFlowFile<'a>, ProcessError> { + let score_floats = + tensor_as_f32(&tensors, self.score_output_index).route_err_to_failure()?; + let box_floats = tensor_as_f32(&tensors, self.box_output_index).route_err_to_failure()?; + + let (scale_x, scale_y, pad_x, pad_y) = match resize_mode { + ResizeMode::Letterbox => { + let scale = + (target_dim.width / orig_dim.width).min(target_dim.height / orig_dim.height); + let pad_x = (target_dim.width - (orig_dim.width * scale)) / 2.0; + let pad_y = (target_dim.height - (orig_dim.height * scale)) / 2.0; + (scale, scale, pad_x, pad_y) + } + ResizeMode::Stretch => ( + target_dim.width / orig_dim.width, + target_dim.height / orig_dim.height, + 0.0, + 0.0, + ), + }; + + if !box_floats.len().is_multiple_of(4) { + return Err(MinifiError::custom( + "Box tensor byte length is not a multiple of 16 (4 f32 per box)", + ) + .into()); + } + let num_boxes = box_floats.len() / 4; + if num_boxes == 0 { + debug!(logger, "No boxes to filter; emitting empty array"); + return Ok(TransformedFlowFile::new(&SUCCESS, None) + .with_content(b"[]".to_vec().into()) + .with_attribute("object.count", "0") + .with_attribute("mime.type", "application/json")); + } Review Comment: 👍 [remove code duplication from InvokeTract model and add result_via_out…](https://github.com/apache/nifi-minifi-cpp/pull/2258/commits/5c045ef6bec5000907d022b25afccbb2b77cfed1) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
