martinzink commented on code in PR #2258: URL: https://github.com/apache/nifi-minifi-cpp/pull/2258#discussion_r4103770014
########## minifi_rust/extensions/minifi_tensor/src/low_level_processors/classify_output.rs: ########## @@ -0,0 +1,476 @@ +// 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. + +use crate::utils::score_activation::{ScoreActivation, SoftmaxTerms}; +use crate::utils::tensor_helpers::{deserialize_tensors, tensor_as_f32, tensor_shape}; +use classify_output_def::SUCCESS; +pub(crate) use classify_output_def::{ + CLASSIFY_OUTPUT_ATTRIBUTES, CONFIDENCE_THRESHOLD, LABEL_INDEX_OFFSET, LABELS_FILE_PATH, + OUTPUT_ATTRIBUTE_NAME, SCORE_ACTIVATION, SCORE_OUTPUT_INDEX, TOP_K, +}; +use minifi_native::macros::ComponentIdentifier; +use minifi_native::{ + Content, FlowFileTransform, GetAttribute, GetId, GetProperty, InputStream, Logger, MinifiError, + ProcessError, RouteErrorExt, Schedule, TransformedFlowFile, warn, +}; +use serde::Serialize; +use std::path::Path; +use tract::Tensor; + +mod classify_output_def; + +#[derive(Serialize, Clone, Debug, PartialEq)] +struct Prediction { + class_id: usize, + confidence: f32, + #[serde(skip_serializing_if = "Option::is_none")] + class_name: Option<String>, +} + +fn load_labels(path: &Path) -> Result<Vec<String>, MinifiError> { + let content = std::fs::read_to_string(path).map_err(|e| { + MinifiError::custom(format!("Failed to read labels file '{:?}': {}", path, e)) + })?; + Ok(content + .lines() + .map(|line| line.trim().to_string()) + .collect()) +} + +fn top_k(mut scored: Vec<(usize, f32)>, k: usize) -> Vec<(usize, f32)> { + scored.sort_by(|&(ai, a), &(bi, b)| b.total_cmp(&a).then(ai.cmp(&bi))); + scored.truncate(k); + scored +} + +#[derive(ComponentIdentifier)] +pub(crate) struct ClassifyOutput { + top_k: usize, + score_output_index: usize, + score_activation: ScoreActivation, + confidence_threshold: f32, + labels: Vec<String>, + label_index_offset: usize, +} + +impl Schedule for ClassifyOutput { + fn schedule<Ctx: GetProperty, L: Logger>( + context: &Ctx, + _logger: &L, + ) -> Result<Self, MinifiError> + where + Self: Sized, + { + let top_k = context.get_property(&TOP_K)?; + if top_k == 0 { + return Err(MinifiError::validation("Top K must be >= 1")); + } + let score_output_index = context.get_property(&SCORE_OUTPUT_INDEX)?; + let score_activation = context.get_property(&SCORE_ACTIVATION)?; + let confidence_threshold = context.get_property(&CONFIDENCE_THRESHOLD)?; + + let labels = match context.get_property(&LABELS_FILE_PATH)? { + Some(path) => load_labels(&path)?, + _ => Vec::new(), + }; + let label_index_offset = context.get_property(&LABEL_INDEX_OFFSET)?; + if !labels.is_empty() && label_index_offset >= labels.len() { + return Err(MinifiError::validation(format!( + "Label index offset ({}) must be smaller than the number of labels ({})", + label_index_offset, + labels.len() + ))); + } + + Ok(Self { + top_k, + score_output_index, + score_activation, + confidence_threshold, + labels, + label_index_offset, + }) + } +} + +impl ClassifyOutput { + fn label_for(&self, class_id: usize) -> Option<String> { + self.labels + .get(class_id.checked_add(self.label_index_offset)?) + .cloned() + } + + pub(crate) fn classify<'a, Context: GetProperty + GetAttribute + GetId, LoggerImpl: Logger>( + &self, + context: &Context, + logger: &LoggerImpl, + tensors: Vec<Tensor>, + ) -> Result<TransformedFlowFile<'a>, ProcessError> { + let score_floats = + tensor_as_f32(&tensors, self.score_output_index).route_err_to_failure()?; + if score_floats.is_empty() { + return Err(MinifiError::custom("Score tensor is empty; nothing to classify").into()); + } + + // A classifier head is a single score vector: shape [num_classes] or + // [1, .., num_classes]. We rank over the flattened class axis, so any + // leading axis > 1 (a real batch) would silently mix rows and yield + // class ids past num_classes. Reject it rather than produce garbage. + // (`ImageToTensor` emits batch=1 today; this just enforces the contract.) + let shape = tensor_shape(&tensors, self.score_output_index).route_err_to_failure()?; + if shape.iter().rev().skip(1).any(|&d| d != 1) { + return Err(MinifiError::custom(format!( + "ClassifyOutput expects a single score vector (shape [num_classes] or \ + [1, .., num_classes]); got {shape:?}. A batch dimension > 1 is not supported." + ))) + .route_err_to_failure(); + } + + let finite: Vec<(usize, f32)> = score_floats + .iter() + .copied() + .enumerate() + .filter(|&(_, s)| s.is_finite()) + .collect(); + + let softmax_terms = SoftmaxTerms::over(finite.iter().map(|&(_, s)| s)); + + let predictions: Vec<Prediction> = top_k(finite, self.top_k) + .into_iter() + .filter_map(|(class_id, raw)| { + let confidence = self.score_activation.confidence(raw, softmax_terms); + + if confidence >= self.confidence_threshold { + let class_name = self.label_for(class_id); + if class_name.is_none() && !self.labels.is_empty() { + warn!( + logger, + "No label for class id {} (offset {}, {} labels loaded); \ + the labels file does not match the model's classes", + class_id, + self.label_index_offset, + self.labels.len() + ); + } + Some(Prediction { + class_id, + confidence, + class_name, + }) + } else { + None + } + }) + .collect(); + + let (content, extra_attribute) = match context.get_property(&OUTPUT_ATTRIBUTE_NAME)? { + None => ( + Some(Content::Buffer( + serde_json::to_vec(&predictions).route_err_to_failure()?, + )), + None, + ), + Some(output_attr) => ( + None, + Some(( + output_attr, + serde_json::to_string(&predictions).route_err_to_failure()?, + )), + ), + }; + + let mut transformed = TransformedFlowFile::new(&SUCCESS, content) + .with_attribute("mime.type", "application/json") Review Comment: https://github.com/apache/nifi-minifi-cpp/pull/2258/changes/8446df5140037b345b2f7275444aeadcfb7d795a#diff-62fccab1592a7a96962a31921fe61d7751cc946ee62535444c8d7e834ea72d1bR101 -- 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]
