diff --git a/demo/config/params.yml b/demo/config/params.yml index 05e1926..25d2591 100644 --- a/demo/config/params.yml +++ b/demo/config/params.yml @@ -57,3 +57,21 @@ camera.camera.image_topic: "~/image" camera.camera.transport: "compressed" camera.camera.output_prefix: "~" + + diagnostic_updater: + period: 1.0 + # Prefix statuses with the fully qualified node name, including its namespace. + use_fqn: true + inputs: + timeout: 2.0 + min_age: -0.05 + max_age: 1.0 + processing: + # timeout defaults to max(5.0, 2 * prediction.triton_client_timeout_s). + warn_duration: 0.1 + # Per-camera rate checks are optional; zero (the default) disables them. + # camera: + # input: + # nominal_frequency: 20.0 + # min_frequency: 16.0 # Derived from the nominal rate unless overridden. + # max_frequency: 24.0 \ No newline at end of file diff --git a/deployment/compose/docker-compose.yml b/deployment/compose/docker-compose.yml index 59185ba..583d544 100644 --- a/deployment/compose/docker-compose.yml +++ b/deployment/compose/docker-compose.yml @@ -7,6 +7,7 @@ services: NAMESPACE: / NAME: image_instance_segmentation # --- other ----- + DIAGNOSTICS_TOPIC: /diagnostics IMAGE_TOPIC: ~/image CLASS_MASK_TOPIC: ~/segmentation/class_mask INSTANCE_MASK_TOPIC: ~/segmentation/instance_mask @@ -30,6 +31,7 @@ services: params:=$${PARAMS} \ ros_tracing:=$${ROS_TRACING} \ triton_server_url:=$${TRITON_SERVER_URL} \ + diagnostics_topic:=$${DIAGNOSTICS_TOPIC} \ image_topic:=$${IMAGE_TOPIC} \ class_mask_topic:=$${CLASS_MASK_TOPIC} \ instance_mask_topic:=$${INSTANCE_MASK_TOPIC} \ diff --git a/deployment/helm/values.yaml b/deployment/helm/values.yaml index a618d5b..d258313 100644 --- a/deployment/helm/values.yaml +++ b/deployment/helm/values.yaml @@ -6,6 +6,7 @@ openadservice: NAMESPACE: / NAME: image_instance_segmentation # --- other ----- + DIAGNOSTICS_TOPIC: /diagnostics IMAGE_TOPIC: ~/image CLASS_MASK_TOPIC: ~/segmentation/class_mask INSTANCE_MASK_TOPIC: ~/segmentation/instance_mask @@ -29,6 +30,7 @@ openadservice: params:=${PARAMS} \ ros_tracing:=${ROS_TRACING} \ triton_server_url:=${TRITON_SERVER_URL} \ + diagnostics_topic:=${DIAGNOSTICS_TOPIC} \ image_topic:=${IMAGE_TOPIC} \ class_mask_topic:=${CLASS_MASK_TOPIC} \ instance_mask_topic:=${INSTANCE_MASK_TOPIC} \ diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md new file mode 100644 index 0000000..ac72a98 --- /dev/null +++ b/docs/IMPLEMENTATION.md @@ -0,0 +1,142 @@ +# Configuration and diagnostics + +Configure the node with [params.yml](../image_instance_segmentation/config/params.yml). +The [node reference](../image_instance_segmentation/README.md) lists its interfaces +and launch arguments. + +## Cameras and outputs + +List camera names in `cameras` and configure each under `camera.`: + +| Parameter | Meaning | +| --- | --- | +| `camera..image_topic` | Base image topic | +| `camera..transport` | `raw` or `compressed`; omit `/compressed` from the base topic | +| `camera..output_prefix` | Prefix for segmentation and overlay outputs | + +The supplied parameter file configures one camera with raw transport, enables +tracking, and selects RF-DETR-Seg decoding. + +For the default camera, launch arguments remap the input and all output topics: + +```bash +ros2 launch image_instance_segmentation image_instance_segmentation.launch.py \ + image_topic:=/camera/image_rect detections_topic:=/perception/detections +``` + +For multiple cameras, set `cameras: [left, right]` and configure each +`camera.` entry. Their default inputs are `~//image` and outputs +are under `~//segmentation/`. + +Outputs preserve the input image dimensions, timestamp, and frame ID. +Subscriptions use sensor-data QoS. Class masks contain `model.class_ids`; +zero is background. Instance masks contain per-frame IDs or per-camera track IDs. +`Detection2D.id` contains the track ID when tracking is enabled. Track IDs can be +reused after a track ends. + +In the topic tables, `config.image_topic` is the configured input and `joinTopic` +places outputs under the camera's prefix. Parameter names `image_topic`, +`transport`, and `output_prefix` are per-camera suffixes. + +## Triton model + +Set `prediction.triton_server_url`, `prediction.model_name`, and +`prediction.model_version` for your model, and select its output decoding with +`model.architecture`. Tensor names (under `model.yolo` or `model.rfdetr`) and +FP32/FP16 precision are configurable. The input is always `[1, 3, H, W]` RGB +normalized to `[0, 1]`. + +| `model.architecture` | Resize | Outputs | +| --- | --- | --- | +| `yolo` (YOLOv8/v11) | Letterbox | Detections `cx, cy, w, h, class scores..., mask coefficients...` and mask prototypes | +| `yolo26` | Letterbox | Detections `x1, y1, x2, y2, confidence, class_id, mask coefficients...` and mask prototypes | +| `rfdetr` (RF-DETR-Seg) | Stretch | Boxes `[1, queries, 4]` (normalized `cx, cy, w, h`), class logits `[1, queries, classes(+1)]`, mask logits `[1, queries, h, w]` | + +YOLO detections are `[1, channels, anchors]` or `[1, anchors, channels]` and +prototypes `[1, mask_channels, mask_height, mask_width]`. RF-DETR yields one +detection per query and class above the confidence threshold. For models that +perform additional resizing and normalization inside the graph, set the node +input size to the model's exported input resolution. + +Output dimensions must stay fixed for the configured input size. The node +resolves dynamic tensor metadata with an inference request during startup. +`model.class_names` follows model-output class order; `model.class_ids` contains +the corresponding semantic mask IDs in `1..65535`. + +The `triton_server_url` launch argument sets the endpoint, defaults to +`triton-server:8001`, and takes precedence over the YAML value. +Shared memory (`prediction.use_shm`) requires a shared POSIX IPC namespace and +Triton client shared-memory access. + +## Tracking and throughput + +Tracking uses a separate ByteTrack tracker per camera, configured under +`tracking`. YOLOv8/v11 and RF-DETR detections use per-class NMS; YOLO26 uses +model selection. +Cameras run concurrently with one Triton client each. Busy cameras drop frames +at the admission limit. Set `prediction.max_in_flight_per_camera: 1` for low +latency; tracking enforces this limit to preserve frame order. + +Enable `debug.publish_overlay` for overlays and `debug.print_timing` for +processing times. +Use `ros_tracing:=true` to enable OpenADS dual-session tracing. Service images +include the `jazzy-ika` tracing fork. + +Postprocessing thresholds and `debug.*` settings support runtime changes through +`ros2 param set`. Model, camera, and tracker settings are read-only after startup. +`ros2 param describe` exposes parameter descriptions and declared ranges. + +## Diagnostics + +`/diagnostics` (`diagnostic_msgs/msg/DiagnosticArray`) is remapped with +`diagnostics_topic`. Reports contain one `: health` and optional +`: topic status` entries. `diagnostic_updater.use_fqn: true` +includes the namespace (for example `/perception/image_instance_segmentation: health`) +without renaming topics. Hardware ID is `none`. + +Health combines the same cycle's topic results and the checks below, with precedence +ERROR > STALE > WARN > OK. Check summaries appear alphabetically, followed by details. + +| Check | Assessment | Detail fields per camera | +| --- | --- | --- | +| `inputs` | ERROR for receive timeout or acquisition age outside bounds; STALE before the first image until timeout | `received_since_start`, `receive_age_s`, `acquisition_age_s` | +| `data_integrity` | ERROR for zero dimensions, empty data/frame ID, or invalid/zero timestamp; STALE before input | `invalid_metadata_since_start` | +| `processing` | ERROR for exceptions, non-finite candidates or stalled output; WARN for slow processing; STALE pending backend/first result | `backend_ready`, `completed_since_start`, `failed_since_start`, `dropped_busy_since_start`, `dropped_not_ready_since_start`, `in_flight`, `output_age_s`, `duration_s`, `peak_duration_since_report_s` | +| `initialization` | Present after an initialization failure: ERROR until recovery, then OK | `error` | +| `topic..` | Enabled topic helper's frequency and timestamp assessment | Frequency, event-window and timestamp statistics | + +Camera details use `..`, such as +`processing.front_center.duration_s`. Errors and duration peaks remain visible +through the next assessment and recover with valid frames. Empty detections are +valid; busy/unavailable-backend drops are counted separately from successful output. + +All settings below have the prefix `diagnostic_updater.` and are read-only. + +| Parameter suffix | Default | +| --- | --- | +| `period` | `1.0` s | +| `use_fqn` | `true` (required) | +| `inputs.timeout` | `2.0` s | +| `inputs.min_age` / `inputs.max_age` | `-0.05` / `1.0` s | +| `processing.timeout` | `max(5.0, 2 * prediction.triton_client_timeout_s)` s | +| `processing.warn_duration` | `0.1` s, input callback to publication | +| `..nominal_frequency` | `0.0` Hz, disabling that topic check | +| `..min_frequency` / `max_frequency` | `0.8` / `1.2` times nominal frequency | + +`` is `input`, `class_mask`, `instance_mask` or `detections`; overlays are +demand-driven. Rate checks use five reports and the ROS clock. Output timestamp +limits add `processing.timeout` to `inputs.max_age`. Topic details under +`topic..` are `frequency_hz`, `{min,max,target}_frequency_hz`, +`events_in_window`, `events_since_start`, `window_s`, `{min,max}_delay_s`, +`{min,max}_allowed_delay_s` and `{late,early,zero_stamp}_reports_since_start` +(counts of reports observing timestamp faults). + +Acquisition age uses ROS time (`use_sim_time` for bags); watchdogs use steady time. +Reports pause with `/clock` and assess elapsed time on resume. Backward time jumps +affect rate windows until they refill. Transport decoding failures appear as receive +timeouts. Backend readiness comes from initialization/inference responses, without +an independent probe. Device/time-sync state and mask-pixel validity are not assessed. +Application QoS is BEST_EFFORT/VOLATILE; RELIABLE subscribers do not match the outputs. + +The `karl-platform` group `/perception/image_instance_segmentation` retains stopped +nodes with a five-second timeout. Grouping is monitoring-only; reactions are separate. diff --git a/image_instance_segmentation/CMakeLists.txt b/image_instance_segmentation/CMakeLists.txt index 2eea524..9c139b7 100644 --- a/image_instance_segmentation/CMakeLists.txt +++ b/image_instance_segmentation/CMakeLists.txt @@ -7,6 +7,8 @@ endif() find_package(ament_cmake REQUIRED) find_package(OpenCV REQUIRED COMPONENTS core dnn imgproc video) +find_package(diagnostic_msgs REQUIRED) +find_package(diagnostic_updater REQUIRED) find_package(image_transport REQUIRED) find_package(rcl_interfaces REQUIRED) find_package(rclcpp REQUIRED) @@ -18,6 +20,7 @@ find_package(vision_msgs REQUIRED) add_library(${PROJECT_NAME}_lib SHARED src/ImageInstanceSegmentation.cpp + src/Diagnostics.cpp ) target_include_directories(${PROJECT_NAME}_lib PUBLIC @@ -28,6 +31,8 @@ target_include_directories(${PROJECT_NAME}_lib PUBLIC target_compile_features(${PROJECT_NAME}_lib PUBLIC cxx_std_17) ament_target_dependencies(${PROJECT_NAME}_lib + diagnostic_msgs + diagnostic_updater image_transport rcl_interfaces rclcpp diff --git a/image_instance_segmentation/README.md b/image_instance_segmentation/README.md index 121b4ae..2aed3af 100644 --- a/image_instance_segmentation/README.md +++ b/image_instance_segmentation/README.md @@ -2,93 +2,13 @@ Image instance segmentation inference node backed by Triton -Configure the node with the [parameter file](config/params.yml). - ## Nodes ### `image_instance_segmentation` -**Cameras and outputs** - -List camera names in `cameras` and configure each under `camera.`: - -| Parameter | Meaning | -| --- | --- | -| `camera..image_topic` | Base image topic | -| `camera..transport` | `raw` or `compressed`; omit `/compressed` from the base topic | -| `camera..output_prefix` | Prefix for segmentation and overlay outputs | - -The supplied parameter file configures one camera with raw transport, enables -tracking, and selects RF-DETR-Seg decoding. - -For the default camera, launch arguments remap the input and all output topics: - -```bash -ros2 launch image_instance_segmentation image_instance_segmentation.launch.py \ - image_topic:=/camera/image_rect detections_topic:=/perception/detections -``` - -For multiple cameras, set `cameras: [left, right]` and configure each -`camera.` entry. Their default inputs are `~//image` and outputs -are under `~//segmentation/`. - -Outputs preserve the input image dimensions, timestamp, and frame ID. -Subscriptions use sensor-data QoS. Class masks contain `model.class_ids`; -zero is background. Instance masks contain per-frame IDs or per-camera track IDs. -`Detection2D.id` contains the track ID when tracking is enabled. Track IDs can be -reused after a track ends. - -In the topic tables, `config.image_topic` is the configured input and `joinTopic` -places outputs under the camera's prefix. Parameter names `image_topic`, -`transport`, and `output_prefix` are per-camera suffixes. - -**Triton model** - -Set `prediction.triton_server_url`, `prediction.model_name`, and -`prediction.model_version` for your model, and select its output decoding with -`model.architecture`. Tensor names (under `model.yolo` or `model.rfdetr`) and -FP32/FP16 precision are configurable. The input is always `[1, 3, H, W]` RGB -normalized to `[0, 1]`. - -| `model.architecture` | Resize | Outputs | -| --- | --- | --- | -| `yolo` (YOLOv8/v11) | Letterbox | Detections `cx, cy, w, h, class scores..., mask coefficients...` and mask prototypes | -| `yolo26` | Letterbox | Detections `x1, y1, x2, y2, confidence, class_id, mask coefficients...` and mask prototypes | -| `rfdetr` (RF-DETR-Seg) | Stretch | Boxes `[1, queries, 4]` (normalized `cx, cy, w, h`), class logits `[1, queries, classes(+1)]`, mask logits `[1, queries, h, w]` | - -YOLO detections are `[1, channels, anchors]` or `[1, anchors, channels]` and -prototypes `[1, mask_channels, mask_height, mask_width]`. RF-DETR yields one -detection per query and class above the confidence threshold. For models that -perform additional resizing and normalization inside the graph, set the node -input size to the model's exported input resolution. - -Output dimensions must stay fixed for the configured input size. The node -resolves dynamic tensor metadata with an inference request during startup. -`model.class_names` follows model-output class order; `model.class_ids` contains -the corresponding semantic mask IDs in `1..65535`. - -The `triton_server_url` launch argument sets the endpoint, defaults to -`triton-server:8001`, and takes precedence over the YAML value. -Shared memory (`prediction.use_shm`) requires a shared POSIX IPC namespace and -Triton client shared-memory access. - -**Tracking and throughput** - -Tracking uses a separate ByteTrack tracker per camera, configured under -`tracking`. YOLOv8/v11 and RF-DETR detections use per-class NMS; YOLO26 uses -model selection. -Cameras run concurrently with one Triton client each. Busy cameras drop frames -at the admission limit. Set `prediction.max_in_flight_per_camera: 1` for low -latency; tracking enforces this limit to preserve frame order. - -Enable `debug.publish_overlay` for overlays and `debug.print_timing` for -processing times. -Use `ros_tracing:=true` to enable OpenADS dual-session tracing. Service images -include the `jazzy-ika` tracing fork. +Image instance segmentation inference node backed by Triton -Postprocessing thresholds and `debug.*` settings support runtime changes through -`ros2 param set`. Model, camera, and tracker settings are read-only after startup. -Numeric parameters expose valid ranges through `ros2 param describe`. +See [configuration and diagnostics](../docs/IMPLEMENTATION.md). ```mermaid flowchart LR @@ -167,6 +87,7 @@ flowchart LR | Argument | Default | Description | | --- | --- | --- | +| `diagnostics_topic` | `"/diagnostics"` | diagnostics topic remap | | `image_topic` | `"~/image"` | input image topic remap | | `class_mask_topic` | `"~/segmentation/class_mask"` | semantic mask topic remap | | `instance_mask_topic` | `"~/segmentation/instance_mask"` | instance mask topic remap | diff --git a/image_instance_segmentation/config/params.yml b/image_instance_segmentation/config/params.yml index 07b6796..845167e 100644 --- a/image_instance_segmentation/config/params.yml +++ b/image_instance_segmentation/config/params.yml @@ -57,3 +57,22 @@ camera.camera.image_topic: "~/image" camera.camera.transport: "raw" camera.camera.output_prefix: "~" + + # diagnostic_updater: + # period: 1.0 + # # Prefix statuses with the fully qualified node name, including its namespace. + # # Example: /perception/image_instance_segmentation: health. This does not rename topics. + # use_fqn: true + # inputs: + # timeout: 2.0 + # min_age: -0.05 + # max_age: 1.0 + # processing: + # # timeout defaults to max(5.0, 2 * prediction.triton_client_timeout_s). + # warn_duration: 0.1 + # # Per-camera rate checks are optional; zero (the default) disables them. + # # camera: + # # input: + # # nominal_frequency: 20.0 + # # min_frequency: 16.0 # Derived from the nominal rate unless overridden. + # # max_frequency: 24.0 \ No newline at end of file diff --git a/image_instance_segmentation/include/image_instance_segmentation/ImageInstanceSegmentation.hpp b/image_instance_segmentation/include/image_instance_segmentation/ImageInstanceSegmentation.hpp index 3310fd6..b1d6da6 100644 --- a/image_instance_segmentation/include/image_instance_segmentation/ImageInstanceSegmentation.hpp +++ b/image_instance_segmentation/include/image_instance_segmentation/ImageInstanceSegmentation.hpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include #include #include @@ -100,6 +102,49 @@ class ImageInstanceSegmentation : public rclcpp::Node { ~ImageInstanceSegmentation() override; private: + struct TopicHealth { + double nominal_frequency = 0.0; + double min_frequency = 0.0; + double max_frequency = 0.0; + diagnostic_updater::DiagnosticStatusWrapper result; + std::unique_ptr task; + }; + + struct CameraHealthSnapshot { + std::chrono::steady_clock::time_point first_receive{}; + std::chrono::steady_clock::time_point last_receive{}; + std::chrono::steady_clock::time_point last_success{}; + rclcpp::Time input_stamp{0, 0, RCL_ROS_TIME}; + std::uint64_t received = 0; + std::uint64_t dropped = 0; + std::uint64_t dropped_not_ready = 0; + std::uint64_t completed = 0; + std::uint64_t failed = 0; + std::uint64_t invalid = 0; + bool backend_ready = false; + bool initialization_failed = false; + bool input_valid = true; + bool invalid_in_cycle = false; + bool processing_failed = false; + bool failure_in_cycle = false; + double duration_s = 0.0; + double peak_duration_s = 0.0; + std::string initialization_error; + std::string processing_error; + }; + + struct CameraHealth : CameraHealthSnapshot { + std::mutex mutex; + std::map topics; + }; + + /** @brief Configure topic tasks and the single overall health assessment. */ + void setupDiagnostics(); + /** @brief Summarize topic results and camera/backend snapshots once per cycle. */ + void health(diagnostic_updater::DiagnosticStatusWrapper& status); + /** @brief Record a failed frame without publishing diagnostics from a worker. */ + void recordProcessingFailure(const std::string& camera_name, const std::string& message); + struct CameraRuntime { CameraConfig config; image_transport::Subscriber image_subscriber; @@ -113,7 +158,9 @@ class ImageInstanceSegmentation : public rclcpp::Node { std::atomic in_flight{0}; /** @brief Create empty runtime state with no in-flight frames. */ - CameraRuntime() = default; + CameraRuntime(); + /** @brief Release the tracker in the implementation that defines it. */ + ~CameraRuntime(); /** @brief Prevent copying subscriptions, tracker ownership, and admission * counters. */ CameraRuntime(const CameraRuntime&) = delete; @@ -122,34 +169,9 @@ class ImageInstanceSegmentation : public rclcpp::Node { /** @brief Transfer camera resources and snapshot the atomic in-flight * count. */ - CameraRuntime(CameraRuntime&& other) noexcept - : config(std::move(other.config)), - image_subscriber(std::move(other.image_subscriber)), - class_mask_publisher(std::move(other.class_mask_publisher)), - instance_mask_publisher(std::move(other.instance_mask_publisher)), - detections_publisher(std::move(other.detections_publisher)), - class_overlay_publisher(std::move(other.class_overlay_publisher)), - instance_overlay_publisher(std::move(other.instance_overlay_publisher)), - callback_group(std::move(other.callback_group)), - tracker(std::move(other.tracker)), - in_flight(other.in_flight.load()) {} - + CameraRuntime(CameraRuntime&& other) noexcept; /** @brief Move camera resources and copy the atomic in-flight count. */ - CameraRuntime& operator=(CameraRuntime&& other) noexcept { - if (this != &other) { - config = std::move(other.config); - image_subscriber = std::move(other.image_subscriber); - class_mask_publisher = std::move(other.class_mask_publisher); - instance_mask_publisher = std::move(other.instance_mask_publisher); - detections_publisher = std::move(other.detections_publisher); - class_overlay_publisher = std::move(other.class_overlay_publisher); - instance_overlay_publisher = std::move(other.instance_overlay_publisher); - callback_group = std::move(other.callback_group); - tracker = std::move(other.tracker); - in_flight.store(other.in_flight.load()); - } - return *this; - } + CameraRuntime& operator=(CameraRuntime&& other) noexcept; }; /** @brief Declare a parameter with its current default and load any @@ -186,8 +208,7 @@ class ImageInstanceSegmentation : public rclcpp::Node { /** @brief Reject invalid dimensions, class mappings, thresholds, and camera * settings. */ void validateParameters() const; - /** @brief Create the reusable Triton client and inference buffers for each - * camera. */ + /** @brief Allocate stable per-camera state before starting model workers. */ void initializeModel(); /** @brief Initialize one camera client, resolving tensor shapes before * allocating buffers. */ @@ -219,20 +240,23 @@ class ImageInstanceSegmentation : public rclcpp::Node { int image_width, int image_height, const LetterboxInfo& letterbox, - double score_threshold); + double score_threshold, + bool& invalid_result); /** @brief Decode validated YOLO tensor layouts into original-image boxes and * mask coefficients. */ std::vector decodeYoloDetections(triton_cpp::TritonInterface& triton_interface, int image_width, int image_height, const LetterboxInfo& letterbox, - double score_threshold); + double score_threshold, + bool& invalid_result); /** @brief Decode RF-DETR boxes and per-class logits into one detection per * query and class above the threshold. */ std::vector decodeRfDetrDetections(triton_cpp::TritonInterface& triton_interface, int image_width, int image_height, - double score_threshold); + double score_threshold, + bool& invalid_result); /** @brief Keep confidence-ordered detections using class-specific IoU * suppression. */ std::vector applyNms(std::vector detections) const; @@ -279,6 +303,16 @@ class ImageInstanceSegmentation : public rclcpp::Node { * separator. */ static std::string joinTopic(const std::string& prefix, const std::string& suffix); + std::map camera_health_; + std::chrono::steady_clock::time_point diagnostics_started_at_ = std::chrono::steady_clock::now(); + double diagnostic_period_s_ = 1.0; + bool diagnostic_use_fqn_ = true; + double input_timeout_s_ = 2.0; + double input_max_age_s_ = 1.0; + double input_min_age_s_ = -0.05; + double processing_timeout_s_ = 5.0; + double processing_warn_duration_s_ = 0.1; + std::string server_url_ = "triton-server:8001"; std::string model_name_ = "rfdetr-seg-small"; std::string model_version_ = "1"; @@ -333,12 +367,12 @@ class ImageInstanceSegmentation : public rclcpp::Node { rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr parameters_callback_handle_; rclcpp::node_interfaces::PostSetParametersCallbackHandle::SharedPtr parameters_post_callback_handle_; - // Declared last so it is destroyed first: its destructor joins all worker - // threads before the members above (cameras_, triton_interfaces_, ...) that - // in-flight tasks reference are torn down. + // Workers are joined before camera state and Triton clients are released. std::mutex admission_mutex_; std::atomic stopping_{false}; std::unique_ptr thread_pool_; + // Destroy the updater timer before the tasks and snapshots it references. + std::unique_ptr diagnostic_updater_; }; } // namespace image_instance_segmentation diff --git a/image_instance_segmentation/launch/image_instance_segmentation.launch.py b/image_instance_segmentation/launch/image_instance_segmentation.launch.py index 106647f..dc81431 100644 --- a/image_instance_segmentation/launch/image_instance_segmentation.launch.py +++ b/image_instance_segmentation/launch/image_instance_segmentation.launch.py @@ -17,6 +17,7 @@ def generate_launch_description(): """Generate the image instance segmentation launch description.""" remappable_topics = [ + DeclareLaunchArgument("diagnostics_topic", default_value="/diagnostics", description="diagnostics topic remap"), DeclareLaunchArgument("image_topic", default_value="~/image", description="input image topic remap"), DeclareLaunchArgument( "class_mask_topic", default_value="~/segmentation/class_mask", description="semantic mask topic remap" diff --git a/image_instance_segmentation/package.xml b/image_instance_segmentation/package.xml index 2eea543..05fe1de 100644 --- a/image_instance_segmentation/package.xml +++ b/image_instance_segmentation/package.xml @@ -13,6 +13,8 @@ ament_cmake + diagnostic_msgs + diagnostic_updater image_transport libopencv-dev rcl_interfaces diff --git a/image_instance_segmentation/src/Diagnostics.cpp b/image_instance_segmentation/src/Diagnostics.cpp new file mode 100644 index 0000000..41f0e98 --- /dev/null +++ b/image_instance_segmentation/src/Diagnostics.cpp @@ -0,0 +1,243 @@ +// Copyright Institute for Automotive Engineering (ika), RWTH Aachen University +// SPDX-License-Identifier: Apache-2.0 + +#include "image_instance_segmentation/ImageInstanceSegmentation.hpp" + +#include +#include +#include + +namespace image_instance_segmentation { +namespace { +using Status = diagnostic_msgs::msg::DiagnosticStatus; +using Wrapper = diagnostic_updater::DiagnosticStatusWrapper; + +/** @brief Capture each topic task's actual result without evaluating it twice. */ +class CapturedTopic : public diagnostic_updater::TopicDiagnostic { + public: + CapturedTopic(const std::string& topic, + diagnostic_updater::Updater& updater, + double& minimum, + double& maximum, + double min_age, + double max_age, + const rclcpp::Clock::SharedPtr& clock, + Wrapper& result) + : TopicDiagnostic(topic, + updater, + diagnostic_updater::FrequencyStatusParam(&minimum, &maximum, 0.0, 5), + diagnostic_updater::TimeStampStatusParam(min_age, max_age), + clock), + result_(result) {} + + /** @brief Evaluate and cache this cycle's topic assessment. */ + void run(Wrapper& status) override { + TopicDiagnostic::run(status); + result_ = status; + } + + private: + Wrapper& result_; +}; + +/** @brief Rank known failures above unavailable assessments. */ +int severity(unsigned char level) { + switch (level) { + case Status::ERROR: + return 3; + case Status::STALE: + return 2; + case Status::WARN: + return 1; + default: + return 0; + } +} + +/** @brief Render ROS diagnostic levels in check summary values. */ +const char* levelName(unsigned char level) { + switch (level) { + case Status::ERROR: + return "ERROR"; + case Status::STALE: + return "STALE"; + case Status::WARN: + return "WARN"; + default: + return "OK"; + } +} +} // namespace + +void ImageInstanceSegmentation::setupDiagnostics() { + declareAndLoadParameter("diagnostic_updater.use_fqn", diagnostic_use_fqn_, + "Prefix diagnostic status names with the fully qualified node name"); + declareAndLoadParameter("diagnostic_updater.period", diagnostic_period_s_, "Diagnostic reporting period in seconds"); + declareAndLoadParameter("diagnostic_updater.inputs.timeout", input_timeout_s_, + "Required camera receive timeout in steady seconds"); + declareAndLoadParameter("diagnostic_updater.inputs.max_age", input_max_age_s_, "Maximum input acquisition age in ROS seconds"); + declareAndLoadParameter("diagnostic_updater.inputs.min_age", input_min_age_s_, "Minimum ROS now minus image stamp in seconds"); + processing_timeout_s_ = std::max(5.0, 2.0 * triton_client_timeout_s_); + declareAndLoadParameter("diagnostic_updater.processing.timeout", processing_timeout_s_, + "Maximum time without successful processing in steady seconds"); + declareAndLoadParameter("diagnostic_updater.processing.warn_duration", processing_warn_duration_s_, + "Input callback to output duration warning threshold in seconds"); + for (const auto value : + {diagnostic_period_s_, input_timeout_s_, input_max_age_s_, processing_timeout_s_, processing_warn_duration_s_}) { + if (!std::isfinite(value) || value <= 0.0) + throw std::invalid_argument("Diagnostic periods and timeouts must be finite and positive"); + } + if (!diagnostic_use_fqn_) throw std::invalid_argument("diagnostic_updater.use_fqn must be true"); + if (!std::isfinite(input_min_age_s_) || input_min_age_s_ > input_max_age_s_) { + throw std::invalid_argument("Diagnostic input timestamp bounds must be finite and ordered"); + } + if (processing_warn_duration_s_ > processing_timeout_s_) { + throw std::invalid_argument("Diagnostic processing warn_duration must not exceed timeout"); + } + if (diagnostic_period_s_ < 0.001) throw std::invalid_argument("Diagnostic reporting period must be at least 0.001 seconds"); + diagnostic_updater_ = std::make_unique(this, diagnostic_period_s_, Status::STALE); + diagnostic_updater_->setHardwareID("none"); + for (auto& [name, state] : camera_health_) { + const auto& camera = cameras_.at(name); + const std::map topics{{"input", camera.image_subscriber.getTopic()}, + {"class_mask", camera.class_mask_publisher->get_topic_name()}, + {"instance_mask", camera.instance_mask_publisher->get_topic_name()}, + {"detections", camera.detections_publisher->get_topic_name()}}; + for (const auto& [key, topic] : topics) { + auto& cfg = state.topics[key]; + const std::string prefix = "diagnostic_updater." + name + "." + key + "."; + declareAndLoadParameter(prefix + "nominal_frequency", cfg.nominal_frequency, + "Expected topic frequency in Hz; zero disables the periodic topic task"); + cfg.min_frequency = 0.8 * cfg.nominal_frequency; + cfg.max_frequency = 1.2 * cfg.nominal_frequency; + declareAndLoadParameter(prefix + "min_frequency", cfg.min_frequency, "Minimum topic frequency in Hz"); + declareAndLoadParameter(prefix + "max_frequency", cfg.max_frequency, "Maximum topic frequency in Hz"); + if (!std::isfinite(cfg.nominal_frequency) || !std::isfinite(cfg.min_frequency) || !std::isfinite(cfg.max_frequency) || + cfg.nominal_frequency < 0.0 || cfg.min_frequency < 0.0 || cfg.max_frequency < cfg.min_frequency || + (cfg.nominal_frequency > 0.0 && cfg.min_frequency <= 0.0) || + (cfg.nominal_frequency == 0.0 && (cfg.min_frequency != 0.0 || cfg.max_frequency != 0.0))) { + throw std::invalid_argument("Invalid frequency bounds for " + prefix); + } + if (cfg.nominal_frequency > 0.0) { + cfg.task = std::make_unique( + topic, *diagnostic_updater_, cfg.min_frequency, cfg.max_frequency, input_min_age_s_, + input_max_age_s_ + (key == "input" ? 0.0 : processing_timeout_s_), get_clock(), cfg.result); + } + } + } + diagnostic_updater_->add("health", this, &ImageInstanceSegmentation::health); +} + +void ImageInstanceSegmentation::recordProcessingFailure(const std::string& camera_name, const std::string& message) { + auto& state = camera_health_.at(camera_name); + std::lock_guard lock(state.mutex); + ++state.failed; + state.processing_failed = true; + state.failure_in_cycle = true; + state.processing_error = message; +} + +void ImageInstanceSegmentation::health(Wrapper& status) { + struct Check { + unsigned char level = Status::OK; + std::string message = "All checks OK"; + }; + std::map checks{{"inputs", {}}, {"processing", {}}, {"data_integrity", {}}}; + Wrapper details; + const auto steady_now = std::chrono::steady_clock::now(); + const auto ros_now = now(); + const auto assess = [&](const std::string& key, unsigned char level, const std::string& message) { + auto& check = checks[key]; + if (severity(level) > severity(check.level)) check = {level, message}; + }; + for (auto& [name, state] : camera_health_) { + CameraHealthSnapshot snapshot; + { + std::lock_guard lock(state.mutex); + snapshot = state; + state.failure_in_cycle = false; + state.invalid_in_cycle = false; + state.peak_duration_s = 0.0; + } + const double receive_age = + std::chrono::duration(steady_now - (snapshot.received ? snapshot.last_receive : diagnostics_started_at_)).count(); + const double output_age = + std::chrono::duration(steady_now - (snapshot.completed + ? snapshot.last_success + : (snapshot.received ? snapshot.first_receive : diagnostics_started_at_))) + .count(); + const double input_age = snapshot.received ? (ros_now - snapshot.input_stamp).seconds() : 0.0; + if (receive_age > input_timeout_s_) { + assess("inputs", Status::ERROR, name + ": required image receive timeout"); + } else if (!snapshot.received) { + assess("inputs", Status::STALE, name + ": awaiting first image"); + } else if (input_age < input_min_age_s_ || input_age > input_max_age_s_) { + assess("inputs", Status::ERROR, name + ": image acquisition timestamp outside bounds"); + } + if (!snapshot.received) assess("data_integrity", Status::STALE, name + ": awaiting first image"); + if (!snapshot.input_valid || snapshot.invalid_in_cycle) + assess("data_integrity", Status::ERROR, name + ": invalid image dimensions, data, frame or timestamp"); + if (snapshot.failure_in_cycle || snapshot.processing_failed) { + assess("processing", Status::ERROR, name + ": " + snapshot.processing_error); + } else if (!snapshot.backend_ready) { + assess("processing", Status::STALE, name + ": awaiting Triton initialization"); + } else if (snapshot.received && output_age > processing_timeout_s_) { + assess("processing", Status::ERROR, name + ": no successful result within processing timeout"); + } else if (!snapshot.completed) { + assess("processing", Status::STALE, name + ": awaiting first result"); + } else if (std::max(snapshot.duration_s, snapshot.peak_duration_s) > processing_warn_duration_s_) { + assess("processing", Status::WARN, name + ": processing duration above warning threshold"); + } + if (snapshot.initialization_failed) { + assess("initialization", snapshot.initialization_error.empty() ? Status::OK : Status::ERROR, + name + ": " + snapshot.initialization_error); + details.add("initialization." + name + ".error", snapshot.initialization_error); + } + details.add("inputs." + name + ".received_since_start", snapshot.received); + details.add("inputs." + name + ".receive_age_s", receive_age); + if (snapshot.received) details.add("inputs." + name + ".acquisition_age_s", input_age); + details.add("data_integrity." + name + ".invalid_metadata_since_start", snapshot.invalid); + details.add("processing." + name + ".backend_ready", snapshot.backend_ready); + details.add("processing." + name + ".completed_since_start", snapshot.completed); + details.add("processing." + name + ".failed_since_start", snapshot.failed); + details.add("processing." + name + ".dropped_busy_since_start", snapshot.dropped); + details.add("processing." + name + ".dropped_not_ready_since_start", snapshot.dropped_not_ready); + details.add("processing." + name + ".in_flight", cameras_.at(name).in_flight.load()); + details.add("processing." + name + ".output_age_s", output_age); + details.add("processing." + name + ".duration_s", snapshot.duration_s); + details.add("processing." + name + ".peak_duration_since_report_s", snapshot.peak_duration_s); + for (const auto& [key, topic] : state.topics) { + if (!topic.task) continue; + const std::string check = "topic." + name + "." + key; + checks[check] = {topic.result.level, + topic.result.message.empty() ? "Frequency and timestamps within bounds" : topic.result.message}; + static const std::map fields{ + {"Events in window", "events_in_window"}, + {"Events since startup", "events_since_start"}, + {"Duration of window (s)", "window_s"}, + {"Actual frequency (Hz)", "frequency_hz"}, + {"Target frequency (Hz)", "target_frequency_hz"}, + {"Minimum acceptable frequency (Hz)", "min_frequency_hz"}, + {"Maximum acceptable frequency (Hz)", "max_frequency_hz"}, + {"Earliest timestamp delay:", "min_delay_s"}, + {"Latest timestamp delay:", "max_delay_s"}, + {"Earliest acceptable timestamp delay:", "min_allowed_delay_s"}, + {"Latest acceptable timestamp delay:", "max_allowed_delay_s"}, + {"Late diagnostic update count:", "late_reports_since_start"}, + {"Early diagnostic update count:", "early_reports_since_start"}, + {"Zero seen diagnostic update count:", "zero_stamp_reports_since_start"}}; + for (const auto& value : topic.result.values) { + const auto field = fields.find(value.key); + if (field != fields.end()) details.add(check + "." + field->second, value.value); + } + } + } + Check worst; + for (const auto& [key, check] : checks) { + status.add(key, std::string(levelName(check.level)) + ": " + check.message); + if (severity(check.level) > severity(worst.level)) worst = {check.level, key + ": " + check.message}; + } + status.summary(worst.level, worst.message); + status.values.insert(status.values.end(), details.values.begin(), details.values.end()); +} +} // namespace image_instance_segmentation diff --git a/image_instance_segmentation/src/ImageInstanceSegmentation.cpp b/image_instance_segmentation/src/ImageInstanceSegmentation.cpp index f23712e..f9175ea 100644 --- a/image_instance_segmentation/src/ImageInstanceSegmentation.cpp +++ b/image_instance_segmentation/src/ImageInstanceSegmentation.cpp @@ -44,6 +44,37 @@ class ITracker { virtual void reset() = 0; }; +ImageInstanceSegmentation::CameraRuntime::CameraRuntime() = default; +ImageInstanceSegmentation::CameraRuntime::~CameraRuntime() = default; + +ImageInstanceSegmentation::CameraRuntime::CameraRuntime(CameraRuntime&& other) noexcept + : config(std::move(other.config)), + image_subscriber(std::move(other.image_subscriber)), + class_mask_publisher(std::move(other.class_mask_publisher)), + instance_mask_publisher(std::move(other.instance_mask_publisher)), + detections_publisher(std::move(other.detections_publisher)), + class_overlay_publisher(std::move(other.class_overlay_publisher)), + instance_overlay_publisher(std::move(other.instance_overlay_publisher)), + callback_group(std::move(other.callback_group)), + tracker(std::move(other.tracker)), + in_flight(other.in_flight.load()) {} + +ImageInstanceSegmentation::CameraRuntime& ImageInstanceSegmentation::CameraRuntime::operator=(CameraRuntime&& other) noexcept { + if (this != &other) { + config = std::move(other.config); + image_subscriber = std::move(other.image_subscriber); + class_mask_publisher = std::move(other.class_mask_publisher); + instance_mask_publisher = std::move(other.instance_mask_publisher); + detections_publisher = std::move(other.detections_publisher); + class_overlay_publisher = std::move(other.class_overlay_publisher); + instance_overlay_publisher = std::move(other.instance_overlay_publisher); + callback_group = std::move(other.callback_group); + tracker = std::move(other.tracker); + in_flight.store(other.in_flight.load()); + } + return *this; +} + // Fixed-size pool of persistent worker threads. Replaces spawning a new // std::thread per frame, which under sustained camera frame rates repeatedly // pays thread create/teardown cost for no benefit. Each camera has its own @@ -726,12 +757,22 @@ ImageInstanceSegmentation::ImageInstanceSegmentation(const rclcpp::NodeOptions& validateParameters(); initializeModel(); setupCameras(); + setupDiagnostics(); parameters_callback_handle_ = add_on_set_parameters_callback( [this](const std::vector& parameters) { return parametersCallback(parameters); }); parameters_post_callback_handle_ = add_post_set_parameters_callback([this](const std::vector& parameters) { applyParameters(parameters); }); const std::size_t worker_count = static_cast(std::max(1, max_in_flight_per_camera_)) * camera_configs_.size(); thread_pool_ = std::make_unique(worker_count); + for (const auto& config : camera_configs_) { + thread_pool_->enqueue([this, name = config.name] { + try { + initializeModelForCamera(name); + } catch (const std::exception& error) { + if (!stopping_.load()) recordProcessingFailure(name, error.what()); + } + }); + } } ImageInstanceSegmentation::~ImageInstanceSegmentation() { @@ -745,6 +786,7 @@ ImageInstanceSegmentation::~ImageInstanceSegmentation() { for (auto& entry : cameras_) { entry.second.image_subscriber.shutdown(); } + diagnostic_updater_.reset(); thread_pool_.reset(); } @@ -790,6 +832,28 @@ void ImageInstanceSegmentation::declareAndLoadParameter(const std::string& name, } } +// Parameter types used by the diagnostics translation unit. +template void ImageInstanceSegmentation::declareAndLoadParameter(const std::string&, + bool&, + const std::string&, + bool, + bool, + bool, + const std::optional&, + const std::optional&, + const std::optional&, + const std::string&); +template void ImageInstanceSegmentation::declareAndLoadParameter(const std::string&, + double&, + const std::string&, + bool, + bool, + bool, + const std::optional&, + const std::optional&, + const std::optional&, + const std::string&); + rcl_interfaces::msg::SetParametersResult ImageInstanceSegmentation::parametersCallback( const std::vector& parameters) const { rcl_interfaces::msg::SetParametersResult result; @@ -994,21 +1058,24 @@ void ImageInstanceSegmentation::validateParameters() const { } void ImageInstanceSegmentation::initializeModel() { - // Pre-populate both maps for every configured camera up front, while still + // Pre-populate camera state and client maps before workers start, while still // single-threaded, so that later per-camera lookups (from worker threads) // only ever call .at() on existing keys and never trigger a concurrent // insertion/rehash. for (const auto& config : camera_configs_) { + camera_health_.try_emplace(config.name); model_mutexes_.try_emplace(config.name); triton_interfaces_.try_emplace(config.name, nullptr); } - for (const auto& config : camera_configs_) { - initializeModelForCamera(config.name); - } } void ImageInstanceSegmentation::initializeModelForCamera(const std::string& camera_name) { std::lock_guard lock(model_mutexes_.at(camera_name)); + auto& state = camera_health_.at(camera_name); + { + std::lock_guard state_lock(state.mutex); + state.backend_ready = false; + } constexpr auto kRetryDelay = std::chrono::seconds(1); while (!stopping_.load() && rclcpp::ok(get_node_base_interface()->get_context())) { try { @@ -1028,6 +1095,11 @@ void ImageInstanceSegmentation::initializeModelForCamera(const std::string& came interface->initInOutputs(output_shape_overrides, std::map>{ {input_tensor_name_, {1, 3, input_height_, input_width_}}}); triton_interfaces_.at(camera_name) = std::move(interface); + { + std::lock_guard state_lock(state.mutex); + state.backend_ready = true; + state.initialization_error.clear(); + } RCLCPP_INFO(get_logger(), "Camera '%s': connected to Triton model '%s:%s' at '%s' " "using input dtype '%s' and output dtype '%s'", @@ -1035,11 +1107,21 @@ void ImageInstanceSegmentation::initializeModelForCamera(const std::string& came tensorDataTypeName(input_tensor_data_type_).c_str(), tensorDataTypeName(output_tensor_data_type_).c_str()); return; } catch (const std::exception& e) { + { + std::lock_guard state_lock(state.mutex); + state.initialization_failed = true; + state.initialization_error = e.what(); + } RCLCPP_WARN(get_logger(), "Camera '%s': failed to initialize Triton model '%s:%s' at " "'%s': %s. Retrying in 1s.", camera_name.c_str(), model_name_.c_str(), model_version_.c_str(), server_url_.c_str(), e.what()); - rclcpp::sleep_for(kRetryDelay); + // Component unloading also interrupts retries while the ROS context stays alive. + const auto retry_at = std::chrono::steady_clock::now() + kRetryDelay; + while (!stopping_.load() && std::chrono::steady_clock::now() < retry_at && + rclcpp::ok(get_node_base_interface()->get_context())) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } } } throw std::runtime_error("Shutdown requested while waiting for Triton connection"); @@ -1197,12 +1279,38 @@ std::map> ImageInstanceSegmentation::probeOutp void ImageInstanceSegmentation::imageCallback(const sensor_msgs::msg::Image::ConstSharedPtr& msg, const std::string& camera_name) { const auto input_received_at = std::chrono::steady_clock::now(); + auto& state = camera_health_.at(camera_name); + bool backend_ready = false; + const bool valid_stamp = msg->header.stamp.sec >= 0 && msg->header.stamp.nanosec < 1000000000u; + { + std::lock_guard state_lock(state.mutex); + backend_ready = state.backend_ready; + if (!backend_ready) ++state.dropped_not_ready; + if (state.received == 0) state.first_receive = input_received_at; + state.last_receive = input_received_at; + state.input_stamp = valid_stamp ? rclcpp::Time(msg->header.stamp, get_clock()->get_clock_type()) + : rclcpp::Time(0, 0, get_clock()->get_clock_type()); + ++state.received; + state.input_valid = msg->width > 0 && msg->height > 0 && !msg->data.empty() && !msg->header.frame_id.empty() && valid_stamp && + state.input_stamp.nanoseconds() > 0; + if (!state.input_valid) { + ++state.invalid; + state.invalid_in_cycle = true; + } + } + if (auto& task = state.topics.at("input").task; task && valid_stamp) task->tick(msg->header.stamp); + // Receive health includes all frames, but initialization must not queue stale images. + if (!backend_ready) return; std::lock_guard admission_lock(admission_mutex_); auto& runtime = cameras_.at(camera_name); if (stopping_.load()) return; int in_flight = runtime.in_flight.load(); do { - if (in_flight >= max_in_flight_per_camera_) return; + if (in_flight >= max_in_flight_per_camera_) { + std::lock_guard state_lock(state.mutex); + ++state.dropped; + return; + } } while (!runtime.in_flight.compare_exchange_weak(in_flight, in_flight + 1)); try { @@ -1216,6 +1324,7 @@ void ImageInstanceSegmentation::imageCallback(const sensor_msgs::msg::Image::Con // msg owns the storage behind raw BGR views throughout processing. processImage(msg->header, rawImageToBgr(*msg), camera_name, input_received_at); } catch (const std::exception& error) { + recordProcessingFailure(camera_name, error.what()); RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000, "Camera '%s': processing failed: %s", camera_name.c_str(), error.what()); } @@ -1250,6 +1359,7 @@ void ImageInstanceSegmentation::processImage(const std_msgs::msg::Header& header inference_started_at = std::chrono::steady_clock::now(); interface.infer(); } catch (const std::exception& error) { + recordProcessingFailure(camera_name, error.what()); lock.unlock(); RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000, "Camera '%s': Triton request failed: %s. Reinitializing.", camera_name.c_str(), error.what()); @@ -1260,11 +1370,29 @@ void ImageInstanceSegmentation::processImage(const std_msgs::msg::Header& header std::shared_lock parameters_lock(runtime_parameters_mutex_); const double score_threshold = tracker_config_.enabled ? std::min(confidence_threshold_, tracker_config_.low_confidence_threshold) : confidence_threshold_; - auto detections = decodeDetections(interface, bgr_image.cols, bgr_image.rows, letterbox, score_threshold); + bool invalid_result = false; + auto detections = decodeDetections(interface, bgr_image.cols, bgr_image.rows, letterbox, score_threshold, invalid_result); + if (invalid_result) recordProcessingFailure(camera_name, "Non-finite detection candidates in model output"); if (camera.tracker) detections = camera.tracker->update(detections); const auto masks = reconstructMasks(interface, detections, bgr_image.cols, bgr_image.rows, letterbox); // Keep publication in the same critical section as inference/tracking. publishResults(camera, header, bgr_image, detections, masks); + auto& state = camera_health_.at(camera_name); + for (const auto* key : {"class_mask", "instance_mask", "detections"}) { + if (auto& task = state.topics.at(key).task; task && header.stamp.sec >= 0 && header.stamp.nanosec < 1000000000u) + task->tick(header.stamp); + } + { + std::lock_guard state_lock(state.mutex); + const auto finished_at = std::chrono::steady_clock::now(); + state.duration_s = std::chrono::duration(finished_at - input_received_at).count(); + state.peak_duration_s = std::max(state.peak_duration_s, state.duration_s); + state.processing_failed = invalid_result; + if (!invalid_result) { + state.last_success = finished_at; + ++state.completed; + } + } if (print_timing_) { const auto finished_at = std::chrono::steady_clock::now(); RCLCPP_INFO(get_logger(), @@ -1281,15 +1409,17 @@ std::vector ImageInstanceSegmentation::decodeDetections(triton_cpp::T int image_width, int image_height, const LetterboxInfo& letterbox, - double score_threshold) { + double score_threshold, + bool& invalid_result) { switch (architecture_) { case ModelArchitecture::Yolo: - return applyNms(decodeYoloDetections(triton_interface, image_width, image_height, letterbox, score_threshold)); + return applyNms( + decodeYoloDetections(triton_interface, image_width, image_height, letterbox, score_threshold, invalid_result)); case ModelArchitecture::Yolo26: // YOLO26 end-to-end exports already select their detections without NMS. - return decodeYoloDetections(triton_interface, image_width, image_height, letterbox, score_threshold); + return decodeYoloDetections(triton_interface, image_width, image_height, letterbox, score_threshold, invalid_result); case ModelArchitecture::RfDetr: - return applyNms(decodeRfDetrDetections(triton_interface, image_width, image_height, score_threshold)); + return applyNms(decodeRfDetrDetections(triton_interface, image_width, image_height, score_threshold, invalid_result)); } return {}; } @@ -1298,7 +1428,8 @@ std::vector ImageInstanceSegmentation::decodeYoloDetections(triton_cp int image_width, int image_height, const LetterboxInfo& letterbox, - double score_threshold) { + double score_threshold, + bool& invalid_result) { const bool yolo26 = architecture_ == ModelArchitecture::Yolo26; const auto runtime_shape = triton_interface.getOutputShape(yolo_detections_output_tensor_name_); if (!((runtime_shape.size() == 3 && runtime_shape[0] == 1) || runtime_shape.size() == 2)) { @@ -1341,17 +1472,22 @@ std::vector ImageInstanceSegmentation::decodeYoloDetections(triton_cp if (yolo26) { best_score = value_at(4, anchor); const float class_id = value_at(5, anchor); - if (!std::isfinite(class_id) || class_id < 0 || class_id >= num_classes || std::floor(class_id) != class_id) continue; + if (!std::isfinite(class_id) || class_id < 0 || class_id >= num_classes || std::floor(class_id) != class_id) { + invalid_result = true; + continue; + } best_class = static_cast(class_id); } else { for (int cls = 0; cls < num_classes; ++cls) { const float score = value_at(4 + cls, anchor); + if (!std::isfinite(score)) invalid_result = true; if (score > best_score) { best_score = score; best_class = cls; } } } + if (!std::isfinite(best_score)) invalid_result = true; if (!std::isfinite(best_score) || best_score < static_cast(score_threshold)) { continue; } @@ -1360,7 +1496,10 @@ std::vector ImageInstanceSegmentation::decodeYoloDetections(triton_cp const float box_b = value_at(1, anchor); const float box_c = value_at(2, anchor); const float box_d = value_at(3, anchor); - if (!std::isfinite(box_a) || !std::isfinite(box_b) || !std::isfinite(box_c) || !std::isfinite(box_d)) continue; + if (!std::isfinite(box_a) || !std::isfinite(box_b) || !std::isfinite(box_c) || !std::isfinite(box_d)) { + invalid_result = true; + continue; + } const cv::Rect2f model_box = yolo26 ? cv::Rect2f(box_a, box_b, box_c - box_a, box_d - box_b) : cv::Rect2f(box_a - box_c * 0.5f, box_b - box_d * 0.5f, box_c, box_d); cv::Rect2f original_box((model_box.x - letterbox.pad_x) / letterbox.scale, @@ -1383,7 +1522,10 @@ std::vector ImageInstanceSegmentation::decodeYoloDetections(triton_cp finite_coefficients = finite_coefficients && std::isfinite(coefficient); detection.mask_coefficients[static_cast(i)] = coefficient; } - if (!finite_coefficients) continue; + if (!finite_coefficients) { + invalid_result = true; + continue; + } detections.push_back(std::move(detection)); } }; @@ -1404,7 +1546,8 @@ std::vector ImageInstanceSegmentation::decodeYoloDetections(triton_cp std::vector ImageInstanceSegmentation::decodeRfDetrDetections(triton_cpp::TritonInterface& triton_interface, int image_width, int image_height, - double score_threshold) { + double score_threshold, + bool& invalid_result) { const auto boxes_shape = triton_interface.getOutputShape(rfdetr_boxes_output_tensor_name_); const auto logits_shape = triton_interface.getOutputShape(rfdetr_logits_output_tensor_name_); const int64_t num_classes = static_cast(class_names_.size()); @@ -1429,11 +1572,16 @@ std::vector ImageInstanceSegmentation::decodeRfDetrDetections(triton_ const float cy = static_cast(boxes(0, query, 1)) * image_height; const float width = static_cast(boxes(0, query, 2)) * image_width; const float height = static_cast(boxes(0, query, 3)) * image_height; - if (!std::isfinite(cx) || !std::isfinite(cy) || !std::isfinite(width) || !std::isfinite(height)) continue; + if (!std::isfinite(cx) || !std::isfinite(cy) || !std::isfinite(width) || !std::isfinite(height)) { + invalid_result = true; + continue; + } const cv::Rect2f box = clipBox({cx - width * 0.5f, cy - height * 0.5f, width, height}, image_width, image_height); if (box.area() <= 1.0f) continue; for (int64_t cls = 0; cls < num_classes; ++cls) { - const float score = 1.0f / (1.0f + std::exp(-static_cast(logits(0, query, cls)))); + const float logit = static_cast(logits(0, query, cls)); + if (!std::isfinite(logit)) invalid_result = true; + const float score = 1.0f / (1.0f + std::exp(-logit)); if (!std::isfinite(score) || score < static_cast(score_threshold)) continue; Detection detection; detection.box = box;