diff --git a/ASSET_LICENSES.md b/ASSET_LICENSES.md index 1cf7523817..064af367ed 100644 --- a/ASSET_LICENSES.md +++ b/ASSET_LICENSES.md @@ -173,6 +173,11 @@ content in all three model families: `probe_02_clean_16k_mono_no_resample.wav` and is distributed under the same terms. +Byte-identical copies of `probe_02_clean_16k_mono_no_resample.wav` are also +stored at: + +- `families/nemotron3_diarization/tests/data/maintainer-recording-16k-mono.wav` + The PersonaPlex fixture contains the same maintainer-owned spoken recording, converted to mono 24 kHz float32 for official-reference regression tests: @@ -212,6 +217,7 @@ International license: - `families/higgs_audio_v2_tokenizer/tests/data/librispeech-test-clean-6930-75918-0003.wav` - `families/hubert/tests/data/librispeech-test-clean-6930-75918-0003.wav` - `families/mimi/tests/data/librispeech-test-clean-6930-75918-0003.wav` +- `families/nemotron3_diarization/tests/data/librispeech-test-clean-6930-75918-0003.wav` - `families/qwen3_asr/tests/data/librispeech-test-clean-6930-75918-0003.wav` - `families/wav2vec2_bert/tests/data/librispeech-test-clean-6930-75918-0003.wav` - `families/wavlm/tests/data/librispeech-test-clean-6930-75918-0003.wav` diff --git a/core/api/include/trtmc/audio.h b/core/api/include/trtmc/audio.h index c49a63566b..9c34eb1f0e 100644 --- a/core/api/include/trtmc/audio.h +++ b/core/api/include/trtmc/audio.h @@ -6,6 +6,7 @@ #ifndef TRTMC_AUDIO_H #define TRTMC_AUDIO_H +#include "trtmc/matrix.h" #include "trtmc/scores.h" #include "trtmc/types.h" @@ -42,6 +43,7 @@ typedef struct { #define TRTMC_TASK_SPEECH_TRANSLATION "speech_translation" #define TRTMC_TASK_AUDIO_LANGUAGE_IDENTIFICATION "audio_language_identification" #define TRTMC_TASK_AUDIO_TO_CLASS_SCORES "audio_to_class_scores" +#define TRTMC_TASK_AUDIO_TO_TIMED_LABELS "audio_to_timed_labels" #define TRTMC_TASK_SPEECH_TO_SPEECH_RESPONSE "speech_to_speech_response" #define TRTMC_TASK_BATCH_SPEECH_TRANSCRIPTION "batch_speech_transcription" #define TRTMC_TASK_BATCH_SPEECH_TRANSLATION "batch_speech_translation" @@ -103,10 +105,45 @@ typedef struct { typedef struct { trtmc_audio_view_v1 audio; } trtmc_audio_to_class_scores_request_v1; +typedef struct { + trtmc_audio_view_v1 audio; +} trtmc_audio_to_timed_labels_request_v1; typedef struct { trtmc_audio_view_v1 audio; } trtmc_speech_to_speech_response_request_v1; +/* One active interval of one label, [start_seconds, end_seconds) on the input + * clock: seconds from the first audio frame, 0 <= start < end. label indexes + * the result's labels. Intervals of one label never overlap; intervals of + * different labels may (overlapping speakers or sound events). */ +typedef struct { + double start_seconds; + double end_seconds; + uint32_t label; +} trtmc_timed_label_v1; + +/* Time-localized labels of one audio input. labels names every label ordinal + * (at least one, each nonempty). An empty vocabulary_id means the names carry + * no identity beyond this result: a diarization family numbers anonymous + * speakers by first appearance in each input. intervals are ordered by start, + * then label. frame_scores is optional: either empty (rows 0, frame_seconds + * 0, score_kind 0) or [frame, label] with one column per label, frame f + * covering [f * frame_seconds, (f + 1) * frame_seconds) of the input, and the + * scores raw in the declared TRTMC_SCORE_* kind: every score finite, and a + * probability within [0, 1]. Multi-label families score every label + * independently; nothing normalizes across labels. */ +typedef struct { + const trtmc_timed_label_v1* intervals; + uint64_t interval_count; + trtmc_strings_view labels; + trtmc_string_view vocabulary_id; + trtmc_f32_matrix_view_v1 frame_scores; + double frame_seconds; + uint32_t score_kind; + double setup_ms; + double inference_ms; +} trtmc_timed_labels_view_v1; + /* Language presence fields are exactly zero or one. Present identifiers must * be nonempty. Absence uses only a default declared by the loaded family; * a family without an applicable default rejects absence. */ @@ -174,6 +211,17 @@ typedef struct { trtmc_error**); } trtmc_audio_to_class_scores_api_v1; +/* Who or what is active when: speaker diarization, voice activity or sound-event + * detection over the whole input, returned as labelled intervals plus the + * family's frame scores. Not transcription and not clip-level tagging. */ +typedef struct { + trtmc_api_header header; + trtmc_status(TRTMC_CALL* run)(trtmc_model*, const trtmc_audio_to_timed_labels_request_v1*, + const trtmc_config_view_v1*, trtmc_result**, trtmc_error**); + trtmc_status(TRTMC_CALL* result_view)(const trtmc_result*, trtmc_timed_labels_view_v1*, + trtmc_error**); +} trtmc_audio_to_timed_labels_api_v1; + /* Response speech to the complete input utterance, not generic audio editing. */ typedef struct { trtmc_api_header header; diff --git a/core/api/include/trtmc/audio.hpp b/core/api/include/trtmc/audio.hpp index 615d878c37..3292d58ba7 100644 --- a/core/api/include/trtmc/audio.hpp +++ b/core/api/include/trtmc/audio.hpp @@ -6,6 +6,7 @@ #pragma once #include "trtmc/audio.h" +#include "trtmc/matrix.hpp" #include "trtmc/scores.hpp" #include "trtmc/text.hpp" @@ -62,6 +63,9 @@ struct AudioLanguageIdentificationRequest { struct AudioToClassScoresRequest { AudioView audio; }; +struct AudioToTimedLabelsRequest { + AudioView audio; +}; struct SpeechToSpeechResponseRequest { AudioView audio; }; @@ -99,6 +103,52 @@ class AudioGenerationResult { trtmc_audio_result_view_v1 view_{}; }; +using TimedLabel = trtmc_timed_label_v1; + +class TimedLabelsResult { + public: + TimedLabelsResult(std::shared_ptr state, trtmc_result* result) noexcept + : owner_(std::move(state), result) {} + TimedLabelsResult(const TimedLabelsResult&) = delete; + TimedLabelsResult& operator=(const TimedLabelsResult&) = delete; + TimedLabelsResult(TimedLabelsResult&& other) noexcept + : owner_(std::move(other.owner_)), view_(std::exchange(other.view_, {})) {} + TimedLabelsResult& operator=(TimedLabelsResult&& other) noexcept { + if (this != &other) { + owner_ = std::move(other.owner_); + view_ = std::exchange(other.view_, {}); + } + return *this; + } + // Ordered by start, then label; label indexes labels(). + Span intervals() const noexcept { + return {view_.intervals, static_cast(view_.interval_count)}; + } + std::vector labels() const { + std::vector labels; + for (std::uint64_t i = 0; i < view_.labels.size; ++i) + labels.push_back(detail::string_view(view_.labels.data[i])); + return labels; + } + std::string_view vocabulary_id() const { return detail::string_view(view_.vocabulary_id); } + // Raw [frame, label] scores; empty when the family has none. + FloatMatrixView frame_scores() const noexcept { + return {{view_.frame_scores.data, static_cast(view_.frame_scores.count)}, + view_.frame_scores.rows, + view_.frame_scores.columns}; + } + double frame_seconds() const noexcept { return view_.frame_seconds; } + std::uint32_t score_kind() const noexcept { return view_.score_kind; } + double setup_ms() const noexcept { return view_.setup_ms; } + double inference_ms() const noexcept { return view_.inference_ms; } + // C views and the convenience views above borrow this result owner. + trtmc_timed_labels_view_v1& wire_view() noexcept { return view_; } + + private: + detail::ResultOwner owner_; + trtmc_timed_labels_view_v1 view_{}; +}; + using TextToAudioResult = AudioGenerationResult; using TextToSpeechResult = AudioGenerationResult; using SpeechToSpeechResponseResult = AudioGenerationResult; @@ -106,6 +156,7 @@ using SpeechTranscriptionResult = TextContinuationResult; using SpeechTranslationResult = TextContinuationResult; using AudioLanguageIdentificationResult = LabelScoresResult; using AudioToClassScoresResult = LabelScoresResult; +using AudioToTimedLabelsResult = TimedLabelsResult; using BatchSpeechTranscriptionResult = BatchTextContinuationResult; using BatchSpeechTranslationResult = BatchTextContinuationResult; using MixedBatchSpeechToTextResult = BatchTextContinuationResult; @@ -379,6 +430,42 @@ class AudioToClassScores { const trtmc_audio_to_class_scores_api_v1* api_; }; +class AudioToTimedLabels { + public: + static constexpr std::string_view kTask = TRTMC_TASK_AUDIO_TO_TIMED_LABELS; + static constexpr std::uint32_t kMajor = 1, kMinor = 0; + AudioToTimedLabelsResult run(const AudioToTimedLabelsRequest& input, + const Config& config = {}) const { + const trtmc_audio_to_timed_labels_request_v1 request{detail::c_audio(input.audio)}; + auto entries = config.c_entries(); + auto options = entries.view(); + trtmc_result* raw = nullptr; + trtmc_error* error = nullptr; + auto status = api_->run(state_->handle, &request, &options, &raw, &error); + TimedLabelsResult result(state_, raw); + detail::check(state_->api, status, error); + error = nullptr; + status = api_->result_view(raw, &result.wire_view(), &error); + detail::check(state_->api, status, error); + return result; + } + std::vector config_fields() const { + return detail::config_fields(state_, kTask, kMajor, kMinor); + } + static void validate_table(const trtmc_api_header* table) { + detail::validate_audio_table(table); + } + + private: + friend class Model; + AudioToTimedLabels(std::shared_ptr state, + const trtmc_api_header* table) noexcept + : state_(std::move(state)), + api_(reinterpret_cast(table)) {} + std::shared_ptr state_; + const trtmc_audio_to_timed_labels_api_v1* api_; +}; + class SpeechToSpeechResponse { public: static constexpr std::string_view kTask = TRTMC_TASK_SPEECH_TO_SPEECH_RESPONSE; diff --git a/core/api/runtime/audio.cpp b/core/api/runtime/audio.cpp index 115c4bb09c..d8cea1bf09 100644 --- a/core/api/runtime/audio.cpp +++ b/core/api/runtime/audio.cpp @@ -5,6 +5,9 @@ #include "api_internal.h" +#include +#include + namespace trtmc::api { internal::AudioView audio_view(const trtmc_audio_view_v1& input) { @@ -266,6 +269,138 @@ extern "C" trtmc_status TRTMC_CALL audio_to_class_scores_run( }); } +void require_named_labels(const std::vector& labels) { + if (labels.empty() || labels.size() > UINT32_MAX) + throw ApiFailure{TRTMC_INTERNAL_ERROR, "timed labels need between one and 2^32-1 labels"}; + for (const auto& label : labels) + if (label.empty()) + throw ApiFailure{TRTMC_INTERNAL_ERROR, "timed labels must name every label"}; +} + +void require_valid_interval(const internal::TimedLabel& interval, std::size_t label_count) { + if (!std::isfinite(interval.start_seconds) || !std::isfinite(interval.end_seconds) || + interval.start_seconds < 0 || interval.end_seconds <= interval.start_seconds) + throw ApiFailure{TRTMC_INTERNAL_ERROR, "timed label interval is empty or not finite"}; + if (interval.label >= label_count) + throw ApiFailure{TRTMC_INTERNAL_ERROR, "timed label interval names an unknown label"}; +} + +bool ordered_after(const internal::TimedLabel& interval, const internal::TimedLabel& previous) { + return interval.start_seconds > previous.start_seconds || + (interval.start_seconds == previous.start_seconds && interval.label > previous.label); +} + +void require_ordered_intervals(const std::vector& intervals, + std::size_t label_count) { + std::vector label_end(label_count, 0.0); + for (std::size_t index = 0; index < intervals.size(); ++index) { + const auto& interval = intervals[index]; + require_valid_interval(interval, label_count); + if (index > 0 && !ordered_after(interval, intervals[index - 1])) + throw ApiFailure{TRTMC_INTERNAL_ERROR, + "timed label intervals are not ordered by start, then label"}; + if (interval.start_seconds < label_end[interval.label]) + throw ApiFailure{TRTMC_INTERNAL_ERROR, "intervals of one timed label overlap"}; + label_end[interval.label] = interval.end_seconds; + } +} + +void require_frame_score_values(const std::vector& scores, bool probability) { + for (const float score : scores) { + if (!std::isfinite(score)) + throw ApiFailure{TRTMC_INTERNAL_ERROR, "timed label frame scores must be finite"}; + if (probability && (score < 0.0F || score > 1.0F)) + throw ApiFailure{TRTMC_INTERNAL_ERROR, + "timed label probability frame scores must lie in [0, 1]"}; + } +} + +void require_frame_scores(const internal::TimedLabelsResult& result) { + if (result.frame_scores.empty()) { + if (result.frame_count != 0 || result.frame_seconds != 0) + throw ApiFailure{TRTMC_INTERNAL_ERROR, + "timed labels without frame scores declare frames"}; + return; + } + const auto labels = static_cast(result.labels.size()); + if (result.frame_count == 0 || result.frame_count > UINT64_MAX / labels || + result.frame_count * labels != result.frame_scores.size()) + throw ApiFailure{TRTMC_INTERNAL_ERROR, + "timed label frame scores are not one row per frame and label"}; + if (!std::isfinite(result.frame_seconds) || result.frame_seconds <= 0) + throw ApiFailure{TRTMC_INTERNAL_ERROR, "timed label frames need a positive duration"}; + switch (result.score_kind) { + case internal::ScoreKind::Logit: + case internal::ScoreKind::Unbounded: + require_frame_score_values(result.frame_scores, false); + return; + case internal::ScoreKind::Probability: + require_frame_score_values(result.frame_scores, true); + return; + } + throw ApiFailure{TRTMC_INTERNAL_ERROR, "timed label frame scores have an unknown kind"}; +} + +struct TimedLabelsStorage final : ResultStorage { + explicit TimedLabelsStorage(internal::TimedLabelsResult value) : result(std::move(value)) { + require_named_labels(result.labels); + require_ordered_intervals(result.intervals, result.labels.size()); + require_frame_scores(result); + intervals.reserve(result.intervals.size()); + for (const auto& interval : result.intervals) + intervals.push_back({interval.start_seconds, interval.end_seconds, interval.label}); + labels.reserve(result.labels.size()); + for (const auto& label : result.labels) + labels.push_back(borrowed_string(label)); + } + internal::TimedLabelsResult result; + std::vector intervals; + std::vector labels; +}; + +extern "C" trtmc_status TRTMC_CALL audio_to_timed_labels_run( + trtmc_model* model, const trtmc_audio_to_timed_labels_request_v1* input, + const trtmc_config_view_v1* config, trtmc_result** output, trtmc_error** error) noexcept { + if (output) + *output = nullptr; + return guarded(error, [&] { + require(input && output, "audio timed-labels request and result output are required"); + const internal::AudioToTimedLabelsRequest request{audio_view(input->audio)}; + const ConvertedConfig options(config); + + std::lock_guard lock(model_mutex(model)); + auto& task = require_interface( + model, internal::IAudioToTimedLabels::kTask); + validate_task_config(model_owner(model), + internal::contract_key(), + options.view()); + *output = make_result(task.run(request, options.view())); + }); +} + +trtmc_status TRTMC_CALL timed_labels_result_view(const trtmc_result* result, + trtmc_timed_labels_view_v1* output, + trtmc_error** error) noexcept { + if (output) + *output = {}; + return guarded(error, [&] { + require(output != nullptr, "timed labels output is required"); + const auto& storage = require_result(result); + const auto& value = storage.result; + const bool framed = !value.frame_scores.empty(); + *output = {storage.intervals.data(), + storage.intervals.size(), + {storage.labels.data(), storage.labels.size()}, + borrowed_string(value.vocabulary_id), + {value.frame_scores.data(), value.frame_scores.size(), value.frame_count, + framed ? value.labels.size() : 0}, + value.frame_seconds, + framed ? static_cast(value.score_kind) : 0U, + value.setup_ms, + value.inference_ms}; + }); +} + extern "C" trtmc_status TRTMC_CALL speech_response_run( trtmc_model* model, const trtmc_speech_to_speech_response_request_v1* input, const trtmc_config_view_v1* config, trtmc_result** output, trtmc_error** error) noexcept { @@ -542,6 +677,8 @@ const trtmc_audio_language_identification_api_v1 language_api{ {1, 0, sizeof(language_api)}, language_identification_run, label_scores_result_view}; const trtmc_audio_to_class_scores_api_v1 audio_class_scores_api{ {1, 0, sizeof(audio_class_scores_api)}, audio_to_class_scores_run, label_scores_result_view}; +const trtmc_audio_to_timed_labels_api_v1 audio_timed_labels_api{ + {1, 0, sizeof(audio_timed_labels_api)}, audio_to_timed_labels_run, timed_labels_result_view}; const trtmc_speech_to_speech_response_api_v1 response_api{ {1, 0, sizeof(response_api)}, speech_response_run, audio_result_view}; const trtmc_audio_codebook_tokens_to_audio_api_v1 codec_audio_api{ @@ -586,6 +723,7 @@ const TaskBinding bindings[] = { {internal::ISpeechTranslation::kTask, 1, 0, &translation_api.header}, {internal::IAudioLanguageIdentification::kTask, 1, 0, &language_api.header}, {internal::IAudioToClassScores::kTask, 1, 0, &audio_class_scores_api.header}, + {internal::IAudioToTimedLabels::kTask, 1, 0, &audio_timed_labels_api.header}, {internal::ISpeechToSpeechResponse::kTask, 1, 0, &response_api.header}, {internal::IBatchSpeechTranscription::kTask, 1, 0, &batch_transcription_api.header}, {internal::IBatchSpeechTranslation::kTask, 1, 0, &batch_translation_api.header}, diff --git a/core/api/tests/audio_c_test.c b/core/api/tests/audio_c_test.c index 54a723d203..250827e5c7 100644 --- a/core/api/tests/audio_c_test.c +++ b/core/api/tests/audio_c_test.c @@ -217,13 +217,15 @@ static void test_audio(trtmc_model* model, trtmc_model* restricted) { model, TRTMC_TASK_AUDIO_LANGUAGE_IDENTIFICATION); const trtmc_audio_to_class_scores_api_v1* events = (const trtmc_audio_to_class_scores_api_v1*)table(model, TRTMC_TASK_AUDIO_TO_CLASS_SCORES); + const trtmc_audio_to_timed_labels_api_v1* timed = + (const trtmc_audio_to_timed_labels_api_v1*)table(model, TRTMC_TASK_AUDIO_TO_TIMED_LABELS); const trtmc_batch_speech_transcription_api_v1* batch = (const trtmc_batch_speech_transcription_api_v1*)table( model, TRTMC_TASK_BATCH_SPEECH_TRANSCRIPTION); const trtmc_mixed_batch_speech_to_text_api_v1* mixed = (const trtmc_mixed_batch_speech_to_text_api_v1*)table( model, TRTMC_TASK_MIXED_BATCH_SPEECH_TO_TEXT); - if (!generation || !asr || !translation || !language || !events || !batch || !mixed) + if (!generation || !asr || !translation || !language || !events || !timed || !batch || !mixed) return; trtmc_error* error = NULL; trtmc_result* result = NULL; @@ -322,6 +324,29 @@ static void test_audio(trtmc_model* model, trtmc_model* restricted) { "sound-event labels are named and the scores stay raw logits"); core->result_release(result); + trtmc_audio_to_timed_labels_request_v1 timed_input = {request.audio}; + status = timed->run(model, &timed_input, NULL, &result, &error); + status_is(status, TRTMC_OK, error, "C audio timed labels succeed"); + trtmc_timed_labels_view_v1 timed_labels = {0}; + status = timed->result_view(result, &timed_labels, &error); + status_is(status, TRTMC_OK, error, "C audio timed labels result view succeeds"); + check(timed_labels.interval_count == 3 && timed_labels.labels.size == 2 && + timed_labels.intervals[1].label == 1 && + timed_labels.intervals[1].start_seconds == 0.01 && + timed_labels.labels.data[1].size == 9 && + memcmp(timed_labels.labels.data[1].data, "speaker_1", 9) == 0 && + timed_labels.vocabulary_id.size == 0, + "timed labels name result-local speakers and keep their intervals"); + check(timed_labels.frame_scores.rows == 3 && timed_labels.frame_scores.columns == 2 && + timed_labels.frame_scores.count == 6 && timed_labels.frame_scores.data[1] == -1.0F && + timed_labels.frame_seconds == 0.01 && timed_labels.score_kind == TRTMC_SCORE_LOGIT, + "timed label frame scores are raw [frame, label] logits"); + trtmc_label_scores_view_v1 not_scores = {0}; + status = events->result_view(result, ¬_scores, &error); + status_is(status, TRTMC_INVALID_ARGUMENT, error, + "timed labels are not readable through a label-scores view"); + core->result_release(result); + trtmc_batch_speech_transcription_item_v1 item = {0}; item.input = request; trtmc_batch_speech_transcription_request_v1 batch_input = {&item, 1}; diff --git a/core/api/tests/audio_family.cpp b/core/api/tests/audio_family.cpp index 3251f8bbe1..36ea34ed82 100644 --- a/core/api/tests/audio_family.cpp +++ b/core/api/tests/audio_family.cpp @@ -9,6 +9,7 @@ #include #include +#include #include namespace { @@ -46,6 +47,7 @@ class AudioFixture final : public IModel, public ISpeechTranslation, public IAudioLanguageIdentification, public IAudioToClassScores, + public IAudioToTimedLabels, public ISpeechToSpeechResponse, public IBatchSpeechTranscription, public IBatchSpeechTranslation, @@ -82,6 +84,7 @@ class AudioFixture final : public IModel, bind(*this, fields_for(IAudioLanguageIdentification::kTask)), bind(*this, fields_for(IAudioToClassScores::kTask)), + bind(*this, fields_for(IAudioToTimedLabels::kTask)), bind(*this, fields_for(ISpeechToSpeechResponse::kTask)), bind(*this, fields_for(IBatchSpeechTranscription::kTask)), bind(*this, fields_for(IBatchSpeechTranslation::kTask)), @@ -125,6 +128,11 @@ class AudioFixture final : public IModel, {"gain", ConfigKind::F64, ConfigValue{1.0}, "Response gain"}}; return declared; } + if (task == IAudioToTimedLabels::kTask) { + static const ConfigField declared[] = { + {"gain", ConfigKind::F64, ConfigValue{1.0}, "Frame score gain"}}; + return declared; + } if (task == ISpeechTranscription::kTask || task == ISpeechTranslation::kTask) { if (mode_ == "asr_new_tokens") { static const ConfigField declared[] = { @@ -236,6 +244,25 @@ class AudioFixture final : public IModel, result.labels[1].clear(); return result; } + TimedLabelsResult run(const AudioToTimedLabelsRequest& input, ConfigView config) override { + const auto audio = resolve_audio(input.audio); + const auto options = parse(config, IAudioToTimedLabels::kTask); + // Two anonymous speakers over three 10 ms frames: speaker 1 overlaps + // both turns of speaker 0, and the scores stay raw per-label logits. + TimedLabelsResult result; + result.labels = {"speaker_0", "speaker_1"}; + result.intervals = {{0.0, 0.01, 0}, {0.01, 0.03, 1}, {0.02, 0.03, 0}}; + const auto gain = static_cast(options.gain); + result.frame_scores = {2.0F * gain, -1.0F * gain, -1.0F * gain, + 3.0F * gain, 1.0F * gain, 4.0F * gain}; + result.frame_count = 3; + result.frame_seconds = 0.01; + result.score_kind = ScoreKind::Logit; + result.setup_ms = audio.channels; + result.inference_ms = static_cast(audio.samples.size()); + damage_timed_labels(result); + return result; + } AudioResult run(const SpeechToSpeechResponseRequest& input, ConfigView config) override { const auto options = parse(config, ISpeechToSpeechResponse::kTask); const auto audio = resolve_audio(input.audio); @@ -392,6 +419,41 @@ class AudioFixture final : public IModel, } private: + // Each mode breaks exactly one promise of the timed-labels contract. + void damage_timed_labels(TimedLabelsResult& result) const { + if (mode_ == "bad_labels") + result.labels[1].clear(); + if (mode_ == "timed_unknown_label") + result.intervals[1].label = 2; + if (mode_ == "timed_unordered") + std::swap(result.intervals[0], result.intervals[1]); + if (mode_ == "timed_overlap") + result.intervals[0].end_seconds = 0.025; + if (mode_ == "timed_empty_interval") + result.intervals[0].end_seconds = result.intervals[0].start_seconds; + if (mode_ == "timed_frame_shape") + result.frame_scores.pop_back(); + if (mode_ == "timed_frame_seconds") + result.frame_seconds = 0; + if (mode_ == "timed_frames_without_scores") + result.frame_scores.clear(); + if (mode_ == "timed_nan_score") + result.frame_scores[4] = std::numeric_limits::quiet_NaN(); + if (mode_ == "timed_infinite_score") + result.frame_scores[4] = std::numeric_limits::infinity(); + // The fixture's logits run from -1 to 4, outside a probability's range. + if (mode_ == "timed_probability_range") + result.score_kind = ScoreKind::Probability; + if (mode_ == "timed_probabilities") { + result.score_kind = ScoreKind::Probability; + result.frame_scores = {1.0F, 0.0F, 0.0F, 0.75F, 0.5F, 1.0F}; + } + if (mode_ == "timed_intervals_only") { + result.frame_scores.clear(); + result.frame_count = 0; + result.frame_seconds = 0; + } + } BatchAudioResult finish_generated_batch(BatchAudioResult result) const { if (mode_ == "batch_execution_error") throw std::runtime_error("fixture native batch execution failed"); diff --git a/core/api/tests/audio_test.cpp b/core/api/tests/audio_test.cpp index a94275d6d8..7320e4d831 100644 --- a/core/api/tests/audio_test.cpp +++ b/core/api/tests/audio_test.cpp @@ -41,8 +41,82 @@ void write_bundle(const std::filesystem::path& path, const std::string& mode) { output.write("PLAN", 4); } +void test_timed_labels(const trtmc::Model& model, trtmc::AudioView audio) { + const auto task = model.task(); + check(task.config_fields().size() == 1 && task.config_fields()[0].name == "gain", + "timed labels expose only the family's declared config"); + auto timed = task.run({audio}, {{"gain", 2.0}}); + const std::vector speakers{"speaker_0", "speaker_1"}; + const auto intervals = timed.intervals(); + check(timed.labels() == speakers && timed.vocabulary_id().empty() && intervals.size() == 3 && + intervals[0].start_seconds == 0.0 && intervals[0].end_seconds == 0.01 && + intervals[0].label == 0 && intervals[1].label == 1 && + intervals[1].end_seconds == 0.03 && intervals[2].start_seconds == 0.02, + "timed labels keep result-local speakers and overlapping turns in start order"); + const auto scores = timed.frame_scores(); + check(scores.rows == 3 && scores.columns == 2 && scores.values.size() == 6 && + scores.values[0] == 4.0F && scores.values[3] == 6.0F && + timed.frame_seconds() == 0.01 && timed.score_kind() == TRTMC_SCORE_LOGIT, + "frame scores stay raw [frame, label] logits on a declared frame clock"); + check(timed.setup_ms() == 2 && timed.inference_ms() == 4, + "timed labels keep the family's timings"); + auto moved = std::move(timed); + check(moved.intervals().size() == 3 && timed.intervals().empty() && + timed.frame_scores().values.empty(), + "timed labels owner move clears the source views"); + check(rejects([&] { (void)task.run({audio}, {{"threshold", 0.5}}); }, TRTMC_INVALID_CONFIG), + "timed labels reject undeclared config"); +} + +void test_timed_label_modes(const std::filesystem::path& root, const trtmc::LoadOptions& options, + trtmc::AudioView audio) { + // Every mode breaks one promise of the contract; the shared layer refuses + // the family result instead of handing it to the application. + for (const auto* mode : + {"bad_labels", "timed_unknown_label", "timed_unordered", "timed_overlap", + "timed_empty_interval", "timed_frame_shape", "timed_frame_seconds", + "timed_frames_without_scores", "timed_nan_score", "timed_infinite_score", + "timed_probability_range"}) { + const auto path = root / (std::string{"audio-timed-"} + mode + ".bundle"); + write_bundle(path, mode); + check(rejects( + [&] { + (void)trtmc::Model::load(path.string(), options) + .task() + .run({audio}); + }, + TRTMC_INTERNAL_ERROR), + mode); + std::filesystem::remove(path); + } + const auto path = root / "audio-timed-intervals-only.bundle"; + write_bundle(path, "timed_intervals_only"); + { + const auto result = trtmc::Model::load(path.string(), options) + .task() + .run({audio}); + const auto scores = result.frame_scores(); + check(result.intervals().size() == 3 && scores.rows == 0 && scores.columns == 0 && + scores.values.empty() && result.frame_seconds() == 0 && result.score_kind() == 0, + "timed labels without frame scores report an empty frame matrix"); + } + std::filesystem::remove(path); + const auto probabilities = root / "audio-timed-probabilities.bundle"; + write_bundle(probabilities, "timed_probabilities"); + { + const auto result = trtmc::Model::load(probabilities.string(), options) + .task() + .run({audio}); + const auto scores = result.frame_scores(); + check(result.score_kind() == TRTMC_SCORE_PROBABILITY && scores.values.size() == 6 && + scores.values[0] == 1.0F && scores.values[1] == 0.0F, + "probability frame scores at both ends of [0, 1] are accepted"); + } + std::filesystem::remove(probabilities); +} + void test_stateless(const trtmc::Model& model, trtmc::AudioView audio) { - check(model.tasks().size() == 14, "all stateless audio contracts are discoverable"); + check(model.tasks().size() == 15, "all stateless audio contracts are discoverable"); auto generated = model.task().run({"wind"}, {{"preset", "calm"}}); check(generated.channels() == 2 && generated.sample_rate() == 24000 && generated.frame_count() == 2, @@ -80,6 +154,7 @@ void test_stateless(const trtmc::Model& model, trtmc::AudioView audio) { check(events.labels() == event_labels && events.scores()[0] == 1.5F && events.kind() == TRTMC_SCORE_LOGIT && events.vocabulary_id().empty(), "audio class scores stay raw multi-label logits over named sound events"); + test_timed_labels(model, audio); auto language = model.task().run({audio}); check(language.labels() == std::vector{"en", "fr"} && language.scores()[0] == 0.75F && language.kind() == TRTMC_SCORE_PROBABILITY && @@ -488,6 +563,7 @@ int main(int argc, char** argv) { test_generated_batches(full.string(), options); test_generated_modes(root, options); test_codec(root, options); + test_timed_label_modes(root, options, audio); const auto limited = trtmc::Model::load(restricted.string(), options); check(limited.supports() && !limited.supports() && diff --git a/core/runtime/include/trtmc/internal/audio.h b/core/runtime/include/trtmc/internal/audio.h index de1b5c2150..e7a25fa6ad 100644 --- a/core/runtime/include/trtmc/internal/audio.h +++ b/core/runtime/include/trtmc/internal/audio.h @@ -70,6 +70,37 @@ struct AudioLanguageIdentificationRequest { struct AudioToClassScoresRequest { AudioView audio; }; +struct AudioToTimedLabelsRequest { + AudioView audio; +}; + +// One active interval of one label, [start_seconds, end_seconds) seconds from +// the first input frame. label indexes TimedLabelsResult::labels. +struct TimedLabel { + double start_seconds{0}; + double end_seconds{0}; + std::uint32_t label{0}; +}; + +struct TimedLabelsResult { + // Ordered by start, then label; one label's intervals never overlap. + std::vector intervals; + // One nonempty name per label ordinal. An empty vocabulary_id means the + // names have no identity beyond this result (anonymous speakers numbered + // by first appearance in each input). + std::vector labels; + std::string vocabulary_id; + // Optional raw frame scores, row-major [frame_count, labels.size()]; frame + // f covers [f * frame_seconds, (f + 1) * frame_seconds). Every score is + // finite, a probability within [0, 1]. Empty with frame_count and + // frame_seconds zero when the family has none. + std::vector frame_scores; + std::uint64_t frame_count{0}; + double frame_seconds{0}; + ScoreKind score_kind{ScoreKind::Logit}; + double setup_ms{0}; + double inference_ms{0}; +}; struct SpeechToSpeechResponseRequest { AudioView audio; }; @@ -147,6 +178,19 @@ class IAudioToClassScores { // scores that do not sum to one; the application never renormalizes them. virtual LabelScoresResult run(const AudioToClassScoresRequest&, ConfigView) = 0; }; +class IAudioToTimedLabels { + public: + using TaskInterface = IAudioToTimedLabels; + static constexpr std::string_view kTask = "audio_to_timed_labels"; + virtual ~IAudioToTimedLabels() = default; + // Who or what is active when over the whole input: speaker diarization, + // voice activity or sound-event detection. Intervals are on the input clock, + // in seconds, ordered by start then label, and never overlap within one + // label. Every label ordinal is named. Frame scores, when the family has + // them, are the raw per-frame per-label scores the intervals were derived + // from, in the declared ScoreKind; nothing renormalizes across labels. + virtual TimedLabelsResult run(const AudioToTimedLabelsRequest&, ConfigView) = 0; +}; class ISpeechToSpeechResponse { public: using TaskInterface = ISpeechToSpeechResponse; diff --git a/families/nemotron3_diarization/NOTICE b/families/nemotron3_diarization/NOTICE new file mode 100644 index 0000000000..994647bfce --- /dev/null +++ b/families/nemotron3_diarization/NOTICE @@ -0,0 +1,38 @@ +Nemotron 3 Diarization checkpoint and model configuration: +https://huggingface.co/nvidia/Nemotron-3-Diarization +Revision 52a432672732425e4c19765b9fec9b5810e6f4ba. +The checkpoint is distributed under its own license (OpenMDW-1.1) and is not +part of this repository. + +Nemotron3DiarizationForAudioFrameClassification, Nemotron3DiarizationSpeakerCache +and Nemotron3DiarizationProcessor (src/transformers/models/nemotron3_diarization/) +and NemotronAsrStreamingFeatureExtractor +(src/transformers/models/nemotron_asr_streaming/) reference implementation in +Hugging Face Transformers 5.22.2, https://github.com/huggingface/transformers. +The family transcribes the encoder and the speaker head (graph.py, model.py, +rotary.py), the log-mel front end (frontend.py, runtime/frontend.cpp), the +Arrival-Order Speaker Cache with its score boosts and compression and the +offline chunk loop (runtime/speaker_cache.cpp, runtime/pipeline.cpp), and the +speaker segments (runtime/pipeline.cpp): +Copyright 2026 The HuggingFace Inc. team. All rights reserved. +Licensed under the Apache License, Version 2.0. + +The Slaney mel filterbank in frontend.py (Slaney mel scale and Slaney area +normalization) follows librosa.filters.mel of librosa 1.0.0, +https://github.com/librosa/librosa, which is licensed as follows: + +ISC License + +Copyright (c) 2013--2026, librosa development team. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/families/nemotron3_diarization/__init__.py b/families/nemotron3_diarization/__init__.py new file mode 100644 index 0000000000..d0136251dc --- /dev/null +++ b/families/nemotron3_diarization/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Nemotron 3 Diarization (streaming Sortformer) speaker diarization family.""" diff --git a/families/nemotron3_diarization/cli.json b/families/nemotron3_diarization/cli.json new file mode 100644 index 0000000000..9060901972 --- /dev/null +++ b/families/nemotron3_diarization/cli.json @@ -0,0 +1,17 @@ +{ + "version": 1, + "commands": [ + { + "name": "diarize", "help": "Label who speaks when in a 16 kHz WAV recording", "executor": "native", + "handler": "diarize", + "arguments": [ + {"name": "bundle", "type": "path"}, + {"name": "audio", "flags": ["--audio"], "type": "path", "required": true, + "help": "16 kHz PCM16 or float32 WAV; channels are averaged"}, + {"name": "runtime_root", "flags": ["--runtime-root"], "type": "path"}, + {"name": "threshold", "flags": ["--threshold"], "type": "float", + "help": "speaker activity threshold, strictly inside (0, 1); the family's default is 0.5"} + ] + } + ] +} diff --git a/families/nemotron3_diarization/config.py b/families/nemotron3_diarization/config.py new file mode 100644 index 0000000000..7e63e6d142 --- /dev/null +++ b/families/nemotron3_diarization/config.py @@ -0,0 +1,308 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Resolve the Nemotron 3 Diarization geometry, cross-checked against the tensors. + +``config.json`` states the encoder, the speaker head, the offline chunking and +the speaker-cache policy; ``processor_config.json`` states the front end. Every +value the bundle depends on is read, checked against the tensor shapes where a +tensor pins it, and refused when this family does not implement it, so a +checkpoint that differs in a way the graph would silently ignore is not built. +""" + +from __future__ import annotations + +import json +import math +import struct +from pathlib import Path + +# The front end floors the mel energies with this constant before the log. +LOG_GUARD = 2.0**-24 +# The checkpoint's prefix of the audio encoder's tensors. +ENCODER_PREFIX = "model.audio_tower" +# The largest finite float32: the engines and the native runtime hold every +# constant in float32. +FLOAT32_MAX = 3.4028234663852886e38 +INT32_MAX = 2**31 - 1 + + +def _unique_keys(pairs: list) -> dict: + """An object hook that refuses a repeated key instead of keeping its last value.""" + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"nemotron3_diarization config repeats the key {key!r}") + result[key] = value + return result + + +def _read(model_dir: Path, name: str) -> dict: + path = Path(model_dir) / name + if not path.is_file(): + raise FileNotFoundError(f"Required nemotron3_diarization config is missing: {path}") + return json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_unique_keys) + + +def _int(config: dict, key: str, *, minimum: int = 1, default: int | None = None) -> int: + # The native runtime reads every count as an int32. + value = config.get(key, default) + if not isinstance(value, int) or isinstance(value, bool) or not minimum <= value <= INT32_MAX: + raise ValueError(f"nemotron3_diarization config has an unusable {key}: {value!r}") + return value + + +def _float(config: dict, key: str, default: float | None = None, *, + low: float = -FLOAT32_MAX, high: float = FLOAT32_MAX, + low_open: bool = False, high_open: bool = False) -> float: + # JSON numbers only: a boolean, a string or an explicit null is refused, never + # coerced. The range holds for the float32 the engines and the runtime store, + # so the value is rounded to float32 before it is compared. + value = config.get(key, default) + if (isinstance(value, bool) or not isinstance(value, (int, float)) + or not abs(value) <= FLOAT32_MAX): # NaN fails the comparison too + raise ValueError(f"nemotron3_diarization config has an unusable {key}: {value!r}") + stored = struct.unpack("= high if high_open else stored > high + if below or above: + raise ValueError(f"nemotron3_diarization config {key} is out of range: {value!r}") + return float(value) + + +def _budget(frames: int, rate: float, key: str, limit: int) -> int: + """A speaker-cache frame budget, ``floor(frames * rate)``, at most ``limit``. + + A boost budget ranks frames with top-k, which needs as many frames as it + boosts; a compression always ranks more frames than the cache holds. + """ + budget = math.floor(frames * rate) + if budget > limit: + raise ValueError(f"nemotron3_diarization config {key} gives a budget past {limit}: {rate!r}") + return budget + + +def _expect(actual, expected, what: str) -> None: + if actual != expected: + raise ValueError(f"nemotron3_diarization {what} is {actual!r}; this family needs {expected!r}") + + +def _encoder(audio: dict, shapes: dict) -> dict: + hidden = _int(audio, "hidden_size") + heads = _int(audio, "num_attention_heads") + kv_heads = _int(audio, "num_key_value_heads", default=heads) + _expect(kv_heads, heads, "num_key_value_heads") + if hidden % heads: + raise ValueError("nemotron3_diarization hidden_size is not divisible by the head count") + # Rotary embeddings pair dimension i with i + head_dim / 2. + if (hidden // heads) % 2: + raise ValueError("nemotron3_diarization needs an even head width for rotary embeddings") + _expect(audio.get("hidden_act"), "gelu", "hidden_act") + rope = audio.get("rope_parameters") or {} + _expect(rope.get("rope_type", "default"), "default", "rope_type") + # Every dimension of every head rotates: the reference passes nothing through. + _expect(_float(rope, "partial_rotary_factor", 1.0), 1.0, "partial_rotary_factor") + encoder = { + "hidden_size": hidden, + "num_heads": heads, + "head_dim": hidden // heads, + "intermediate_size": _int(audio, "intermediate_size"), + "num_layers": _int(audio, "num_hidden_layers"), + "num_mel_bins": _int(audio, "num_mel_bins"), + "subsampling_factor": _int(audio, "subsampling_factor"), + "max_position_embeddings": _int(audio, "max_position_embeddings"), + # A base above one keeps every inverse frequency in (0, 1] in float32. + "rope_theta": _float(rope, "rope_theta", low=1.0, low_open=True), + "layer_norm_eps": 1e-5, # nn.LayerNorm's default; the config does not override it. + } + stacked = encoder["subsampling_factor"] * encoder["num_mel_bins"] + _expect(shapes.get("model.audio_tower.embedder.projection.weight"), (hidden, stacked), + "feature-stacking projection shape") + _expect(sum(key.startswith("model.audio_tower.layers.") and key.endswith(".self_attn.q_proj.weight") + for key in shapes), encoder["num_layers"], "encoder layer count") + _expect(shapes.get("model.audio_tower.layers.0.mlp.fc1.weight"), + (encoder["intermediate_size"], hidden), "MLP shape") + return encoder + + +def _head(head_config: dict, encoder: dict, shapes: dict) -> dict: + head = { + "head_hidden_size": _int(head_config, "hidden_size"), + "num_speakers": _int(head_config, "num_speakers"), + } + _expect(_int(head_config, "audio_hidden_size"), encoder["hidden_size"], "head audio_hidden_size") + _expect(_int(head_config, "subsampling_factor"), encoder["subsampling_factor"], + "head subsampling_factor") + width, speakers, factor = (head["head_hidden_size"], head["num_speakers"], + encoder["subsampling_factor"]) + _expect(shapes.get("model.proj.weight"), (width, encoder["hidden_size"]), "projection shape") + _expect(shapes.get("model.upsampler.conv.weight"), (width * factor, width, 3), "upsampler shape") + _expect(shapes.get("classifier.dense.weight"), (width, width), "classifier shape") + _expect(shapes.get("classifier.out_proj.weight"), (speakers, width), "speaker output shape") + _expect(shapes.get("silence_embeds"), (encoder["hidden_size"],), "silence embedding shape") + return head + + +def _speaker_cache(streaming: dict, encoder: dict, head: dict) -> dict: + """The Arrival-Order Speaker Cache policy, with its derived frame budgets. + + The budgets are computed here, once, with the reference's own arithmetic, so + the runtime receives integers instead of re-deriving them from rates. + """ + _expect(_int(streaming, "num_speakers"), head["num_speakers"], "streaming num_speakers") + _expect(_int(streaming, "subsampling_factor"), encoder["subsampling_factor"], + "streaming subsampling_factor") + length = _int(streaming, "speaker_cache_length") + silence = _int(streaming, "speaker_cache_silence_frames_per_speaker", minimum=0) + speakers = head["num_speakers"] + if length < (1 + silence) * speakers: + raise ValueError("nemotron3_diarization speaker cache cannot hold every speaker") + budget = length // speakers - silence + return { + "speaker_cache_length": length, + "silence_frames_per_speaker": silence, + # The probability floor of the cache's log scores: a log of zero would + # turn saturated probabilities into infinities. + "prediction_score_threshold": _float(streaming, "prediction_score_threshold", low=0.0, + high=1.0, low_open=True, high_open=True), + "latest_frames_score_boost": _float(streaming, "latest_frames_score_boost"), + "min_positive_scores": _budget(budget, _float(streaming, "min_positive_scores_rate", + low=0.0), "min_positive_scores_rate", + INT32_MAX), + **{name: _budget(budget, _float(streaming, rate, low=0.0), rate, length) + for name, rate in (("strong_boosted_frames", "strong_boost_rate"), + ("weak_boosted_frames", "weak_boost_rate"))}, + } + + +def _offline_chunking(model: dict, encoder: dict, cache: dict) -> dict: + """Whole-recording diarization: the reference's offline chunk loop.""" + chunking = { + "chunk_length": _int(model, "chunk_length"), + "chunk_left_context": _int(model, "chunk_left_context", minimum=0, default=0), + "chunk_right_context": _int(model, "chunk_right_context", minimum=0), + "fifo_length": _int(model, "fifo_length", minimum=0), + "speaker_cache_update_period": _int(model, "speaker_cache_update_period"), + } + if chunking["chunk_right_context"] >= chunking["chunk_length"]: + raise ValueError("nemotron3_diarization chunk_right_context must be below chunk_length") + # One encoder step attends over the whole cache, the FIFO queue and one chunk + # with both of its contexts; positions restart at zero for every step. + chunking["max_step_rows"] = (cache["speaker_cache_length"] + chunking["fifo_length"] + + chunking["chunk_left_context"] + chunking["chunk_length"] + + chunking["chunk_right_context"]) + if chunking["max_step_rows"] > encoder["max_position_embeddings"]: + raise ValueError("nemotron3_diarization step exceeds max_position_embeddings") + return chunking + + +def _front_end(processor: dict, encoder: dict) -> dict: + features = processor.get("feature_extractor") or {} + _expect(features.get("feature_extractor_type"), "NemotronAsrStreamingFeatureExtractor", + "feature extractor") + _expect(features.get("mel_filters_dtype", "float32"), "float32", "mel_filters_dtype") + _expect(_float(features, "padding_value", 0.0), 0.0, "feature padding_value") + front = { + "sample_rate": _int(features, "sampling_rate"), + "n_fft": _int(features, "n_fft"), + # The symmetric window divides by win_length - 1. + "win_length": _int(features, "win_length", minimum=2), + "hop_length": _int(features, "hop_length"), + "preemphasis": _float(features, "preemphasis", low=0.0, high=1.0, high_open=True), + "log_guard": LOG_GUARD, + } + _expect(_int(features, "feature_size"), encoder["num_mel_bins"], "feature_size") + if front["win_length"] > front["n_fft"] or front["n_fft"] & (front["n_fft"] - 1): + raise ValueError("nemotron3_diarization needs a power-of-two n_fft no shorter than the window") + _expect(_int(processor, "subsampling_factor"), encoder["subsampling_factor"], + "processor subsampling_factor") + return front + + +def expected_tensors(cfg: dict) -> dict[str, tuple[int, ...]]: + """Every tensor of the checkpoint, with the shape the configuration implies.""" + hidden, inner = cfg["hidden_size"], cfg["intermediate_size"] + width, factor, speakers = cfg["head_hidden_size"], cfg["subsampling_factor"], cfg["num_speakers"] + encoder = ENCODER_PREFIX + shapes = { + f"{encoder}.embedder.projection.weight": (hidden, factor * cfg["num_mel_bins"]), + f"{encoder}.input_layer_norm.weight": (hidden,), + f"{encoder}.input_layer_norm.bias": (hidden,), + f"{encoder}.layer_norm.weight": (hidden,), + f"{encoder}.layer_norm.bias": (hidden,), + "model.proj.weight": (width, hidden), + "model.proj.bias": (width,), + "model.upsampler.conv.weight": (width * factor, width, 3), + "model.upsampler.conv.bias": (width * factor,), + "classifier.dense.weight": (width, width), + "classifier.dense.bias": (width,), + "classifier.out_proj.weight": (speakers, width), + "classifier.out_proj.bias": (speakers,), + "silence_embeds": (hidden,), + } + for index in range(cfg["num_layers"]): + prefix = f"{encoder}.layers.{index}" + for norm in ("layer_norm1", "layer_norm2"): + shapes[f"{prefix}.{norm}.weight"] = (hidden,) + shapes[f"{prefix}.{norm}.bias"] = (hidden,) + # The query, key and value projections have no bias. + for name in ("q_proj", "k_proj", "v_proj", "o_proj"): + shapes[f"{prefix}.self_attn.{name}.weight"] = (hidden, hidden) + shapes[f"{prefix}.self_attn.o_proj.bias"] = (hidden,) + shapes[f"{prefix}.mlp.fc1.weight"] = (inner, hidden) + shapes[f"{prefix}.mlp.fc1.bias"] = (inner,) + shapes[f"{prefix}.mlp.fc2.weight"] = (hidden, inner) + shapes[f"{prefix}.mlp.fc2.bias"] = (hidden,) + return shapes + + +def check_tensors(cfg: dict, tensors: dict) -> None: + """The checkpoint holds exactly the expected tensors, each float32 in its configured shape. + + ``tensors`` maps every name in the file to its safetensors dtype and shape, + read from the header before any tensor is loaded. + """ + expected = expected_tensors(cfg) + missing = sorted(set(expected) - set(tensors)) + unexpected = sorted(set(tensors) - set(expected)) + if missing or unexpected: + raise ValueError(f"nemotron3_diarization checkpoint tensors differ from the configuration: " + f"missing {missing[:3]}, unexpected {unexpected[:3]}") + for name, (dtype, shape) in sorted(tensors.items()): + if dtype != "F32": + raise ValueError(f"nemotron3_diarization checkpoint tensor {name} is {dtype}, not F32") + if tuple(shape) != expected[name]: + raise ValueError(f"nemotron3_diarization checkpoint tensor {name} has the shape " + f"{tuple(shape)}, not {expected[name]}") + + +RUNTIME_KEYS = ( + "sample_rate", "n_fft", "win_length", "hop_length", "preemphasis", "log_guard", + "num_mel_bins", "subsampling_factor", "hidden_size", "num_speakers", "chunk_length", + "chunk_left_context", "chunk_right_context", "fifo_length", "speaker_cache_update_period", + "speaker_cache_length", "silence_frames_per_speaker", "prediction_score_threshold", + "latest_frames_score_boost", "min_positive_scores", "strong_boosted_frames", + "weak_boosted_frames", "max_step_rows", +) + + +def runtime_config(cfg: dict) -> dict: + """``runtime.json``: everything the native runtime reads, nothing it re-derives.""" + values = {key: cfg[key] for key in RUNTIME_KEYS} + # Speakers are anonymous and numbered by first appearance in each input, + # spelled as the reference toolkit spells them. + values["labels"] = [f"speaker_{index}" for index in range(cfg["num_speakers"])] + return values + + +def resolve(model_dir: Path, shapes: dict) -> dict: + model = _read(model_dir, "config.json") + processor = _read(model_dir, "processor_config.json") + _expect(model.get("model_type"), "nemotron3_diarization", "model_type") + encoder = _encoder(model.get("audio_config") or {}, shapes) + head = _head(model.get("head_config") or {}, encoder, shapes) + cache = _speaker_cache(model.get("streaming_config") or {}, encoder, head) + cfg = {**encoder, **head, **cache} + cfg.update(_offline_chunking(model, encoder, cache)) + cfg.update(_front_end(processor, encoder)) + return cfg diff --git a/families/nemotron3_diarization/frontend.py b/families/nemotron3_diarization/frontend.py new file mode 100644 index 0000000000..313beb02aa --- /dev/null +++ b/families/nemotron3_diarization/frontend.py @@ -0,0 +1,67 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The constants of the log-mel front end, shipped with the bundle. + +The reference feature extractor takes its filters from ``librosa.filters.mel`` +with the Slaney scale and Slaney area normalisation, and its analysis window +from ``torch.hann_window(win_length, periodic=False)``. Both are computed here +with the same arithmetic, so the build needs neither library and the runtime +never re-derives a mel scale; ``tests/test_model.py`` holds them against the +originals. +""" + +from __future__ import annotations + +import numpy as np + +_SLANEY_SP = 200.0 / 3.0 +_SLANEY_MIN_LOG_HZ = 1000.0 +_SLANEY_MIN_LOG_MEL = _SLANEY_MIN_LOG_HZ / _SLANEY_SP +_SLANEY_LOG_STEP = np.log(6.4) / 27.0 + + +def _hz_to_mel(hz: float) -> float: + if hz >= _SLANEY_MIN_LOG_HZ: + return _SLANEY_MIN_LOG_MEL + np.log(hz / _SLANEY_MIN_LOG_HZ) / _SLANEY_LOG_STEP + return hz / _SLANEY_SP + + +def _mel_to_hz(mels: np.ndarray) -> np.ndarray: + hz = _SLANEY_SP * mels + logarithmic = mels >= _SLANEY_MIN_LOG_MEL + hz[logarithmic] = _SLANEY_MIN_LOG_HZ * np.exp( + _SLANEY_LOG_STEP * (mels[logarithmic] - _SLANEY_MIN_LOG_MEL)) + return hz + + +def mel_filters(num_mel_bins: int, n_fft: int, sample_rate: int) -> np.ndarray: + """``[num_mel_bins, n_fft // 2 + 1]`` float32 triangles over 0 Hz to Nyquist. + + The rounding follows librosa: the triangles are evaluated in float64 and + stored as float32, then scaled by the float64 area normalisation. + """ + bins = n_fft // 2 + 1 + frequencies = np.linspace(0.0, sample_rate / 2.0, bins) + edges = _mel_to_hz(np.linspace(_hz_to_mel(0.0), _hz_to_mel(sample_rate / 2.0), + num_mel_bins + 2)) + widths = np.diff(edges) + ramps = np.subtract.outer(edges, frequencies) + weights = np.zeros((num_mel_bins, bins), dtype=np.float32) + for index in range(num_mel_bins): + lower = -ramps[index] / widths[index] + upper = ramps[index + 2] / widths[index + 1] + weights[index] = np.maximum(0.0, np.minimum(lower, upper)) + weights *= (2.0 / (edges[2:num_mel_bins + 2] - edges[:num_mel_bins]))[:, np.newaxis] + return np.ascontiguousarray(weights) + + +def symmetric_hann(win_length: int) -> np.ndarray: + """``torch.hann_window(win_length, periodic=False)`` in float32. + + Symmetric, not periodic: the window touches zero at both ends. The products + and the cosine are taken in float32, the order torch evaluates them in. + """ + positions = np.arange(win_length, dtype=np.float32) + angles = positions * np.float32(2.0 * np.pi / (win_length - 1)) + return np.ascontiguousarray(np.float32(0.5) - np.float32(0.5) * np.cos(angles)) diff --git a/families/nemotron3_diarization/graph.py b/families/nemotron3_diarization/graph.py new file mode 100644 index 0000000000..dd3d33beba --- /dev/null +++ b/families/nemotron3_diarization/graph.py @@ -0,0 +1,158 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""TensorRT graph helpers for the Nemotron 3 Diarization encoder step. + +Every helper takes and returns rows ``[frames, width]`` whose frame count is +dynamic: one encoder step holds the speaker cache, the FIFO queue and one chunk +with its look-ahead, and that total changes from step to step. The arithmetic +stays in float32 throughout; the checkpoint is float32 and the speaker cache +selects frames by comparing scores, which rewards exact parity over speed. +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + + +def add_constant(network, values, dtype=np.float32): + data = np.ascontiguousarray(np.asarray(values, dtype=dtype)) + return network.add_constant(data.shape, data).get_output(0) + + +def add_elementwise(network, left, right, operation): + return network.add_elementwise(left, right, operation).get_output(0) + + +def add_sum(network, left, right): + return add_elementwise(network, left, right, trt.ElementWiseOperation.SUM) + + +def add_product(network, left, right): + return add_elementwise(network, left, right, trt.ElementWiseOperation.PROD) + + +def reshape(network, tensor, dims, transpose=None): + layer = network.add_shuffle(tensor) + layer.reshape_dims = tuple(dims) + if transpose is not None: + layer.second_transpose = tuple(transpose) + return layer.get_output(0) + + +def transpose(network, tensor, order): + layer = network.add_shuffle(tensor) + layer.first_transpose = tuple(order) + return layer.get_output(0) + + +def add_linear(network, rows, weight, bias=None): + """``rows @ weight.T + bias``, torch.nn.Linear's layout, on ``[frames, in]``.""" + out = network.add_matrix_multiply( + rows, trt.MatrixOperation.NONE, add_constant(network, weight), + trt.MatrixOperation.TRANSPOSE).get_output(0) + if bias is None: + return out + return add_sum(network, out, add_constant(network, np.asarray(bias).reshape(1, -1))) + + +def add_layer_norm(network, rows, gamma, beta, eps): + """Biased-variance layer norm over the last axis, as torch.nn.LayerNorm.""" + mean = network.add_reduce(rows, trt.ReduceOperation.AVG, 1 << 1, True).get_output(0) + centred = add_elementwise(network, rows, mean, trt.ElementWiseOperation.SUB) + square = add_product(network, centred, centred) + variance = network.add_reduce(square, trt.ReduceOperation.AVG, 1 << 1, True).get_output(0) + shifted = add_sum(network, variance, add_constant(network, np.full((1, 1), eps))) + deviation = network.add_unary(shifted, trt.UnaryOperation.SQRT).get_output(0) + normed = add_elementwise(network, centred, deviation, trt.ElementWiseOperation.DIV) + scaled = add_product(network, normed, add_constant(network, np.asarray(gamma).reshape(1, -1))) + return add_sum(network, scaled, add_constant(network, np.asarray(beta).reshape(1, -1))) + + +def add_activation(network, tensor, kind): + return network.add_activation(tensor, kind).get_output(0) + + +def leading_rows(network, table, rows_like): + """The first ``frames`` rows of a constant table, ``frames`` taken from ``rows_like``.""" + width = int(table.shape[1]) + shape = network.add_shape(rows_like).get_output(0) + frames = network.add_gather( + shape, add_constant(network, np.array([0], dtype=np.int32), np.int32), 0).get_output(0) + size = network.add_concatenation( + [frames, add_constant(network, np.array([width], dtype=np.int64), np.int64)]) + size.axis = 0 + layer = network.add_slice(table, (0, 0), (1, width), (1, 1)) + layer.set_input(2, size.get_output(0)) + return layer.get_output(0) + + +def rotary_tables(network, rows_like, cos_table, sin_table): + """Per-position RoPE factors ``[1, frames, head_dim]`` for this step's frames.""" + cos = leading_rows(network, add_constant(network, cos_table), rows_like) + sin = leading_rows(network, add_constant(network, sin_table), rows_like) + head_dim = int(cos_table.shape[1]) + return reshape(network, cos, (1, -1, head_dim)), reshape(network, sin, (1, -1, head_dim)) + + +def apply_rotary(network, heads, cos, sin, head_dim): + """``x * cos + rotate_half(x) * sin`` with ``rotate_half(x) = [-x2, x1]``. + + rotate_half is a gather plus a sign flip, so it adds no rounding of its own. + """ + half = head_dim // 2 + order = np.concatenate([np.arange(half, head_dim), np.arange(0, half)]).astype(np.int32) + rotated = network.add_gather(heads, add_constant(network, order, np.int32), 2).get_output(0) + signs = np.concatenate([-np.ones(half), np.ones(half)]).reshape(1, 1, head_dim) + rotated = add_product(network, rotated, add_constant(network, signs)) + return add_sum(network, add_product(network, heads, cos), add_product(network, rotated, sin)) + + +def add_self_attention(network, rows, weights, prefix, cfg, rope, key_bias): + """Bidirectional multi-head attention over the step's frames. + + ``key_bias`` ``[1, 1, frames]`` holds zero for a valid frame and a large + negative number for a padding frame, which the runtime supplies: padding is + excluded as a key, but is still a query, because the head's convolution + reads its hidden state. + """ + heads, head_dim = cfg["num_heads"], cfg["head_dim"] + + def split(name): + projected = add_linear(network, rows, weights[f"{prefix}.{name}.weight"]) + return reshape(network, projected, (-1, heads, head_dim), transpose=(1, 0, 2)) + + cos, sin = rope + query = apply_rotary(network, split("q_proj"), cos, sin, head_dim) + key = apply_rotary(network, split("k_proj"), cos, sin, head_dim) + value = split("v_proj") + scores = network.add_matrix_multiply( + query, trt.MatrixOperation.NONE, key, trt.MatrixOperation.TRANSPOSE).get_output(0) + scores = add_product(network, scores, add_constant(network, np.full((1, 1, 1), + head_dim**-0.5))) + scores = add_sum(network, scores, key_bias) + softmax = network.add_softmax(scores) + softmax.axes = 1 << 2 + context = network.add_matrix_multiply( + softmax.get_output(0), trt.MatrixOperation.NONE, value, + trt.MatrixOperation.NONE).get_output(0) + merged = reshape(network, transpose(network, context, (1, 0, 2)), (-1, heads * head_dim)) + return add_linear(network, merged, weights[f"{prefix}.o_proj.weight"], + weights[f"{prefix}.o_proj.bias"]) + + +def add_subpixel_upsampler(network, rows, weight, bias, factor): + """``Conv1d(width, width * factor, 3, padding=1)`` over frames, then one row per sub-frame. + + Output channel block ``s`` of frame ``t`` becomes row ``t * factor + s``, the + reference's reshape of ``[frames, width * factor]`` into ``[frames * factor, width]``. + """ + width = int(weight.shape[1]) + image = reshape(network, transpose(network, rows, (1, 0)), (1, width, 1, -1)) + kernel = np.ascontiguousarray(np.asarray(weight, dtype=np.float32)[:, :, None, :]) + conv = network.add_convolution_nd(image, int(weight.shape[0]), (1, 3), trt.Weights(kernel), + trt.Weights(np.ascontiguousarray(bias, dtype=np.float32))) + conv.padding_nd = (0, 1) + channels = reshape(network, conv.get_output(0), (int(weight.shape[0]), -1)) + return reshape(network, transpose(network, channels, (1, 0)), (-1, width)) diff --git a/families/nemotron3_diarization/model.py b/families/nemotron3_diarization/model.py new file mode 100644 index 0000000000..559e9c07f2 --- /dev/null +++ b/families/nemotron3_diarization/model.py @@ -0,0 +1,192 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build a Nemotron 3 Diarization bundle. + +Two engines. ``embedder.plan`` projects stacked mel frames to the encoder width; +``encoder.plan`` runs one step of the offline chunk loop: the speaker cache, +the FIFO queue and one chunk with its look-ahead, all already in the encoder +input space, through the 31-layer RoPE transformer and the speaker head, and +returns per-10 ms speaker logits for every row of the step. The speaker cache +lives between the two in the runtime, because it stores encoder *inputs* +selected by the head's own scores, so a step's input depends on every earlier +step's output. + +The checkpoint is float32 and is built in float32. The cache keeps the frames +it ranks highest, so a precision that moved the ranking would move which +frames the later chunks attend to, not only the logits of one chunk. +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import tensorrt as trt + +from . import config as config_module +from . import frontend, rotary +from . import graph as g + +_FAMILY = "nemotron3_diarization" +_TASK = "audio_to_timed_labels" +_ENCODER = config_module.ENCODER_PREFIX + + +def _checkpoint(model_dir: Path) -> Path: + path = Path(model_dir) / "model.safetensors" + if not path.is_file(): + raise FileNotFoundError(f"Required safetensors checkpoint is missing: {path}") + return path + + +def _tensor_headers(model_dir: Path) -> dict: + """Every tensor's safetensors dtype and shape, read from the header alone.""" + from safetensors import safe_open + + with safe_open(str(_checkpoint(model_dir)), framework="numpy") as handle: + return {key: (handle.get_slice(key).get_dtype(), tuple(handle.get_slice(key).get_shape())) + for key in handle.keys()} + + +def _load(model_dir: Path) -> dict: + """The tensors themselves; only after check_tensors has accepted their headers.""" + from safetensors import safe_open + + with safe_open(str(_checkpoint(model_dir)), framework="numpy") as handle: + return {key: np.array(handle.get_tensor(key), copy=True) for key in handle.keys()} + + +def _builder(verbose: bool): + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + config = builder.create_builder_config() + config.builder_optimization_level = 3 + # TF32 would round every matmul and convolution input to 10 mantissa bits. + config.clear_flag(trt.BuilderFlag.TF32) + return builder, network, config + + +def _serialize(builder, network, config, what: str) -> bytes: + plan = builder.build_serialized_network(network, config) + if plan is None: + raise RuntimeError(f"{_FAMILY} {what} engine build failed") + return bytes(plan) + + +def build_embedder(weights: dict, cfg: dict, *, verbose: bool = False) -> bytes: + """Stacked mel frames ``[frames, factor * mel]`` to encoder inputs ``[frames, width]``.""" + builder, network, config = _builder(verbose) + stacked = cfg["subsampling_factor"] * cfg["num_mel_bins"] + features = network.add_input("stacked_features", trt.float32, (-1, stacked)) + embeds = g.add_linear(network, features, weights[f"{_ENCODER}.embedder.projection.weight"]) + embeds.name = "inputs_embeds" + network.mark_output(embeds) + profile = builder.create_optimization_profile() + rows = cfg["max_step_rows"] + profile.set_shape("stacked_features", (1, stacked), (rows, stacked), (rows, stacked)) + config.add_optimization_profile(profile) + return _serialize(builder, network, config, "embedder") + + +def _encoder_layers(network, hidden, weights, cfg, rope, key_bias): + eps = cfg["layer_norm_eps"] + for index in range(cfg["num_layers"]): + prefix = f"{_ENCODER}.layers.{index}" + normed = g.add_layer_norm(network, hidden, weights[f"{prefix}.layer_norm1.weight"], + weights[f"{prefix}.layer_norm1.bias"], eps) + attention = g.add_self_attention(network, normed, weights, f"{prefix}.self_attn", cfg, + rope, key_bias) + hidden = g.add_sum(network, hidden, attention) + normed = g.add_layer_norm(network, hidden, weights[f"{prefix}.layer_norm2.weight"], + weights[f"{prefix}.layer_norm2.bias"], eps) + inner = g.add_linear(network, normed, weights[f"{prefix}.mlp.fc1.weight"], + weights[f"{prefix}.mlp.fc1.bias"]) + # hidden_act "gelu" is the exact erf GELU, not the tanh approximation. + inner = g.add_activation(network, inner, trt.ActivationType.GELU_ERF) + inner = g.add_linear(network, inner, weights[f"{prefix}.mlp.fc2.weight"], + weights[f"{prefix}.mlp.fc2.bias"]) + hidden = g.add_sum(network, hidden, inner) + return hidden + + +def _speaker_head(network, hidden, weights, cfg): + projected = g.add_linear(network, hidden, weights["model.proj.weight"], + weights["model.proj.bias"]) + frames = g.add_subpixel_upsampler(network, projected, weights["model.upsampler.conv.weight"], + weights["model.upsampler.conv.bias"], + cfg["subsampling_factor"]) + relu = trt.ActivationType.RELU + dense = g.add_linear(network, g.add_activation(network, frames, relu), + weights["classifier.dense.weight"], weights["classifier.dense.bias"]) + return g.add_linear(network, g.add_activation(network, dense, relu), + weights["classifier.out_proj.weight"], weights["classifier.out_proj.bias"]) + + +def build_encoder(weights: dict, cfg: dict, *, verbose: bool = False) -> bytes: + """One chunk step: ``[rows, width]`` inputs and ``[rows]`` key bias to ``[rows * factor, speakers]``.""" + builder, network, config = _builder(verbose) + width = cfg["hidden_size"] + embeds = network.add_input("inputs_embeds", trt.float32, (-1, width)) + key_bias = network.add_input("key_bias", trt.float32, (-1,)) + eps = cfg["layer_norm_eps"] + hidden = g.add_layer_norm(network, embeds, weights[f"{_ENCODER}.input_layer_norm.weight"], + weights[f"{_ENCODER}.input_layer_norm.bias"], eps) + rope = g.rotary_tables(network, embeds, *rotary.rotary_tables( + cfg["head_dim"], cfg["rope_theta"], cfg["max_step_rows"])) + bias = g.reshape(network, key_bias, (1, 1, -1)) + hidden = _encoder_layers(network, hidden, weights, cfg, rope, bias) + hidden = g.add_layer_norm(network, hidden, weights[f"{_ENCODER}.layer_norm.weight"], + weights[f"{_ENCODER}.layer_norm.bias"], eps) + logits = _speaker_head(network, hidden, weights, cfg) + logits.name = "logits" + network.mark_output(logits) + profile = builder.create_optimization_profile() + rows = cfg["max_step_rows"] + profile.set_shape("inputs_embeds", (1, width), (rows, width), (rows, width)) + profile.set_shape("key_bias", (1,), (rows,), (rows,)) + config.add_optimization_profile(profile) + return _serialize(builder, network, config, "encoder") + + +def build(request, writer) -> None: + """Build one Nemotron 3 Diarization bundle.""" + if request.dynamic_kv_cache: + raise NotImplementedError("nemotron3_diarization does not support dynamic_kv_cache") + required = ( + ("task", request.task, _TASK), + ("backend", request.backend, "trt"), + ("precision", request.precision, "fp32"), + ("tensor_parallel_size", request.tensor_parallel_size, 1), + ("context_parallel_size", request.context_parallel_size, 1), + ("max_batch_size", request.max_batch_size, 1), + # The offline loop runs any length in chunks; nothing in the bundle bounds it. + ("max_sequence_length", request.max_sequence_length, None), + ("image_height", request.image_height, None), + ("image_width", request.image_width, None), + ("video_num_frames", request.video_num_frames, None), + ("fp32_layers", request.fp32_layers, ()), + ("mtp_seq_len", request.mtp_seq_len, None), + ) + for name, actual, expected in required: + if actual != expected: + raise ValueError(f"{_FAMILY} requires {name}={expected!r}") + if request.quantization not in {None, "none"}: + raise ValueError(f"{_FAMILY} does not support quantization") + model_dir = Path(request.model_dir) + headers = _tensor_headers(model_dir) + cfg = config_module.resolve(model_dir, {name: shape for name, (_, shape) in headers.items()}) + config_module.check_tensors(cfg, headers) + weights = _load(model_dir) + verbose = bool(request.verbose) + + writer.set_header(family="nemotron3_diarization", task=request.task, backend=request.backend) + writer.add_bytes("embedder.plan", build_embedder(weights, cfg, verbose=verbose)) + writer.add_bytes("encoder.plan", build_encoder(weights, cfg, verbose=verbose)) + writer.add_bytes("mel_filters.f32", frontend.mel_filters( + cfg["num_mel_bins"], cfg["n_fft"], cfg["sample_rate"]).tobytes()) + writer.add_bytes("window.f32", frontend.symmetric_hann(cfg["win_length"]).tobytes()) + writer.add_bytes("silence_embeds.f32", + np.ascontiguousarray(weights["silence_embeds"], dtype=np.float32).tobytes()) + writer.add_json("runtime.json", config_module.runtime_config(cfg)) diff --git a/families/nemotron3_diarization/requirements.txt b/families/nemotron3_diarization/requirements.txt new file mode 100644 index 0000000000..d0229fbcb1 --- /dev/null +++ b/families/nemotron3_diarization/requirements.txt @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# The official reference of the E2E and the front-end tests. The bundle build +# needs neither: the mel filters and the window are computed in this family. +# Both are pinned to the releases the family was measured against. +transformers==5.22.2 +# The reference feature extractor builds its mel filters with librosa. +librosa==1.0.0 +# Installed on top of the base image, transformers 5.22.2 (huggingface-hub +# >=1.31.0,<3.0) would otherwise take huggingface-hub to 2.x, past the <2.0 +# that other packages of the image require; numpy stays in the image's range. +huggingface-hub==1.33.0 +numpy>=1.24,<2.5 diff --git a/families/nemotron3_diarization/rotary.py b/families/nemotron3_diarization/rotary.py new file mode 100644 index 0000000000..6c6b5d738d --- /dev/null +++ b/families/nemotron3_diarization/rotary.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The rotary position tables the encoder engine carries as constants.""" + +from __future__ import annotations + +import numpy as np + + +def inverse_frequencies(head_dim: int, theta: float) -> np.ndarray: + """``1 / theta ** (2i / head_dim)`` in float32, the reference's own rounding.""" + exponents = np.arange(0, head_dim, 2, dtype=np.float32) / np.float32(head_dim) + return np.float32(1.0) / np.power(np.float32(theta), exponents) + + +def rotary_tables(head_dim: int, theta: float, positions: int) -> tuple[np.ndarray, np.ndarray]: + """Float32 cos and sin ``[positions, head_dim]`` for positions ``0 .. positions - 1``. + + The angles are float32 products, as the reference forms them; the cosine + and sine of each float32 angle are rounded once. Positions restart at zero + every encoder step, so the table covers one step, never the recording. + """ + angles = np.arange(positions, dtype=np.float32)[:, None] * inverse_frequencies( + head_dim, theta)[None, :] + angles = np.concatenate([angles, angles], axis=1).astype(np.float64) + return np.cos(angles).astype(np.float32), np.sin(angles).astype(np.float32) diff --git a/families/nemotron3_diarization/runtime/CMakeLists.txt b/families/nemotron3_diarization/runtime/CMakeLists.txt new file mode 100644 index 0000000000..b1cb8dfa1d --- /dev/null +++ b/families/nemotron3_diarization/runtime/CMakeLists.txt @@ -0,0 +1,123 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_nemotron3_diarization SHARED + bundle.cpp + frontend.cpp + pipeline.cpp + plugin.cpp + speaker_cache.cpp +) + +target_include_directories(trtmc_model_nemotron3_diarization + PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include +) +target_include_directories(trtmc_model_nemotron3_diarization SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} +) +target_link_libraries(trtmc_model_nemotron3_diarization PRIVATE + trtmc_core + nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} +) +# The front end and the speaker-cache scores reproduce the reference's float32 +# arithmetic step by step; a fused multiply-add would round differently, and +# the cache ranks frames by those scores. +target_compile_options(trtmc_model_nemotron3_diarization PRIVATE + "$<$:-Wall;-Wextra;-Wpedantic;-ffp-contract=off>" +) +set_target_properties(trtmc_model_nemotron3_diarization PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" + INSTALL_RPATH "\$ORIGIN" +) +install(TARGETS trtmc_model_nemotron3_diarization + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) +# The library carries code transcribed from Apache-2.0 and ISC sources; ship their notices with it. +install(FILES ${PROJECT_SOURCE_DIR}/families/nemotron3_diarization/NOTICE + DESTINATION ${CMAKE_INSTALL_DATADIR}/trtmc/families/nemotron3_diarization) + +# The command-line adapter of cli.json. It runs the model through the public +# Task SDK; the model never depends on its loader. +add_library(trtmc_cli_nemotron3_diarization SHARED cli.cpp wav.cpp) +target_include_directories(trtmc_cli_nemotron3_diarization PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include +) +target_link_libraries(trtmc_cli_nemotron3_diarization PRIVATE + trtmc_c + nlohmann_json::nlohmann_json +) +target_compile_options(trtmc_cli_nemotron3_diarization PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_cli_nemotron3_diarization PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" + INSTALL_RPATH "\$ORIGIN" +) +install(TARGETS trtmc_cli_nemotron3_diarization LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(test_nemotron3_diarization_cli + ${PROJECT_SOURCE_DIR}/families/nemotron3_diarization/tests/cpp/test_cli.cpp + cli.cpp + wav.cpp + ) + target_include_directories(test_nemotron3_diarization_cli PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include + ) + target_link_libraries(test_nemotron3_diarization_cli PRIVATE + trtmc_c + nlohmann_json::nlohmann_json + ) + target_compile_options(test_nemotron3_diarization_cli PRIVATE -Wall -Wextra -Wpedantic -Werror) + add_test(NAME nemotron3_diarization_cli COMMAND test_nemotron3_diarization_cli) + set_tests_properties(nemotron3_diarization_cli PROPERTIES LABELS "cpu") + + add_executable(test_nemotron3_diarization_runtime + ${PROJECT_SOURCE_DIR}/families/nemotron3_diarization/tests/cpp/test_runtime.cpp + ) + target_include_directories(test_nemotron3_diarization_runtime PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include + ) + target_include_directories(test_nemotron3_diarization_runtime SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} + ) + target_link_libraries(test_nemotron3_diarization_runtime PRIVATE + trtmc_model_nemotron3_diarization + trtmc_core + nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} + ) + target_compile_options(test_nemotron3_diarization_runtime PRIVATE + -Wall -Wextra -Wpedantic -Werror -ffp-contract=off + ) + target_compile_definitions(test_nemotron3_diarization_runtime PRIVATE + NEMOTRON3_DIARIZATION_TEST_DATA="${PROJECT_SOURCE_DIR}/families/nemotron3_diarization/tests/data" + ) + add_test(NAME nemotron3_diarization_runtime COMMAND test_nemotron3_diarization_runtime) + set_tests_properties(nemotron3_diarization_runtime PROPERTIES LABELS "cpu") + + # Public SDK consumers for the single-device E2E. They link only the public + # C runtime, and building the CPU test builds them too. + foreach(_language IN ITEMS c cpp) + add_executable(test_nemotron3_diarization_sdk_${_language} + ${PROJECT_SOURCE_DIR}/families/nemotron3_diarization/tests/sdk_consumer.${_language} + ) + target_link_libraries(test_nemotron3_diarization_sdk_${_language} PRIVATE trtmc_c) + target_compile_options(test_nemotron3_diarization_sdk_${_language} PRIVATE + -Wall -Wextra -Wpedantic -Werror + ) + set_target_properties(test_nemotron3_diarization_sdk_${_language} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + ) + endforeach() + add_dependencies(test_nemotron3_diarization_runtime + test_nemotron3_diarization_sdk_c + test_nemotron3_diarization_sdk_cpp + ) +endif() diff --git a/families/nemotron3_diarization/runtime/bundle.cpp b/families/nemotron3_diarization/runtime/bundle.cpp new file mode 100644 index 0000000000..bd16072b8e --- /dev/null +++ b/families/nemotron3_diarization/runtime/bundle.cpp @@ -0,0 +1,199 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/nemotron3_diarization/runtime/bundle.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { +namespace { + +using Json = nlohmann::json; + +[[noreturn]] void unusable(const std::string& key, const std::string& why) { + throw std::runtime_error("nemotron3_diarization runtime.json: " + key + " " + why); +} + +// The parser keeps the last of repeated keys; the callback refuses them. +Json parse_strict(const std::vector& text) { + std::vector> keys; + const Json::parser_callback_t callback = [&keys](int, Json::parse_event_t event, Json& parsed) { + if (event == Json::parse_event_t::object_start) { + keys.emplace_back(); + } else if (event == Json::parse_event_t::object_end) { + keys.pop_back(); + } else if (event == Json::parse_event_t::key) { + const auto key = parsed.get(); + if (!keys.back().insert(key).second) + unusable(key, "appears twice"); + } + return true; + }; + return Json::parse(text.begin(), text.end(), callback); +} + +const Json& member(const Json& json, const char* key) { + const auto found = json.find(key); + if (found == json.end()) + unusable(key, "is missing"); + return *found; +} + +std::int32_t integer(const Json& json, const char* key, std::int64_t minimum) { + const auto& value = member(json, key); + if (!value.is_number_integer()) + unusable(key, "must be a JSON integer"); + constexpr auto top = std::numeric_limits::max(); + if (value.is_number_unsigned() ? value.get() > static_cast(top) + : value.get() > top) + unusable(key, "exceeds " + std::to_string(top)); + const auto number = value.get(); + if (number < minimum) + unusable(key, "is below " + std::to_string(minimum)); + return static_cast(number); +} + +float real(const Json& json, const char* key) { + const auto& value = member(json, key); + if (!value.is_number()) + unusable(key, "must be a JSON number"); + const double number = value.get(); + if (!std::isfinite(number) || std::fabs(number) > std::numeric_limits::max()) + unusable(key, "is not a finite float32"); + return static_cast(number); +} + +// The step's rows are reported as dynamic (-1) or as the rows the backend's +// buffers hold now; the profile check and each output's exact shape at run time +// pin them. Every other dimension must be the expected one. +bool same_shape(const std::vector& actual, + const std::vector& expected) { + if (actual.size() != expected.size()) + return false; + for (std::size_t i = 0; i < actual.size(); ++i) { + const bool usable = + expected[i] == kStepRows ? actual[i] == -1 || actual[i] > 0 : actual[i] == expected[i]; + if (!usable) + return false; + } + return true; +} + +std::string shape_text(const std::vector& shape) { + std::string text = "["; + for (std::size_t i = 0; i < shape.size(); ++i) + text += (i ? ", " : "") + std::to_string(shape[i]); + return text + "]"; +} + +} // namespace + +DiarizationConfig parse_runtime_json(const std::vector& text) { + const auto json = parse_strict(text); + if (!json.is_object()) + unusable("document", "must be a JSON object"); + DiarizationConfig config; + auto& front = config.front_end; + front.sample_rate = integer(json, "sample_rate", 1); + front.n_fft = integer(json, "n_fft", 2); + front.win_length = integer(json, "win_length", 2); + front.hop_length = integer(json, "hop_length", 1); + front.num_mel_bins = integer(json, "num_mel_bins", 1); + front.preemphasis = real(json, "preemphasis"); + front.log_guard = real(json, "log_guard"); + auto& cache = config.cache; + cache.num_speakers = integer(json, "num_speakers", 1); + cache.subsampling_factor = integer(json, "subsampling_factor", 1); + cache.hidden_size = integer(json, "hidden_size", 1); + cache.cache_length = integer(json, "speaker_cache_length", 1); + cache.silence_frames_per_speaker = integer(json, "silence_frames_per_speaker", 0); + cache.fifo_length = integer(json, "fifo_length", 0); + cache.update_period = integer(json, "speaker_cache_update_period", 1); + cache.score_threshold = real(json, "prediction_score_threshold"); + cache.latest_frames_boost = real(json, "latest_frames_score_boost"); + cache.min_positive_scores = integer(json, "min_positive_scores", 0); + cache.strong_boosted_frames = integer(json, "strong_boosted_frames", 0); + cache.weak_boosted_frames = integer(json, "weak_boosted_frames", 0); + config.chunk_length = integer(json, "chunk_length", 1); + config.chunk_left_context = integer(json, "chunk_left_context", 0); + config.chunk_right_context = integer(json, "chunk_right_context", 0); + config.max_step_rows = integer(json, "max_step_rows", 1); + const auto& labels = member(json, "labels"); + if (!labels.is_array()) + unusable("labels", "must be an array of strings"); + std::set seen; + for (const auto& label : labels) { + if (!label.is_string() || label.get_ref().empty()) + unusable("labels", "must name every speaker with a nonempty string"); + if (!seen.insert(label.get()).second) + unusable("labels", "repeat a name"); + config.labels.push_back(label.get()); + } + return config; +} + +void check_float_section(std::uint64_t length, std::size_t count, const std::string& name) { + constexpr auto width = static_cast(sizeof(float)); + if (static_cast(count) > std::numeric_limits::max() / width || + length != static_cast(count) * width) + throw std::runtime_error("nemotron3_diarization bundle section " + name + " has " + + std::to_string(length) + " bytes, not " + std::to_string(count) + + " float32 values"); +} + +void check_section_limit(std::uint64_t length, std::uint64_t limit, const std::string& name) { + if (length > limit) + throw std::runtime_error("nemotron3_diarization bundle section " + name + " has " + + std::to_string(length) + " bytes, more than " + + std::to_string(limit)); +} + +void check_engine_io(const EngineIo& io, const std::vector& inputs, + const std::vector& outputs, std::int64_t max_step_rows, + const std::string& engine) { + const auto fail = [&engine](const std::string& why) { + throw std::runtime_error("nemotron3_diarization " + engine + " " + why); + }; + for (const bool input : {true, false}) { + const auto& specs = input ? inputs : outputs; + const std::string kind = input ? "input" : "output"; + const auto count = + std::count_if(io.tensors.begin(), io.tensors.end(), + [input](const TensorInfo& tensor) { return tensor.is_input == input; }); + if (static_cast(count) != specs.size()) + fail("has " + std::to_string(count) + " " + kind + "s, not " + + std::to_string(specs.size())); + for (const auto& spec : specs) { + const auto found = + std::find_if(io.tensors.begin(), io.tensors.end(), [&](const TensorInfo& tensor) { + return tensor.is_input == input && tensor.name == spec.name; + }); + if (found == io.tensors.end()) + fail("lacks the " + kind + " " + spec.name); + if (found->dtype != DType::kFloat32) + fail(kind + " " + spec.name + " is not float32"); + if (!same_shape(found->shape, spec.shape)) + fail(kind + " " + spec.name + " has the shape " + shape_text(found->shape) + + ", not " + shape_text(spec.shape)); + } + } + if (io.profiles < 1) + fail("has no optimization profile"); + for (const auto& spec : inputs) { + const auto found = std::find_if(io.input_rows.begin(), io.input_rows.end(), + [&](const auto& rows) { return rows.first == spec.name; }); + if (found == io.input_rows.end() || found->second.first > 1 || + found->second.second < max_step_rows) + fail("input " + spec.name + " does not accept 1 to " + std::to_string(max_step_rows) + + " rows in profile 0"); + } +} + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/bundle.h b/families/nemotron3_diarization/runtime/bundle.h new file mode 100644 index 0000000000..150ec25fbd --- /dev/null +++ b/families/nemotron3_diarization/runtime/bundle.h @@ -0,0 +1,54 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/nemotron3_diarization/runtime/pipeline.h" +#include "trtmc/runtime/tensor.h" + +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { + +// runtime.json as the family's build writes it, checked before any value is +// used: no duplicate key; counts are JSON integers within their range, rates +// and constants finite JSON numbers, labels distinct nonempty strings. Nothing +// is coerced. The loader attaches the bundle's float sections afterwards. +DiarizationConfig parse_runtime_json(const std::vector& text); + +// Section lengths, from the bundle's section table, checked before a section is +// read: a float section holds exactly `count` float32 values, any other section +// at most `limit` bytes. +void check_float_section(std::uint64_t length, std::size_t count, const std::string& name); +void check_section_limit(std::uint64_t length, std::uint64_t limit, const std::string& name); + +// The dynamic first dimension of a tensor: the rows of one step (for the +// logits, those rows times the subsampling factor). +inline constexpr std::int64_t kStepRows = -1; + +struct TensorSpec { + std::string name; + std::vector shape; +}; + +// What a loaded engine reports: its tensors, and for each input the first +// dimension's [min, max] in optimization profile 0. +struct EngineIo { + std::vector tensors; + std::vector>> input_rows; + std::int32_t profiles{0}; +}; + +// The engine has exactly these float32 inputs and outputs with these shapes (a +// kStepRows dimension may be reported as -1 or as the rows a buffer holds), and +// its profile 0 accepts every step from one row to max_step_rows. +void check_engine_io(const EngineIo& io, const std::vector& inputs, + const std::vector& outputs, std::int64_t max_step_rows, + const std::string& engine); + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/cli.cpp b/families/nemotron3_diarization/runtime/cli.cpp new file mode 100644 index 0000000000..5e40b387ba --- /dev/null +++ b/families/nemotron3_diarization/runtime/cli.cpp @@ -0,0 +1,117 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Family-owned command line: `trtmc nemotron3_diarization diarize BUNDLE +// --audio WAV`. The handler runs the public audio_to_timed_labels Task, so the +// shared contract checks every result it prints. +#include "trtmc/internal/cli.h" + +#include "families/nemotron3_diarization/runtime/wav.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr std::string_view kFamily = "nemotron3_diarization"; + +const char* score_kind(std::uint32_t kind) { + switch (kind) { + case 0: + return "none"; + case TRTMC_SCORE_LOGIT: + return "logit"; + case TRTMC_SCORE_PROBABILITY: + return "probability"; + case TRTMC_SCORE_UNBOUNDED: + return "unbounded"; + default: + throw std::runtime_error("timed labels have an unknown frame score kind"); + } +} + +nlohmann::json timed_labels_json(const trtmc::TimedLabelsResult& result) { + std::vector labels; + for (const auto label : result.labels()) + labels.emplace_back(label); + auto intervals = nlohmann::json::array(); + for (const auto& interval : result.intervals()) + intervals.push_back({{"start_seconds", interval.start_seconds}, + {"end_seconds", interval.end_seconds}, + {"label", interval.label}}); + // The Task guarantees rows * columns values, every one finite. + const auto scores = result.frame_scores(); + auto rows = nlohmann::json::array(); + for (std::uint64_t row = 0; row < scores.rows; ++row) { + const float* first = scores.values.data() + row * scores.columns; + rows.push_back(std::vector(first, first + scores.columns)); + } + return {{"task", std::string(trtmc::AudioToTimedLabels::kTask)}, + {"labels", labels}, + {"vocabulary_id", std::string(result.vocabulary_id())}, + {"intervals", std::move(intervals)}, + {"frame_seconds", result.frame_seconds()}, + {"score_kind", score_kind(result.score_kind())}, + {"frame_scores", std::move(rows)}, + {"setup_ms", result.setup_ms()}, + {"inference_ms", result.inference_ms()}}; +} + +nlohmann::json diarize(const nlohmann::json& values, const char* default_runtime_root) { + const auto bundle = values.at("bundle").get(); + // Check identity before loading: this command must not run another + // family's bundle just because it serves the same Task. + if (trtmc::Bundle::open(bundle).info().family != kFamily) + throw std::invalid_argument("diarize requires a nemotron3_diarization bundle"); + const auto audio = + trtmc::nemotron3_diarization::read_wav(values.at("audio").get()); + trtmc::Config config; + // Absent, the threshold keeps the default the family declares. + if (values.contains("threshold")) + config.add("threshold", values.at("threshold").get()); + trtmc::LoadOptions options; + options.runtime_root = values.value("runtime_root", std::string(default_runtime_root)); + const auto model = trtmc::Model::load(bundle, options); + const auto task = model.task(); + const trtmc::AudioToTimedLabelsRequest request{ + {{audio.samples.data(), audio.samples.size()}, audio.sample_rate, audio.channels}}; + return timed_labels_json(task.run(request, config)); +} + +} // namespace + +extern "C" int trtmc_family_cli_v1(const char* handler, const char* values_json, + const char* default_runtime_root, void* context, + trtmc_cli_write_v1 output, trtmc_cli_write_v1 error) { + if (error == nullptr) + return 1; + auto fail = [&](const std::string& reason) { + const auto message = "Error: " + reason + '\n'; + error(context, message.data(), message.size()); + return 1; + }; + try { + if (handler == nullptr || values_json == nullptr || default_runtime_root == nullptr || + output == nullptr) + return fail("the CLI host passed an incomplete call"); + if (std::string_view(handler) != "diarize") + return fail("unknown Nemotron 3 Diarization command: " + std::string(handler)); + const auto text = + diarize(nlohmann::json::parse(values_json), default_runtime_root).dump() + '\n'; + output(context, text.data(), text.size()); + return 0; + } catch (const std::exception& exception) { + return fail(exception.what()); + } catch (...) { + return fail("unknown failure"); + } +} diff --git a/families/nemotron3_diarization/runtime/frontend.cpp b/families/nemotron3_diarization/runtime/frontend.cpp new file mode 100644 index 0000000000..6c3ea91811 --- /dev/null +++ b/families/nemotron3_diarization/runtime/frontend.cpp @@ -0,0 +1,166 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/nemotron3_diarization/runtime/frontend.h" + +#include +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { +namespace { + +void require(bool condition, const char* message) { + if (!condition) + throw std::runtime_error(std::string("nemotron3_diarization front end: ") + message); +} + +bool is_power_of_two(std::int32_t value) { + return value > 0 && (value & (value - 1)) == 0; +} + +} // namespace + +LogMelFrontEnd::LogMelFrontEnd(FrontEndConfig config) : config_(std::move(config)) { + const auto& c = config_; + require(c.sample_rate > 0 && c.hop_length > 0 && c.num_mel_bins > 0, "geometry is unusable"); + require(is_power_of_two(c.n_fft) && c.win_length > 1 && c.win_length <= c.n_fft, + "n_fft must be a power of two no shorter than the window"); + require(c.window.size() == static_cast(c.win_length), + "window length does not match win_length"); + const auto bins = static_cast(c.n_fft / 2 + 1); + require(c.mel_filters.size() == static_cast(c.num_mel_bins) * bins, + "mel filter bank does not match the spectrum"); + require(c.preemphasis >= 0.0F && c.preemphasis < 1.0F && std::isfinite(c.log_guard) && + c.log_guard > 0.0F, + "constants are unusable"); + + // torch.stft centres a window shorter than the transform inside it. + const auto n_fft = static_cast(c.n_fft); + const auto offset = static_cast((c.n_fft - c.win_length) / 2); + padded_window_.assign(n_fft, 0.0F); + for (std::size_t i = 0; i < c.window.size(); ++i) + padded_window_[offset + i] = c.window[i]; + + std::size_t bits = 0; + while ((std::size_t{1} << bits) < n_fft) + ++bits; + bit_reversed_.resize(n_fft); + for (std::size_t i = 0; i < n_fft; ++i) { + std::size_t reversed = 0; + for (std::size_t bit = 0; bit < bits; ++bit) + reversed |= ((i >> bit) & 1U) << (bits - 1 - bit); + bit_reversed_[i] = reversed; + } + twiddle_.resize(n_fft / 2); + for (std::size_t k = 0; k < twiddle_.size(); ++k) { + const double angle = -2.0 * M_PI * static_cast(k) / static_cast(n_fft); + twiddle_[k] = {std::cos(angle), std::sin(angle)}; + } + + // The triangles are sparse; multiplying only their nonzero span gives the + // same sums, since every skipped product is an exact zero. + filter_begin_.assign(static_cast(c.num_mel_bins), 0); + filter_end_.assign(static_cast(c.num_mel_bins), 0); + for (std::size_t mel = 0; mel < filter_begin_.size(); ++mel) { + const float* row = c.mel_filters.data() + mel * bins; + std::size_t begin = bins, end = 0; + for (std::size_t bin = 0; bin < bins; ++bin) { + if (row[bin] != 0.0F) { + begin = std::min(begin, bin); + end = bin + 1; + } + } + filter_begin_[mel] = begin < end ? begin : 0; + filter_end_[mel] = end; + } +} + +void LogMelFrontEnd::power_spectrum(const std::vector& padded, std::int64_t start, + std::vector>& buffer, + std::vector& power) const { + const std::size_t n = buffer.size(); + for (std::size_t i = 0; i < n; ++i) { + const float sample = padded[static_cast(start) + i] * padded_window_[i]; + buffer[bit_reversed_[i]] = {static_cast(sample), 0.0}; + } + for (std::size_t length = 2; length <= n; length <<= 1) { + const std::size_t half = length / 2, stride = n / length; + for (std::size_t base = 0; base < n; base += length) { + for (std::size_t k = 0; k < half; ++k) { + const auto even = buffer[base + k]; + const auto odd = buffer[base + k + half] * twiddle_[k * stride]; + buffer[base + k] = even + odd; + buffer[base + k + half] = even - odd; + } + } + } + // The reference holds the transform as complex64, takes |X| with sqrt of + // the float32 sum of squares, and squares that again; each step rounds. + for (std::size_t bin = 0; bin < power.size(); ++bin) { + const auto real = static_cast(buffer[bin].real()); + const auto imaginary = static_cast(buffer[bin].imag()); + const float sum = real * real + imaginary * imaginary; + const float magnitude = std::sqrt(sum); + power[bin] = magnitude * magnitude; + } +} + +LogMel LogMelFrontEnd::compute(const float* mono, std::int64_t count) const { + const auto& c = config_; + require(mono != nullptr || count == 0, "audio pointer is null"); + LogMel result; + result.valid_frames = count / c.hop_length; + result.frames = 1 + count / c.hop_length; + const auto mels = static_cast(c.num_mel_bins); + result.values.assign(static_cast(result.frames) * mels, 0.0F); + + // Pre-emphasis first, then the centring pad of n_fft / 2 zeros at both ends. + const auto pad = static_cast(c.n_fft / 2); + std::vector padded(static_cast(count) + 2 * pad, 0.0F); + for (std::int64_t i = 0; i < count; ++i) { + float value = mono[i]; + if (i > 0) { + const float previous = c.preemphasis * mono[i - 1]; + value = mono[i] - previous; + } + padded[pad + static_cast(i)] = value; + } + + std::vector> buffer(static_cast(c.n_fft)); + std::vector power(static_cast(c.n_fft / 2 + 1)); + const std::size_t bins = power.size(); + // Frames past the valid count are padding: the reference zeroes them. + for (std::int64_t frame = 0; frame < result.valid_frames; ++frame) { + power_spectrum(padded, frame * c.hop_length, buffer, power); + float* out = result.values.data() + static_cast(frame) * mels; + for (std::size_t mel = 0; mel < mels; ++mel) { + const float* row = c.mel_filters.data() + mel * bins; + double total = 0.0; + for (std::size_t bin = filter_begin_[mel]; bin < filter_end_[mel]; ++bin) + total += static_cast(row[bin]) * static_cast(power[bin]); + out[mel] = std::log(static_cast(total) + c.log_guard); + } + } + return result; +} + +std::vector mix_to_mono(const float* samples, std::size_t count, std::uint32_t channels) { + if (channels <= 1) + return std::vector(samples, samples + count); + const std::size_t frames = count / channels; + std::vector mono(frames); + for (std::size_t frame = 0; frame < frames; ++frame) { + double total = 0.0; + for (std::uint32_t channel = 0; channel < channels; ++channel) + total += samples[frame * channels + channel]; + mono[frame] = static_cast(total / channels); + } + return mono; +} + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/frontend.h b/families/nemotron3_diarization/runtime/frontend.h new file mode 100644 index 0000000000..cf94abb69d --- /dev/null +++ b/families/nemotron3_diarization/runtime/frontend.h @@ -0,0 +1,61 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { + +// The log-mel front end of the reference feature extractor, with its window +// and mel filters computed by the family's Python side and carried in the +// bundle. Nothing here normalises the features: the reference does not. +struct FrontEndConfig { + std::int32_t sample_rate{16000}; + std::int32_t n_fft{512}; + std::int32_t win_length{400}; + std::int32_t hop_length{160}; + std::int32_t num_mel_bins{128}; + float preemphasis{0.97F}; + float log_guard{5.9604644775390625e-08F}; // 2**-24 + std::vector window; // [win_length], symmetric Hann + std::vector mel_filters; // [num_mel_bins, n_fft / 2 + 1], row-major +}; + +// Row-major [frames, num_mel_bins]. The analysis windows are centred and the +// signal zero-padded by n_fft / 2 at both ends, so there are 1 + L / hop frames +// for L samples, of which the first L / hop are valid; the rest are zero. +struct LogMel { + std::vector values; + std::int64_t frames{0}; + std::int64_t valid_frames{0}; +}; + +class LogMelFrontEnd { + public: + explicit LogMelFrontEnd(FrontEndConfig config); + + LogMel compute(const float* mono, std::int64_t count) const; + const FrontEndConfig& config() const noexcept { return config_; } + + private: + void power_spectrum(const std::vector& padded, std::int64_t start, + std::vector>& buffer, std::vector& power) const; + + FrontEndConfig config_; + std::vector padded_window_; // [n_fft], the window centred in the transform + std::vector bit_reversed_; // [n_fft] + std::vector> twiddle_; // [n_fft / 2] + std::vector filter_begin_, filter_end_; // nonzero bins of each mel filter +}; + +// Interleaved channels averaged to mono, as the reference feature extractor +// does for multichannel input. One channel is copied through unchanged. +std::vector mix_to_mono(const float* samples, std::size_t count, std::uint32_t channels); + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/pipeline.cpp b/families/nemotron3_diarization/runtime/pipeline.cpp new file mode 100644 index 0000000000..92a8a93ccc --- /dev/null +++ b/families/nemotron3_diarization/runtime/pipeline.cpp @@ -0,0 +1,260 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/nemotron3_diarization/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { +namespace { + +using Clock = std::chrono::steady_clock; + +// Key bias of a padding frame: it is excluded as a key and stays a query, +// because the speaker head's convolution reads its neighbours. Finite, and +// exp() of it is exactly zero. +constexpr float kMaskedKey = -1.0e30F; + +const internal::ConfigField kFields[] = { + {"threshold", internal::ConfigKind::F64, internal::ConfigValue{0.5}, + "Speaker activity probability above which a 10 ms frame counts as that speaker's speech."}}; + +double elapsed_ms(Clock::time_point since) { + return std::chrono::duration(Clock::now() - since).count(); +} + +float threshold(internal::ConfigView supplied) { + const double value = *internal::config_get(supplied, kFields, "threshold"); + if (!std::isfinite(value) || value <= 0.0 || value >= 1.0) + throw internal::ConfigError("threshold must lie strictly between 0 and 1"); + // The comparison runs in float32, where 1e-300 and 0.999999999 become 0 and 1. + const auto converted = static_cast(value); + if (converted <= 0.0F || converted >= 1.0F) + throw internal::ConfigError("threshold must lie strictly between 0 and 1 in float32"); + return converted; +} + +// The exact shape, not only the element count: a transposed tensor would +// otherwise be read as frame-major scores. +const float* float_output(const TensorMap& outputs, const char* name, + const std::vector& shape) { + const auto found = outputs.find(name); + if (found == outputs.end() || found->second.data == nullptr || + found->second.dtype != DType::kFloat32 || found->second.shape != shape) + throw std::runtime_error(std::string("nemotron3_diarization engine returned an unusable ") + + name); + const auto* values = static_cast(found->second.data); + for (std::size_t i = 0; i < found->second.numel(); ++i) + if (!std::isfinite(values[i])) + throw std::runtime_error( + std::string("nemotron3_diarization engine returned a non-finite ") + name); + return values; +} + +} // namespace + +bool speaker_active(float logit, float threshold) { + const float probability = 1.0F / (1.0F + std::exp(-logit)); + return probability > threshold; +} + +std::vector active_intervals(const std::vector& logits, + std::int64_t frames, std::int64_t speakers, + float threshold, std::int32_t hop_length, + std::int32_t sample_rate) { + struct Run { + std::int64_t start, end, speaker; + }; + std::vector runs; + for (std::int64_t speaker = 0; speaker < speakers; ++speaker) { + std::int64_t start = -1; + for (std::int64_t frame = 0; frame <= frames; ++frame) { + const bool active = + frame < frames && speaker_active(logits[frame * speakers + speaker], threshold); + if (active && start < 0) + start = frame; + if (!active && start >= 0) { + runs.push_back({start, frame, speaker}); + start = -1; + } + } + } + std::sort(runs.begin(), runs.end(), [](const Run& a, const Run& b) { + return a.start != b.start ? a.start < b.start : a.speaker < b.speaker; + }); + // Frame f starts at f * hop samples; the division is rounded once, so a + // boundary lands on the nearest double to its decimal value (0.03, 15.43). + const auto seconds = [&](std::int64_t frame) { + return static_cast(frame * hop_length) / static_cast(sample_rate); + }; + std::vector intervals; + intervals.reserve(runs.size()); + for (const auto& run : runs) + intervals.push_back( + {seconds(run.start), seconds(run.end), static_cast(run.speaker)}); + return intervals; +} + +DiarizationPipeline::DiarizationPipeline(std::unique_ptr embedder, + std::unique_ptr encoder, + DiarizationConfig config) + : embedder_(std::move(embedder)), encoder_(std::move(encoder)), config_(std::move(config)), + front_end_(config_.front_end) { + if (!embedder_ || !encoder_) + throw std::runtime_error("nemotron3_diarization pipeline is missing an engine"); + if (config_.labels.size() != static_cast(config_.cache.num_speakers)) + throw std::runtime_error("nemotron3_diarization needs one label per speaker"); + const std::int64_t longest_step = static_cast(config_.cache.cache_length) + + config_.cache.fifo_length + config_.chunk_left_context + + config_.chunk_length + config_.chunk_right_context; + if (config_.chunk_length <= 0 || config_.chunk_left_context < 0 || + config_.chunk_right_context < 0 || config_.max_step_rows < longest_step) + throw std::runtime_error("nemotron3_diarization chunking does not fit one encoder step"); + // The speaker cache checks its policy when it is built; build one now, so + // that a bundle it would refuse is refused at load, before any request. + (void)SpeakerCache(config_.cache, config_.silence_embedding); +} + +std::vector DiarizationPipeline::task_bindings() { + return {internal::bind(*this, kFields)}; +} + +std::vector DiarizationPipeline::embed(const LogMel& features, std::int64_t& rows) { + const auto factor = static_cast(config_.cache.subsampling_factor); + const auto mels = static_cast(config_.front_end.num_mel_bins); + const auto width = static_cast(config_.cache.hidden_size); + // Groups of `factor` frames, the last one completed with zero frames. + rows = (features.frames + factor - 1) / factor; + std::vector stacked(static_cast(rows * factor * mels), 0.0F); + std::copy(features.values.begin(), features.values.end(), stacked.begin()); + + std::vector embeddings(static_cast(rows * width)); + const std::int64_t block = config_.max_step_rows; + for (std::int64_t first = 0; first < rows; first += block) { + const std::int64_t count = std::min(block, rows - first); + Tensor input{ + stacked.data() + first * factor * mels, {count, factor * mels}, DType::kFloat32}; + const auto outputs = embedder_->forward({{"stacked_features", input}}); + const auto* out = float_output(outputs, "inputs_embeds", {count, width}); + std::memcpy(embeddings.data() + first * width, out, + static_cast(count * width) * sizeof(float)); + } + return embeddings; +} + +std::vector DiarizationPipeline::diarize(const std::vector& embeddings, + std::int64_t rows, + const std::vector& valid_rows, + std::int64_t frames) { + const auto width = static_cast(config_.cache.hidden_size); + const auto factor = static_cast(config_.cache.subsampling_factor); + const auto speakers = static_cast(config_.cache.num_speakers); + SpeakerCache cache(config_.cache, config_.silence_embedding); + std::vector logits; + logits.reserve(static_cast(rows * factor * speakers)); + std::vector input, bias; + std::vector valid; + for (std::int64_t start = 0; start < rows; start += config_.chunk_length) { + const std::int64_t end = std::min(start + config_.chunk_length, rows); + const std::int64_t first = std::max(start - config_.chunk_left_context, 0); + const std::int64_t last = std::min(end + config_.chunk_right_context, rows); + const std::int64_t cached = cache.cached_rows(); + const std::int64_t step = cached + (last - first); + if (step > config_.max_step_rows) + throw std::runtime_error("nemotron3_diarization step exceeds the engine profile"); + + input.resize(static_cast(step * width)); + cache.copy_cached_rows(input.data()); + std::memcpy(input.data() + cached * width, embeddings.data() + first * width, + static_cast((last - first) * width) * sizeof(float)); + valid.assign(static_cast(cached), 1U); + valid.insert(valid.end(), valid_rows.begin() + first, valid_rows.begin() + last); + bias.resize(valid.size()); + for (std::size_t i = 0; i < valid.size(); ++i) + bias[i] = valid[i] ? 0.0F : kMaskedKey; + + const auto outputs = + encoder_->forward({{"inputs_embeds", Tensor{input.data(), {step, width}}}, + {"key_bias", Tensor{bias.data(), {step}}}}); + // Every logit of the step is checked before the cache pools and ranks + // them, the look-ahead and cached rows included. + const auto* step_logits = float_output(outputs, "logits", {step * factor, speakers}); + cache.update(input.data(), step, step_logits, valid, end - start, start - first); + // Only the chunk's own frames are scored here; its look-ahead opens the next chunk. + const std::int64_t begin = (cached + start - first) * factor * speakers; + logits.insert(logits.end(), step_logits + begin, + step_logits + begin + (end - start) * factor * speakers); + } + // The last stacked group may end in padding frames past the spectrogram. + logits.resize(static_cast(frames * speakers)); + return logits; +} + +internal::TimedLabelsResult +DiarizationPipeline::run(const internal::AudioToTimedLabelsRequest& request, + internal::ConfigView supplied) { + const float activity_threshold = threshold(supplied); + const auto& audio = request.audio; + const auto rate = + audio.sample_rate.value_or(static_cast(config_.front_end.sample_rate)); + // Framing and mel band edges are fixed to the training rate; the family + // does not resample. + if (rate != static_cast(config_.front_end.sample_rate)) + throw std::invalid_argument("nemotron3_diarization requires " + + std::to_string(config_.front_end.sample_rate) + + " Hz audio, not " + std::to_string(rate) + " Hz"); + for (const float sample : audio.samples) + if (!std::isfinite(sample)) + throw std::invalid_argument("nemotron3_diarization audio samples must be finite"); + const auto mono = mix_to_mono(audio.samples.data(), audio.samples.size(), audio.channels); + if (mono.size() < static_cast(config_.front_end.hop_length)) + throw std::invalid_argument( + "nemotron3_diarization needs at least one 10 ms frame of audio"); + + const auto setup = Clock::now(); + const auto features = front_end_.compute(mono.data(), static_cast(mono.size())); + // Finite samples can still overflow float32 in the pre-emphasis or the + // power spectrum; such features never reach an engine. + for (const float value : features.values) + if (!std::isfinite(value)) + throw std::invalid_argument( + "nemotron3_diarization audio overflows the float32 front end"); + const auto factor = static_cast(config_.cache.subsampling_factor); + std::int64_t rows = 0; + const auto embeddings = embed(features, rows); + // An encoder frame is valid when its first spectrogram frame is. + std::vector valid_rows(static_cast(rows)); + for (std::int64_t row = 0; row < rows; ++row) + valid_rows[static_cast(row)] = row * factor < features.valid_frames; + const double setup_ms = elapsed_ms(setup); + + const auto inference = Clock::now(); + auto logits = diarize(embeddings, rows, valid_rows, features.frames); + const auto speakers = static_cast(config_.cache.num_speakers); + // Frames past the audio are padding; the result covers the audio only. + logits.resize(static_cast(features.valid_frames * speakers)); + + internal::TimedLabelsResult result; + result.intervals = + active_intervals(logits, features.valid_frames, speakers, activity_threshold, + config_.front_end.hop_length, config_.front_end.sample_rate); + result.labels = config_.labels; + result.frame_scores = std::move(logits); + result.frame_count = static_cast(features.valid_frames); + result.frame_seconds = static_cast(config_.front_end.hop_length) / + static_cast(config_.front_end.sample_rate); + result.score_kind = internal::ScoreKind::Logit; + result.setup_ms = setup_ms; + result.inference_ms = elapsed_ms(inference); + return result; +} + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/pipeline.h b/families/nemotron3_diarization/runtime/pipeline.h new file mode 100644 index 0000000000..7561a45d8a --- /dev/null +++ b/families/nemotron3_diarization/runtime/pipeline.h @@ -0,0 +1,70 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/nemotron3_diarization/runtime/frontend.h" +#include "families/nemotron3_diarization/runtime/speaker_cache.h" +#include "trtmc/internal/audio.h" +#include "trtmc/internal/model.h" +#include "trtmc/runtime/trt_module.h" + +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { + +struct DiarizationConfig { + FrontEndConfig front_end; + SpeakerCachePolicy cache; // with the offline FIFO sizes + std::int32_t chunk_length{340}; + std::int32_t chunk_left_context{0}; + std::int32_t chunk_right_context{40}; + std::int32_t max_step_rows{684}; + std::vector labels; + std::vector silence_embedding; +}; + +// Speaker activity of one 10 ms frame and speaker: the logistic of its logit +// above the threshold, both in float32 as the reference compares them. +bool speaker_active(float logit, float threshold); + +// Labelled intervals from row-major [frames, speakers] logits, frame f covering +// [f * hop, (f + 1) * hop) samples: one interval per run of active frames, +// ordered by start, then speaker. +std::vector active_intervals(const std::vector& logits, + std::int64_t frames, std::int64_t speakers, + float threshold, std::int32_t hop_length, + std::int32_t sample_rate); + +// Whole-recording diarization, the reference's offline mode: the recording is +// cut into chunks of encoder frames, each run with its look-ahead behind the +// speaker cache and FIFO queue that the earlier chunks left. +class DiarizationPipeline final : public internal::IModel, public internal::IAudioToTimedLabels { + public: + DiarizationPipeline(std::unique_ptr embedder, std::unique_ptr encoder, + DiarizationConfig config); + + const char* task() const noexcept override { + return internal::IAudioToTimedLabels::kTask.data(); + } + std::vector task_bindings() override; + internal::TimedLabelsResult run(const internal::AudioToTimedLabelsRequest& request, + internal::ConfigView config) override; + + private: + std::vector embed(const LogMel& features, std::int64_t& rows); + std::vector diarize(const std::vector& embeddings, std::int64_t rows, + const std::vector& valid_rows, std::int64_t frames); + + std::unique_ptr embedder_; + std::unique_ptr encoder_; + DiarizationConfig config_; + LogMelFrontEnd front_end_; +}; + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/plugin.cpp b/families/nemotron3_diarization/runtime/plugin.cpp new file mode 100644 index 0000000000..6f18779e3a --- /dev/null +++ b/families/nemotron3_diarization/runtime/plugin.cpp @@ -0,0 +1,129 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/nemotron3_diarization/runtime/bundle.h" +#include "families/nemotron3_diarization/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { +namespace { + +// runtime.json holds a few hundred bytes of geometry and policy. +constexpr std::uint64_t kRuntimeJsonLimit = 1 << 20; + +const BundleSectionInfo& section_info(const BundleReader& bundle, const char* name) { + const auto* section = bundle.find_section(name); + if (section == nullptr || section->length == 0) + throw std::runtime_error("nemotron3_diarization bundle section is missing or empty: " + + std::string(name)); + return *section; +} + +std::vector require_section(const BundleReader& bundle, const char* name) { + (void)section_info(bundle, name); + return bundle.read_section(name); +} + +std::vector float_section(const BundleReader& bundle, const char* name, + std::size_t expected) { + // The section table's length is checked before the section is read. + check_float_section(section_info(bundle, name).length, expected, name); + const auto raw = bundle.read_section(name); + if (raw.size() != expected * sizeof(float)) + throw std::runtime_error("nemotron3_diarization bundle section has the wrong length: " + + std::string(name)); + std::vector values(expected); + std::memcpy(values.data(), raw.data(), raw.size()); + for (const float value : values) + if (!std::isfinite(value)) + throw std::runtime_error("nemotron3_diarization bundle section is not finite: " + + std::string(name)); + return values; +} + +DiarizationConfig load_config(const BundleReader& bundle) { + check_section_limit(section_info(bundle, "runtime.json").length, kRuntimeJsonLimit, + "runtime.json"); + auto config = parse_runtime_json(bundle.read_section("runtime.json")); + auto& front = config.front_end; + front.window = float_section(bundle, "window.f32", static_cast(front.win_length)); + front.mel_filters = float_section(bundle, "mel_filters.f32", + static_cast(front.num_mel_bins) * + (static_cast(front.n_fft) / 2 + 1)); + config.silence_embedding = float_section(bundle, "silence_embeds.f32", + static_cast(config.cache.hidden_size)); + return config; +} + +EngineIo describe(const ITrtModule& engine) { + EngineIo io; + const auto inputs = engine.input_info(); + for (auto tensor : inputs) { + tensor.is_input = true; + io.tensors.push_back(std::move(tensor)); + } + for (auto tensor : engine.output_info()) { + tensor.is_input = false; + io.tensors.push_back(std::move(tensor)); + } + io.profiles = engine.optimization_profile_count(); + if (io.profiles < 1) + return io; + for (const auto& tensor : inputs) { + const auto low = engine.input_profile_shape(tensor.name, 0, ProfileShapeSelector::kMin); + const auto high = engine.input_profile_shape(tensor.name, 0, ProfileShapeSelector::kMax); + if (!low.empty() && !high.empty()) + io.input_rows.push_back({tensor.name, {low.front(), high.front()}}); + } + return io; +} + +std::unique_ptr load_engine(const FamilyContext& context, const char* section, + const std::vector& inputs, + const std::vector& outputs, + std::int64_t max_step_rows) { + const auto plan = require_section(context.reader, section); + ModuleCreateOptions options{}; + auto engine = context.backend.create_module(plan.data(), plan.size(), options); + if (!engine || !engine->ok()) + throw std::runtime_error("nemotron3_diarization engine failed to load: " + + std::string(section)); + check_engine_io(describe(*engine), inputs, outputs, max_step_rows, section); + return engine; +} + +} // namespace +} // namespace trtmc::nemotron3_diarization + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + using namespace trtmc::nemotron3_diarization; + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("nemotron3_diarization does not support --kv-cache-size"); + const auto& task = context.reader.info().task; + if (task != trtmc::internal::IAudioToTimedLabels::kTask) + throw std::runtime_error("nemotron3_diarization bundle declares an unsupported task: " + + task); + auto config = load_config(context.reader); + const std::int64_t width = config.cache.hidden_size; + const std::int64_t stacked = + static_cast(config.cache.subsampling_factor) * config.front_end.num_mel_bins; + const std::int64_t speakers = config.cache.num_speakers; + auto embedder = + load_engine(context, "embedder.plan", {{"stacked_features", {kStepRows, stacked}}}, + {{"inputs_embeds", {kStepRows, width}}}, config.max_step_rows); + auto encoder = load_engine(context, "encoder.plan", + {{"inputs_embeds", {kStepRows, width}}, {"key_bias", {kStepRows}}}, + {{"logits", {kStepRows, speakers}}}, config.max_step_rows); + return new DiarizationPipeline(std::move(embedder), std::move(encoder), std::move(config)); +} diff --git a/families/nemotron3_diarization/runtime/speaker_cache.cpp b/families/nemotron3_diarization/runtime/speaker_cache.cpp new file mode 100644 index 0000000000..b475cd21ce --- /dev/null +++ b/families/nemotron3_diarization/runtime/speaker_cache.cpp @@ -0,0 +1,261 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/nemotron3_diarization/runtime/speaker_cache.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { +namespace { + +// The reference's score constants, rounded once to float32 as torch does when +// it combines a Python float with a float32 tensor. +constexpr float kLogHalf = -0.6931471805599453F; +constexpr float kStrongBoost = 1.3862943611198906F; // -2 * log(0.5) +constexpr float kWeakBoost = 0.6931471805599453F; // -log(0.5) +constexpr float kMinusInfinity = -std::numeric_limits::infinity(); +constexpr float kPlusInfinity = std::numeric_limits::infinity(); + +void require(bool condition, const char* message) { + if (!condition) + throw std::runtime_error(std::string("nemotron3_diarization speaker cache: ") + message); +} + +float sigmoid(float logit) { + return 1.0F / (1.0F + std::exp(-logit)); +} + +void append_rows(std::vector& destination, const float* rows, std::int64_t count, + std::int64_t width) { + destination.insert(destination.end(), rows, rows + count * width); +} + +} // namespace + +std::vector top_k_first_seen(const std::vector& values, std::size_t k) { + std::vector order(values.size()); + std::iota(order.begin(), order.end(), std::size_t{0}); + // Larger first; NaN ranks above every number, as in torch.topk. The stable + // sort keeps equal values in index order, so the k-th place is the first seen. + const auto larger = [&](std::size_t a, std::size_t b) { + const float x = values[a], y = values[b]; + return (std::isnan(x) && !std::isnan(y)) || x > y; + }; + std::stable_sort(order.begin(), order.end(), larger); + order.resize(std::min(k, order.size())); + return order; +} + +SpeakerCache::SpeakerCache(SpeakerCachePolicy policy, std::vector silence_embedding) + : policy_(policy), silence_(std::move(silence_embedding)) { + const auto& p = policy_; + require(p.num_speakers > 0 && p.subsampling_factor > 0 && p.hidden_size > 0, + "geometry is unusable"); + require(p.silence_frames_per_speaker >= 0 && + p.cache_length >= + (static_cast(p.silence_frames_per_speaker) + 1) * p.num_speakers, + "the cache cannot hold every speaker"); + // The probability floor of the log scores: zero would turn a saturated + // probability into log(0) and the scores into infinities. + require(p.score_threshold > 0.0F && p.score_threshold < 1.0F && + std::isfinite(p.latest_frames_boost), + "score constants are unusable"); + require(p.fifo_length >= 0 && p.update_period > 0, "FIFO sizes are unusable"); + // A compression ranks more frames than the cache holds, so a boost budget + // up to the cache length always finds its frames. + require(p.min_positive_scores >= 0 && p.strong_boosted_frames >= 0 && + p.weak_boosted_frames >= 0 && p.strong_boosted_frames <= p.cache_length && + p.weak_boosted_frames <= p.cache_length, + "frame budgets are unusable"); + require(silence_.size() == static_cast(p.hidden_size), + "silence embedding width differs from the encoder width"); +} + +void SpeakerCache::copy_cached_rows(float* destination) const { + const auto width = static_cast(policy_.hidden_size); + std::memcpy(destination, cache_.data(), + static_cast(cache_rows_) * width * sizeof(float)); + std::memcpy(destination + static_cast(cache_rows_) * width, fifo_.data(), + static_cast(fifo_rows_) * width * sizeof(float)); +} + +std::vector SpeakerCache::pool_probabilities(const float* logits, std::int64_t rows, + const std::vector& valid) const { + const auto speakers = static_cast(policy_.num_speakers); + const auto factor = static_cast(policy_.subsampling_factor); + require(valid.size() == static_cast(rows), "frame mask does not match the step"); + std::vector probs(static_cast(rows * speakers)); + for (std::int64_t row = 0; row < rows; ++row) { + for (std::int64_t speaker = 0; speaker < speakers; ++speaker) { + float total = 0.0F; + for (std::int64_t sub = 0; sub < factor; ++sub) + total += sigmoid(logits[(row * factor + sub) * speakers + speaker]); + const float mask = valid[static_cast(row)] ? 1.0F : 0.0F; + probs[static_cast(row * speakers + speaker)] = + total / static_cast(factor) * mask; + } + } + return probs; +} + +std::vector SpeakerCache::frame_scores(const std::vector& probs, + std::int64_t rows) const { + const auto speakers = static_cast(policy_.num_speakers); + const float floor = policy_.score_threshold; + std::vector scores(probs.size()); + std::vector log_probs(speakers), log_complements(speakers); + for (std::size_t row = 0; row < static_cast(rows); ++row) { + const float* p = probs.data() + row * speakers; + float complement_total = 0.0F; + for (std::size_t s = 0; s < speakers; ++s) { + log_probs[s] = std::log(std::max(p[s], floor)); + log_complements[s] = std::log(std::max(1.0F - p[s], floor)); + complement_total += log_complements[s]; + } + for (std::size_t s = 0; s < speakers; ++s) { + const float difference = log_probs[s] - log_complements[s]; + const float joint = difference + complement_total; + scores[row * speakers + s] = p[s] > 0.5F ? joint - kLogHalf : kMinusInfinity; + } + } + // A speaker with enough positively scored frames loses its non-positive + // ones: overlapped speech, which describes the speaker worst. + std::vector positives(speakers, 0); + for (std::size_t i = 0; i < scores.size(); ++i) + positives[i % speakers] += scores[i] > 0.0F; + for (std::size_t i = 0; i < scores.size(); ++i) { + const bool speech = probs[i] > 0.5F; + const bool enough = positives[i % speakers] >= policy_.min_positive_scores; + if (!(scores[i] > 0.0F) && speech && enough) + scores[i] = kMinusInfinity; + } + return scores; +} + +namespace { + +void boost_scores(std::vector& scores, std::size_t rows, std::size_t speakers, + std::size_t count, float boost) { + // torch.topk refuses k above the frames it ranks; so does the cache, never + // boosting fewer frames than the policy asks for. + require(count <= rows, "a boost budget exceeds the frames to rank"); + std::vector column(rows); + for (std::size_t speaker = 0; speaker < speakers; ++speaker) { + for (std::size_t row = 0; row < rows; ++row) + column[row] = scores[row * speakers + speaker]; + for (const auto row : top_k_first_seen(column, count)) + scores[row * speakers + speaker] += boost; + } +} + +} // namespace + +void SpeakerCache::compress(std::vector& embeddings, std::vector& probs, + std::int64_t& rows) const { + const auto frames = static_cast(rows); + const auto speakers = static_cast(policy_.num_speakers); + const auto width = static_cast(policy_.hidden_size); + const auto length = static_cast(policy_.cache_length); + auto scores = frame_scores(probs, rows); + // Frames past the cache capacity are the ones just popped from the FIFO. + for (std::size_t i = length * speakers; i < scores.size(); ++i) + scores[i] += policy_.latest_frames_boost; + boost_scores(scores, frames, speakers, static_cast(policy_.strong_boosted_frames), + kStrongBoost); + boost_scores(scores, frames, speakers, static_cast(policy_.weak_boosted_frames), + kWeakBoost); + + // Speaker-major candidates, each speaker's frames followed by its reserved + // silence slots, which always win. + const std::size_t scored = + frames + static_cast(policy_.silence_frames_per_speaker); + std::vector flat(scored * speakers, kPlusInfinity); + for (std::size_t speaker = 0; speaker < speakers; ++speaker) + for (std::size_t frame = 0; frame < frames; ++frame) + flat[speaker * scored + frame] = scores[frame * speakers + speaker]; + const std::size_t sentinel = flat.size(); + auto chosen = top_k_first_seen(flat, length); + for (auto& index : chosen) + if (flat[index] == kMinusInfinity) + index = sentinel; + std::sort(chosen.begin(), chosen.end()); + + std::vector kept_embeddings, kept_probs; + kept_embeddings.reserve(length * width); + kept_probs.reserve(length * speakers); + const std::vector no_speech(speakers, 0.0F); + for (const auto index : chosen) { + const std::size_t frame = index == sentinel ? frames : std::min(index % scored, frames); + const float* embedding = + frame < frames ? embeddings.data() + frame * width : silence_.data(); + const float* prob = frame < frames ? probs.data() + frame * speakers : no_speech.data(); + kept_embeddings.insert(kept_embeddings.end(), embedding, embedding + width); + kept_probs.insert(kept_probs.end(), prob, prob + speakers); + } + embeddings = std::move(kept_embeddings); + probs = std::move(kept_probs); + rows = static_cast(chosen.size()); +} + +std::int64_t SpeakerCache::popped_frames(std::int64_t fifo_rows) const noexcept { + if (fifo_rows <= policy_.fifo_length) + return 0; + const std::int64_t popped = + std::max(policy_.update_period, fifo_rows - policy_.fifo_length); + return std::min(popped, fifo_rows); +} + +void SpeakerCache::update(const float* step_input, std::int64_t rows, const float* logits, + const std::vector& valid, std::int64_t chunk_frames, + std::int64_t lookback_frames) { + const auto width = static_cast(policy_.hidden_size); + const auto speakers = static_cast(policy_.num_speakers); + const std::int64_t chunk_start = cache_rows_ + fifo_rows_ + lookback_frames; + require(chunk_frames > 0 && lookback_frames >= 0 && chunk_start + chunk_frames <= rows, + "the chunk does not fit the step"); + const auto probs = pool_probabilities(logits, rows, valid); + + std::vector queue = fifo_; + append_rows(queue, step_input + chunk_start * width, chunk_frames, width); + const std::int64_t queued = fifo_rows_ + chunk_frames; + const std::int64_t popped = popped_frames(queued); + if (popped > 0) { + // An uncompressed cache still holds plain earlier frames, whose + // probabilities this step re-estimates; a compressed one is out of + // order, so the probabilities stored with its frames are the only ones. + std::vector merged_probs; + if (compressed_) + merged_probs = cache_probs_; + else + merged_probs.assign(probs.begin(), probs.begin() + cache_rows_ * speakers); + std::vector queue_probs(probs.begin() + cache_rows_ * speakers, + probs.begin() + (cache_rows_ + fifo_rows_) * speakers); + append_rows(queue_probs, probs.data() + chunk_start * speakers, chunk_frames, speakers); + + std::vector merged = cache_; + append_rows(merged, queue.data(), popped, width); + append_rows(merged_probs, queue_probs.data(), popped, speakers); + std::int64_t merged_rows = cache_rows_ + popped; + queue.erase(queue.begin(), queue.begin() + popped * width); + if (merged_rows > policy_.cache_length) { + compress(merged, merged_probs, merged_rows); + compressed_ = true; + } + cache_ = std::move(merged); + cache_probs_ = std::move(merged_probs); + cache_rows_ = merged_rows; + } + fifo_ = std::move(queue); + fifo_rows_ = queued - popped; +} + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/speaker_cache.h b/families/nemotron3_diarization/runtime/speaker_cache.h new file mode 100644 index 0000000000..15e9351702 --- /dev/null +++ b/families/nemotron3_diarization/runtime/speaker_cache.h @@ -0,0 +1,81 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include + +namespace trtmc::nemotron3_diarization { + +// The Arrival-Order Speaker Cache policy of the checkpoint's streaming config, +// with the FIFO sizes of offline mode. The frame budgets are integers derived +// at bundle time with the reference's own arithmetic. +struct SpeakerCachePolicy { + std::int32_t num_speakers{8}; + std::int32_t subsampling_factor{8}; + std::int32_t hidden_size{512}; + std::int32_t cache_length{264}; + std::int32_t silence_frames_per_speaker{1}; + std::int32_t fifo_length{40}; + std::int32_t update_period{300}; + float score_threshold{0.25F}; + float latest_frames_boost{0.05F}; + std::int32_t min_positive_scores{16}; + std::int32_t strong_boosted_frames{24}; + std::int32_t weak_boosted_frames{48}; +}; + +// Streaming state between encoder steps: the speaker cache and the FIFO queue +// of the most recent encoder *input* frames. Every step attends to these rows +// ahead of its chunk; after the step, the chunk joins the FIFO queue, and when +// the queue overflows its oldest frames move to the cache, which is compressed +// to the frames the step's own speaker scores rank highest, grouped by speaker +// in arrival order with learned silence frames between them. +class SpeakerCache { + public: + SpeakerCache(SpeakerCachePolicy policy, std::vector silence_embedding); + + // Rows to put ahead of the next chunk: the cache frames, then the FIFO frames. + std::int64_t cached_rows() const noexcept { return cache_rows_ + fifo_rows_; } + void copy_cached_rows(float* destination) const; + + // step_input: [rows, hidden] that the encoder saw (cached rows, look-back + // rows, the chunk, then its look-ahead). logits: [rows * factor, speakers]. + // valid: [rows], zero for padding frames, whose probabilities are zeroed. + void update(const float* step_input, std::int64_t rows, const float* logits, + const std::vector& valid, std::int64_t chunk_frames, + std::int64_t lookback_frames); + + bool compressed() const noexcept { return compressed_; } + std::int64_t cache_rows() const noexcept { return cache_rows_; } + std::int64_t fifo_rows() const noexcept { return fifo_rows_; } + const std::vector& cache_embeddings() const noexcept { return cache_; } + const std::vector& cache_probabilities() const noexcept { return cache_probs_; } + + // Exposed for the unit tests: speaker probabilities at the encoder frame + // rate, the frame scores, and the compression of the policy. + std::vector pool_probabilities(const float* logits, std::int64_t rows, + const std::vector& valid) const; + std::vector frame_scores(const std::vector& probs, std::int64_t rows) const; + void compress(std::vector& embeddings, std::vector& probs, + std::int64_t& rows) const; + + private: + std::int64_t popped_frames(std::int64_t fifo_rows) const noexcept; + + SpeakerCachePolicy policy_; + std::vector silence_; + std::vector cache_, cache_probs_, fifo_; + std::int64_t cache_rows_{0}, fifo_rows_{0}; + bool compressed_{false}; +}; + +// torch.topk(values, k, sorted=False) as CUDA resolves it: every value above +// the k-th largest, then values equal to it in index order (the first seen). +std::vector top_k_first_seen(const std::vector& values, std::size_t k); + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/wav.cpp b/families/nemotron3_diarization/runtime/wav.cpp new file mode 100644 index 0000000000..a62ebd0c01 --- /dev/null +++ b/families/nemotron3_diarization/runtime/wav.cpp @@ -0,0 +1,135 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/nemotron3_diarization/runtime/wav.h" + +#include +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { +namespace { + +static_assert(sizeof(float) == sizeof(std::uint32_t), "float32 samples are copied bit for bit"); + +constexpr std::uint32_t kPcm = 1; +constexpr std::uint32_t kFloat = 3; +[[noreturn]] void refuse(const std::string& reason) { + throw std::invalid_argument("invalid WAV input: " + reason); +} + +// RIFF stores integers little-endian, whatever the host's byte order. +std::uint32_t little_endian(const char* data, unsigned width) { + std::uint32_t value = 0; + for (unsigned i = width; i-- > 0;) + value = (value << 8U) | static_cast(data[i]); + return value; +} + +} // namespace + +WavAudio parse_wav(const std::vector& bytes) { + if (bytes.size() < 12 || std::memcmp(bytes.data(), "RIFF", 4) != 0 || + std::memcmp(bytes.data() + 8, "WAVE", 4) != 0) + refuse("not a RIFF/WAVE file"); + const std::uint64_t end = 8ULL + little_endian(bytes.data() + 4, 4); + if (end < 12) + refuse("the RIFF size does not cover its WAVE tag"); + if (end > bytes.size()) + refuse("the RIFF payload is truncated"); + + const char* format = nullptr; + const char* data = nullptr; + std::uint64_t data_size = 0; + for (std::uint64_t at = 12; at < end;) { + if (end - at < 8) + refuse("a chunk header is truncated"); + const char* chunk = bytes.data() + at; + const std::uint64_t size = little_endian(chunk + 4, 4); + // An odd-sized chunk is followed by one pad byte, inside the payload too. + const std::uint64_t padded = size + (size & 1U); + if (padded > end - at - 8) + refuse("a chunk exceeds the RIFF payload"); + if (std::memcmp(chunk, "fmt ", 4) == 0) { + if (format != nullptr) + refuse("more than one fmt chunk"); + if (size < 16) + refuse("the fmt chunk is shorter than 16 bytes"); + format = chunk + 8; + } else if (std::memcmp(chunk, "data", 4) == 0) { + if (data != nullptr) + refuse("more than one data chunk"); + data = chunk + 8; + data_size = size; + } + at += 8 + padded; + } + if (format == nullptr) + refuse("no fmt chunk"); + if (data == nullptr) + refuse("no data chunk"); + + const auto encoding = little_endian(format, 2); + const auto channels = little_endian(format + 2, 2); + const auto sample_rate = little_endian(format + 4, 4); + const auto block_align = little_endian(format + 12, 2); + const auto bits = little_endian(format + 14, 2); + const bool pcm16 = encoding == kPcm && bits == 16; + if (!pcm16 && !(encoding == kFloat && bits == 32)) + refuse("only PCM16 and float32 WAV are supported"); + if (channels == 0 || sample_rate == 0) + refuse("the sample rate and the channel count must be positive"); + const std::uint32_t width = bits / 8; + if (block_align != channels * width) + refuse("the block alignment does not match the channels and the sample width"); + if (data_size == 0) + refuse("no sample frames"); + if (data_size % block_align != 0) + refuse("the data chunk ends inside a sample frame"); + + WavAudio audio; + audio.sample_rate = sample_rate; + audio.channels = channels; + audio.samples.resize(static_cast(data_size / width)); + for (std::size_t i = 0; i < audio.samples.size(); ++i) { + const char* sample = data + i * width; + if (pcm16) { + const auto code = static_cast(little_endian(sample, 2)); + audio.samples[i] = static_cast(code >= 32768 ? code - 65536 : code) / 32768.0F; + } else { + const auto word = little_endian(sample, 4); + std::memcpy(&audio.samples[i], &word, sizeof(float)); + } + } + return audio; +} + +WavAudio read_wav(std::istream& input, std::uint64_t size) { + std::vector bytes(static_cast(std::min(size, 12))); + if (!input.read(bytes.data(), static_cast(bytes.size()))) + throw std::runtime_error("cannot read the WAV header"); + if (bytes.size() == 12 && std::memcmp(bytes.data(), "RIFF", 4) == 0) { + const std::uint64_t end = 8ULL + little_endian(bytes.data() + 4, 4); + bytes.resize(static_cast(std::max(12, std::min(end, size)))); + if (!input.read(bytes.data() + 12, static_cast(bytes.size() - 12))) + throw std::runtime_error("cannot read the WAV payload"); + } + return parse_wav(bytes); +} + +WavAudio read_wav(const std::string& path) { + std::error_code error; + if (!std::filesystem::is_regular_file(path, error)) + throw std::invalid_argument("the WAV input is not a readable file: " + path); + const std::uint64_t size = std::filesystem::file_size(path, error); + std::ifstream file(path, std::ios::binary); + if (error || !file) + throw std::invalid_argument("cannot open the WAV input: " + path); + return read_wav(file, size); +} + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/runtime/wav.h b/families/nemotron3_diarization/runtime/wav.h new file mode 100644 index 0000000000..b93f3138c5 --- /dev/null +++ b/families/nemotron3_diarization/runtime/wav.h @@ -0,0 +1,33 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include + +namespace trtmc::nemotron3_diarization { + +// One WAV file as interleaved float samples, for the family's command line. +// PCM16 decodes as value / 32768 and float32 as stored; every other encoding +// is refused. The model checks the sample rate and the samples themselves. +struct WavAudio { + std::vector samples; + std::uint32_t sample_rate{0}; + std::uint32_t channels{0}; +}; + +// The bytes of a RIFF/WAVE file: exactly one fmt and one data chunk, every +// chunk and its pad byte inside the RIFF payload, whole sample frames, at +// least one frame. +WavAudio parse_wav(const std::vector& bytes); +// Reads the RIFF header of a stream of `size` bytes, then no more than the +// payload it declares: nothing after the RIFF chunk belongs to the audio. +WavAudio read_wav(std::istream& input, std::uint64_t size); +WavAudio read_wav(const std::string& path); + +} // namespace trtmc::nemotron3_diarization diff --git a/families/nemotron3_diarization/support.py b/families/nemotron3_diarization/support.py new file mode 100644 index 0000000000..d24a625214 --- /dev/null +++ b/families/nemotron3_diarization/support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned model and task support for Nemotron 3 Diarization.""" + +from tensorrt_model_connect.model_support import family_support + + +describe = family_support( + model_types=("nemotron3_diarization",), + architectures=("Nemotron3DiarizationForAudioFrameClassification",), + tasks=("audio_to_timed_labels",), + default_task="audio_to_timed_labels", +) diff --git a/families/nemotron3_diarization/tests/__init__.py b/families/nemotron3_diarization/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/nemotron3_diarization/tests/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/families/nemotron3_diarization/tests/cpp/test_cli.cpp b/families/nemotron3_diarization/tests/cpp/test_cli.cpp new file mode 100644 index 0000000000..4ee724cf24 --- /dev/null +++ b/families/nemotron3_diarization/tests/cpp/test_cli.cpp @@ -0,0 +1,303 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// The family's command-line adapter without a model: its WAV reader, and the +// order in which it refuses a call (command, bundle identity, input, load). +#include "families/nemotron3_diarization/runtime/wav.h" +#include "trtmc/internal/cli.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +using Bytes = std::vector; +using trtmc::nemotron3_diarization::parse_wav; +using trtmc::nemotron3_diarization::read_wav; +int failures = 0; + +void check(bool condition, const std::string& message) { + if (!condition) { + std::cerr << "FAIL: " << message << '\n'; + ++failures; + } +} + +void put(Bytes& out, std::uint32_t value, unsigned width) { + for (unsigned i = 0; i < width; ++i) + out.push_back(static_cast((value >> (8U * i)) & 0xFFU)); +} + +Bytes chunk(const char* id, const Bytes& body) { + Bytes out(id, id + 4); + put(out, static_cast(body.size()), 4); + out.insert(out.end(), body.begin(), body.end()); + if (body.size() % 2 != 0) + out.push_back(0); + return out; +} + +Bytes format(std::uint32_t encoding, std::uint32_t channels, std::uint32_t rate, std::uint32_t bits, + std::uint32_t align) { + Bytes body; + put(body, encoding, 2); + put(body, channels, 2); + put(body, rate, 4); + put(body, rate * align, 4); + put(body, align, 2); + put(body, bits, 2); + return chunk("fmt ", body); +} + +Bytes riff(const std::vector& chunks) { + Bytes payload{'W', 'A', 'V', 'E'}; + for (const auto& part : chunks) + payload.insert(payload.end(), part.begin(), part.end()); + Bytes out{'R', 'I', 'F', 'F'}; + put(out, static_cast(payload.size()), 4); + out.insert(out.end(), payload.begin(), payload.end()); + return out; +} + +// Rewrites the RIFF size so that the payload is every byte after the header. +void cover(Bytes& bytes) { + Bytes size; + put(size, static_cast(bytes.size() - 8), 4); + std::copy(size.begin(), size.end(), bytes.begin() + 4); +} + +Bytes pcm16(const std::vector& codes) { + Bytes body; + for (const auto code : codes) + put(body, static_cast(code) & 0xFFFFU, 2); + return body; +} + +void refused(const Bytes& bytes, const std::string& reason) { + try { + parse_wav(bytes); + check(false, "accepted a WAV that should fail with: " + reason); + } catch (const std::invalid_argument& error) { + check(std::string(error.what()).find(reason) != std::string::npos, + "expected \"" + reason + "\", got \"" + error.what() + "\""); + } +} + +void test_wav_decoding() { + const auto mono = parse_wav( + riff({format(1, 1, 16000, 16, 2), chunk("data", pcm16({0, 16384, -32768, 32767}))})); + check(mono.sample_rate == 16000 && mono.channels == 1 && + mono.samples == std::vector{0.0F, 0.5F, -1.0F, 32767.0F / 32768.0F}, + "PCM16 decodes as value / 32768"); + + const std::vector values{0.25F, -0.5F, 1.5F, -0.0F}; + Bytes body; + for (const float value : values) { + std::uint32_t word = 0; + std::memcpy(&word, &value, sizeof(word)); + put(body, word, 4); + } + // An odd-sized chunk ahead of fmt, with its pad byte, is skipped. + const auto stereo = parse_wav(riff( + {chunk("LIST", Bytes{'a', 'b', 'c'}), format(3, 2, 8000, 32, 8), chunk("data", body)})); + check(stereo.sample_rate == 8000 && stereo.channels == 2 && stereo.samples == values && + std::signbit(stereo.samples[3]), + "float32 keeps every sample bit for bit, interleaved"); +} + +void test_wav_refusals() { + const auto fmt16 = format(1, 1, 16000, 16, 2); + const auto data = chunk("data", pcm16({1, 2})); + refused(Bytes{'R', 'I', 'F', 'F'}, "not a RIFF/WAVE file"); + auto riffx = riff({fmt16, data}); + riffx[3] = 'X'; + refused(riffx, "not a RIFF/WAVE file"); + auto small = riff({fmt16, data}); + small[4] = 3; + small[5] = small[6] = small[7] = 0; + refused(small, "does not cover its WAVE tag"); + auto truncated = riff({fmt16, data}); + truncated.pop_back(); + refused(truncated, "payload is truncated"); + auto stub = riff({fmt16, data}); + stub.insert(stub.end(), {'J', 'U', 'N', 'K'}); + cover(stub); + refused(stub, "chunk header is truncated"); + auto unpadded = riff({fmt16, data}); + for (const char byte : chunk("LIST", Bytes{'a', 'b', 'c'})) + unpadded.push_back(byte); + unpadded.pop_back(); + cover(unpadded); + refused(unpadded, "exceeds the RIFF payload"); + auto overlong = riff({fmt16, data}); + overlong[overlong.size() - 8] = 9; + refused(overlong, "exceeds the RIFF payload"); + refused(riff({data}), "no fmt chunk"); + refused(riff({fmt16}), "no data chunk"); + refused(riff({fmt16, fmt16, data}), "more than one fmt chunk"); + refused(riff({fmt16, data, data}), "more than one data chunk"); + refused(riff({chunk("fmt ", Bytes(14, 0)), data}), "shorter than 16 bytes"); + refused(riff({format(1, 1, 16000, 24, 3), chunk("data", Bytes(6, 0))}), + "only PCM16 and float32"); + refused(riff({format(3, 1, 16000, 64, 8), chunk("data", Bytes(8, 0))}), + "only PCM16 and float32"); + refused(riff({format(0xFFFE, 1, 16000, 16, 2), data}), "only PCM16 and float32"); + refused(riff({format(1, 0, 16000, 16, 0), data}), "must be positive"); + refused(riff({format(1, 1, 0, 16, 2), data}), "must be positive"); + refused(riff({format(1, 2, 16000, 16, 2), data}), "block alignment"); + refused(riff({fmt16, chunk("data", Bytes{})}), "no sample frames"); + refused(riff({format(1, 2, 16000, 16, 4), chunk("data", pcm16({1, 2, 3}))}), + "inside a sample frame"); +} + +// Serves bytes from memory and records how many the reader took. +class Tape : public std::streambuf { + public: + explicit Tape(Bytes bytes) : bytes_(std::move(bytes)) { + setg(bytes_.data(), bytes_.data(), bytes_.data() + bytes_.size()); + } + std::size_t consumed() const { return static_cast(gptr() - eback()); } + + private: + Bytes bytes_; +}; + +void test_wav_reads_only_its_riff_chunk() { + auto bytes = riff({format(1, 1, 16000, 16, 2), chunk("data", pcm16({8192}))}); + const auto length = bytes.size(); + bytes.resize(length + 4096, 'x'); + Tape tape(bytes); + std::istream input(&tape); + const auto audio = read_wav(input, bytes.size()); + check(audio.samples == std::vector{0.25F} && tape.consumed() == length, + "the bytes after the RIFF chunk are never read"); +} + +void test_wav_files(const fs::path& root) { + const auto path = root / "speech.wav"; + const auto bytes = riff({format(1, 1, 16000, 16, 2), chunk("data", pcm16({-16384}))}); + std::ofstream(path, std::ios::binary) + .write(bytes.data(), static_cast(bytes.size())); + check(read_wav(path.string()).samples == std::vector{-0.5F}, "a WAV file is read"); + for (const auto& missing : {root / "missing.wav", root}) { + try { + read_wav(missing.string()); + check(false, "read a WAV input that is not a file: " + missing.string()); + } catch (const std::invalid_argument& error) { + check(std::string(error.what()).find("not a readable file") != std::string::npos, + "a missing file or a directory is refused before any read"); + } + } +} + +void write_bundle(const fs::path& path, const std::string& family) { + const auto header = + nlohmann::json{{"format", 1}, + {"family", family}, + {"task", "audio_to_timed_labels"}, + {"backend", "trt"}, + {"sections", {{"engine.plan", {{"offset", 0}, {"length", 4}}}}}} + .dump(); + std::ofstream output(path, std::ios::binary); + output.write("BUNDLE\x01\x00", 8); + for (unsigned shift = 0; shift < 64; shift += 8) + output.put(static_cast((static_cast(header.size()) >> shift) & 255U)); + output.write(header.data(), static_cast(header.size())); + output.write("PLAN", 4); +} + +struct Capture { + std::string output, error; +}; +void capture_output(void* context, const char* data, std::size_t size) { + static_cast(context)->output.append(data, size); +} +void capture_error(void* context, const char* data, std::size_t size) { + static_cast(context)->error.append(data, size); +} + +struct Call { + int status; + Capture captured; +}; +Call invoke(const char* handler, const std::string& values, const std::string& runtime_root) { + Capture captured; + const auto status = trtmc_family_cli_v1(handler, values.c_str(), runtime_root.c_str(), + &captured, capture_output, capture_error); + return {status, captured}; +} + +bool refuses(const Call& call, const std::string& reason) { + return call.status == 1 && call.captured.output.empty() && + call.captured.error.rfind("Error: ", 0) == 0 && + call.captured.error.find(reason) != std::string::npos; +} + +void test_handler(const fs::path& root) { + const auto ours = root / "diarization.bundle"; + const auto other = root / "other.bundle"; + write_bundle(ours, "nemotron3_diarization"); + write_bundle(other, "another_family"); + const auto wav = root / "speech.wav"; + const auto missing = root / "missing.wav"; + const auto runtime = root / "runtime"; + fs::create_directories(runtime); + const auto values = [&](const fs::path& bundle, const fs::path& audio) { + return nlohmann::json{{"bundle", bundle.string()}, {"audio", audio.string()}}.dump(); + }; + + check(refuses(invoke("detect", values(ours, wav), runtime.string()), "unknown Nemotron 3"), + "an undeclared command is refused"); + check(refuses(invoke(nullptr, values(ours, wav), runtime.string()), "incomplete call"), + "a call without a handler name is refused"); + check(refuses(invoke("diarize", "{", runtime.string()), "parse"), + "malformed values are reported, not thrown across the C boundary"); + check(refuses(invoke("diarize", R"({"audio": "x.wav"})", runtime.string()), "bundle"), + "a call without a bundle is refused"); + // Identity comes first: the missing audio of another family's bundle is never read. + check(refuses(invoke("diarize", values(other, missing), runtime.string()), + "requires a nemotron3_diarization bundle"), + "another family's bundle is refused before its input is read"); + // The input comes before the model: a bad WAV never loads an engine. + check( + refuses(invoke("diarize", values(ours, missing), runtime.string()), "not a readable file"), + "the WAV input is checked before the model loads"); + const auto loaded = invoke("diarize", values(ours, wav), runtime.string()); + check(loaded.status == 1 && loaded.captured.output.empty() && + loaded.captured.error.rfind("Error: ", 0) == 0, + "a model that cannot load is reported as an error"); +} + +} // namespace + +int main() { + const auto root = + fs::temp_directory_path() / ("trtmc-nemotron3-diarization-cli-" + std::to_string(getpid())); + fs::create_directories(root); + try { + test_wav_decoding(); + test_wav_refusals(); + test_wav_reads_only_its_riff_chunk(); + test_wav_files(root); + test_handler(root); + } catch (const std::exception& error) { + std::cerr << "FAIL: " << error.what() << '\n'; + ++failures; + } + fs::remove_all(root); + return failures == 0 ? 0 : 1; +} diff --git a/families/nemotron3_diarization/tests/cpp/test_runtime.cpp b/families/nemotron3_diarization/tests/cpp/test_runtime.cpp new file mode 100644 index 0000000000..9febfa09f3 --- /dev/null +++ b/families/nemotron3_diarization/tests/cpp/test_runtime.cpp @@ -0,0 +1,613 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// CPU tests of the host side of the Nemotron 3 Diarization runtime against the +// reference implementation: the log-mel front end, the Arrival-Order Speaker +// Cache over a sequence of steps with compressions, and the speaker segments. +// The golden data comes from tests/generate_runtime_golden.py. + +#include "families/nemotron3_diarization/runtime/bundle.h" +#include "families/nemotron3_diarization/runtime/frontend.h" +#include "families/nemotron3_diarization/runtime/pipeline.h" +#include "families/nemotron3_diarization/runtime/speaker_cache.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace trtmc::nemotron3_diarization; +using nlohmann::json; + +int failures = 0; + +void check(bool passed, const std::string& label) { + if (!passed) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} + +std::string data_path(const char* name) { + return std::string(NEMOTRON3_DIARIZATION_TEST_DATA) + "/" + name; +} + +std::vector read_f32(const char* name) { + std::ifstream file(data_path(name), std::ios::binary); + const std::vector bytes((std::istreambuf_iterator(file)), + std::istreambuf_iterator()); + if (bytes.size() % sizeof(float) != 0) + throw std::runtime_error(std::string(name) + " does not hold whole float32 values"); + std::vector values(bytes.size() / sizeof(float)); + std::copy(bytes.begin(), bytes.end(), reinterpret_cast(values.data())); + return values; +} + +std::vector flat(const json& rows) { + std::vector values; + for (const auto& row : rows) + for (const auto& value : row) + values.push_back(value.get()); + return values; +} + +float max_gap(const std::vector& a, const std::vector& b) { + if (a.size() != b.size()) + return std::numeric_limits::infinity(); + float worst = 0.0F; + for (std::size_t i = 0; i < a.size(); ++i) { + const float gap = std::abs(a[i] - b[i]); + // std::max would skip a NaN, so a nonfinite gap fails every bound. + if (!std::isfinite(gap)) + return std::numeric_limits::infinity(); + worst = std::max(worst, gap); + } + return worst; +} + +bool refuses(const std::function& action) { + try { + action(); + } catch (const std::exception&) { + return true; + } + return false; +} + +void test_top_k() { + const float inf = std::numeric_limits::infinity(); + const std::vector values{1.0F, 3.0F, 3.0F, 3.0F, 2.0F, -inf}; + auto two = top_k_first_seen(values, 2); + std::sort(two.begin(), two.end()); + check(two == std::vector{1, 2}, "ties at the k-th value keep the first seen"); + auto all = top_k_first_seen(values, 6); + check(all.size() == 6 && all.back() == 5, "minus infinity ranks last"); + const std::vector with_nan{0.0F, std::nanf(""), 1.0F}; + check(top_k_first_seen(with_nan, 1) == std::vector{1}, + "NaN ranks above every number, as in torch.topk"); +} + +void test_front_end(const json& golden) { + FrontEndConfig config; + config.window = read_f32("window.f32"); + config.mel_filters = read_f32("mel_filters.f32"); + const LogMelFrontEnd front_end(config); + const auto samples = golden.at("samples").get>(); + const auto features = + front_end.compute(samples.data(), static_cast(samples.size())); + check(features.frames == static_cast(golden.at("features").size()) && + features.valid_frames == golden.at("valid_frames").get(), + "centred framing gives 1 + L / hop frames, L / hop of them valid"); + // The same front end with a float64 transform: what this one must reproduce. + const float exact = max_gap(features.values, flat(golden.at("features_float64"))); + // The reference transforms in float32 and sits up to 2.4e-4 from the float64 + // features at mel bins near the 2**-24 floor; twice that bounds it, while a + // wrong window, framing or filter bank moves features by orders more. + const float reference = max_gap(features.values, flat(golden.at("features"))); + std::cout << "front end: worst log-mel gap " << exact << " to float64, " << reference + << " to the reference\n"; + check(exact <= 1e-5F, "log-mel features match the float64 front end"); + check(reference <= 5e-4F, "log-mel features match the reference feature extractor"); + if (features.values.size() < static_cast(config.num_mel_bins)) { + check(false, "the front end returned fewer values than one frame"); + return; + } + const auto last = features.values.end() - config.num_mel_bins; + check(std::all_of(last, features.values.end(), [](float value) { return value == 0.0F; }), + "the frame past the audio is zero, as the reference masks it"); + const std::vector stereo{1.0F, 3.0F, -2.0F, 0.0F}; + check(mix_to_mono(stereo.data(), stereo.size(), 2) == std::vector{2.0F, -1.0F}, + "interleaved channels are averaged to mono"); +} + +SpeakerCachePolicy policy_from(const json& value) { + SpeakerCachePolicy policy; + policy.num_speakers = value.at("num_speakers"); + policy.subsampling_factor = value.at("subsampling_factor"); + policy.hidden_size = value.at("hidden_size"); + policy.cache_length = value.at("cache_length"); + policy.silence_frames_per_speaker = value.at("silence_frames_per_speaker"); + policy.fifo_length = value.at("fifo_length"); + policy.update_period = value.at("update_period"); + policy.score_threshold = value.at("score_threshold"); + policy.latest_frames_boost = value.at("latest_frames_boost"); + policy.min_positive_scores = value.at("min_positive_scores"); + policy.strong_boosted_frames = value.at("strong_boosted_frames"); + policy.weak_boosted_frames = value.at("weak_boosted_frames"); + return policy; +} + +void test_speaker_cache(const json& golden) { + const auto policy = policy_from(golden.at("policy")); + SpeakerCache cache(policy, golden.at("silence").get>()); + // The trajectory must keep frames queued, read look-back rows and compress, + // or the checks below would pass on paths they never reach. + bool queued = false, looked_back = false, compressed = false; + for (const auto& step : golden.at("steps")) { + queued = queued || step.at("fifo_rows").get() > 0; + looked_back = looked_back || step.at("lookback_frames").get() > 0; + compressed = compressed || step.at("compressed").get(); + } + check(queued && looked_back && compressed, + "the golden trajectory queues frames, reads look-back rows and compresses"); + int index = 0; + for (const auto& step : golden.at("steps")) { + const auto label = "step " + std::to_string(index++) + ": "; + const auto input = flat(step.at("step_input")); + const auto rows = static_cast(step.at("step_input").size()); + // The rows the cache puts ahead of the chunk are the reference's own. + std::vector cached(static_cast(cache.cached_rows()) * + static_cast(policy.hidden_size)); + cache.copy_cached_rows(cached.data()); + // Sizes first: a wrong size stops the trajectory before any range is read. + if (cached.size() > input.size()) { + check(false, label + "the cache holds more rows than the step input"); + return; + } + check(std::equal(cached.begin(), cached.end(), input.begin()), + label + "cached rows lead the step input"); + const auto logits = flat(step.at("logits")); + const auto valid = step.at("valid").get>(); + cache.update(input.data(), rows, logits.data(), valid, + step.at("chunk_frames").get(), + step.at("lookback_frames").get()); + check(cache.cache_rows() == step.at("cache_rows").get() && + cache.fifo_rows() == step.at("fifo_rows").get() && + cache.compressed() == step.at("compressed").get(), + label + "cache and FIFO sizes follow the reference"); + // The embeddings are copies, so the same selection gives equal values. + check(cache.cache_embeddings() == flat(step.at("cache")), + label + "the cache keeps the reference's frames in its order"); + check(max_gap(cache.cache_probabilities(), flat(step.at("cache_probs"))) <= 1e-6F, + label + "the cache keeps the reference's speaker probabilities"); + std::vector all(static_cast(cache.cached_rows()) * + static_cast(policy.hidden_size)); + cache.copy_cached_rows(all.data()); + const auto fifo = flat(step.at("fifo")); + if (fifo.size() > all.size()) { + check(false, label + "the cache and FIFO hold fewer rows than the reference's FIFO"); + return; + } + check(std::equal(fifo.begin(), fifo.end(), + all.end() - static_cast(fifo.size())), + label + "the FIFO queue holds the reference's latest frames"); + } +} + +void test_intervals(const json& golden) { + const auto logits = flat(golden.at("logits")); + const auto frames = static_cast(golden.at("logits").size()); + const auto speakers = static_cast(golden.at("logits").at(0).size()); + for (const auto& item : golden.at("cases")) { + const auto threshold = item.at("threshold").get(); + const auto intervals = active_intervals(logits, frames, speakers, threshold, 160, 16000); + const auto& expected = item.at("segments"); + bool same = intervals.size() == expected.size(); + for (std::size_t i = 0; same && i < intervals.size(); ++i) + same = std::abs(intervals[i].start_seconds - expected[i][0].get()) < 1e-9 && + std::abs(intervals[i].end_seconds - expected[i][1].get()) < 1e-9 && + intervals[i].label == expected[i][2].get(); + check(same, + "speaker segments match the reference at threshold " + std::to_string(threshold)); + } + check(speaker_active(0.0F, 0.5F) == false && speaker_active(1e-6F, 0.5F) == true, + "activity is strictly above the threshold"); +} + +void test_max_gap() { + const float nan = std::numeric_limits::quiet_NaN(); + const float inf = std::numeric_limits::infinity(); + check(max_gap({1.0F, 2.0F}, {1.0F, 2.5F}) == 0.5F, "max_gap reports the largest difference"); + check(max_gap({nan, 2.0F}, {1.0F, 2.0F}) == inf && max_gap({1.0F, 2.0F}, {1.0F, nan}) == inf, + "a NaN operand fails every bound"); + check(max_gap({inf}, {inf}) == inf, "infinite operands fail every bound"); +} + +// runtime.json as config.runtime_config() writes it for the released checkpoint. +json released_runtime_json() { + json labels = json::array(); + for (int index = 0; index < 8; ++index) + labels.push_back("speaker_" + std::to_string(index)); + return {{"sample_rate", 16000}, + {"n_fft", 512}, + {"win_length", 400}, + {"hop_length", 160}, + {"preemphasis", 0.97}, + {"log_guard", 5.9604644775390625e-08}, + {"num_mel_bins", 128}, + {"subsampling_factor", 8}, + {"hidden_size", 512}, + {"num_speakers", 8}, + {"chunk_length", 340}, + {"chunk_left_context", 0}, + {"chunk_right_context", 40}, + {"fifo_length", 40}, + {"speaker_cache_update_period", 300}, + {"speaker_cache_length", 264}, + {"silence_frames_per_speaker", 1}, + {"prediction_score_threshold", 0.25}, + {"latest_frames_score_boost", 0.05}, + {"min_positive_scores", 16}, + {"strong_boosted_frames", 24}, + {"weak_boosted_frames", 48}, + {"max_step_rows", 684}, + {"labels", labels}}; +} + +std::vector text_of(const std::string& text) { + return {text.begin(), text.end()}; +} + +void test_runtime_json() { + const auto config = parse_runtime_json(text_of(released_runtime_json().dump())); + check(config.cache.subsampling_factor == 8 && config.max_step_rows == 684 && + config.labels.size() == 8 && config.front_end.preemphasis == 0.97F, + "runtime.json of the released checkpoint parses"); + const std::vector> unusable{ + {"subsampling_factor", 0}, + {"subsampling_factor", 2.5}, + {"subsampling_factor", true}, + {"subsampling_factor", "8"}, + {"subsampling_factor", nullptr}, + {"subsampling_factor", std::int64_t{2147483648}}, + {"subsampling_factor", std::uint64_t{4294967296}}, + {"silence_frames_per_speaker", -1}, + {"preemphasis", "0.97"}, + {"preemphasis", false}, + {"log_guard", 1e300}, + {"labels", "speaker_0"}, + {"labels", json::array({"speaker_0", ""})}, + {"labels", json::array({"speaker_0", "speaker_0"})}, + {"labels", json::array({"speaker_0", 1})}, + }; + for (const auto& [key, value] : unusable) { + auto variant = released_runtime_json(); + variant[key] = value; + check(refuses([&] { (void)parse_runtime_json(text_of(variant.dump())); }), + "runtime.json refuses " + key + " = " + value.dump()); + } + auto missing = released_runtime_json(); + missing.erase("chunk_length"); + check(refuses([&] { (void)parse_runtime_json(text_of(missing.dump())); }), + "runtime.json refuses a missing key"); + // A repeated key, which the parser alone would resolve to its last value. + const auto repeated = "{\"subsampling_factor\": 0, " + released_runtime_json().dump().substr(1); + check(refuses([&] { (void)parse_runtime_json(text_of(repeated)); }), + "runtime.json refuses a repeated key"); + check(refuses([&] { (void)parse_runtime_json(text_of("[1, 2]")); }), + "runtime.json must be an object"); +} + +void test_engine_io() { + const std::vector inputs{{"inputs_embeds", {kStepRows, 4}}, + {"key_bias", {kStepRows}}}; + const std::vector outputs{{"logits", {kStepRows, 2}}}; + const trtmc::TensorInfo embeds{"inputs_embeds", {-1, 4}, trtmc::DType::kFloat32, true}; + const trtmc::TensorInfo bias{"key_bias", {-1}, trtmc::DType::kFloat32, true}; + const trtmc::TensorInfo logits{"logits", {-1, 2}, trtmc::DType::kFloat32, false}; + const auto io = [](std::vector tensors, std::int64_t low, std::int64_t high, + std::int32_t profiles) { + EngineIo value{std::move(tensors), {}, profiles}; + for (const auto& tensor : value.tensors) + if (tensor.is_input) + value.input_rows.push_back({tensor.name, {low, high}}); + return value; + }; + const auto loads = [&](const EngineIo& value) { + return !refuses([&] { check_engine_io(value, inputs, outputs, 24, "encoder.plan"); }); + }; + check(loads(io({embeds, bias, logits}, 1, 24, 1)), "an engine with the expected I/O loads"); + // A backend may report the rows its buffers hold instead of -1. + check(loads(io({{"inputs_embeds", {24, 4}, trtmc::DType::kFloat32, true}, + {"key_bias", {24}, trtmc::DType::kFloat32, true}, + {"logits", {192, 2}, trtmc::DType::kFloat32, false}}, + 1, 24, 1)), + "an engine reporting its buffers' rows loads"); + check(!loads(io({embeds, bias, {"logits", {192, 3}, trtmc::DType::kFloat32, false}}, 1, 24, 1)), + "a reported speaker count other than the expected one is refused"); + check(!loads(io({embeds, bias, {"logits", {2, -1}, trtmc::DType::kFloat32, false}}, 1, 24, 1)), + "transposed logits are refused"); + check(!loads(io({embeds, bias, {"logits", {-1, 3}, trtmc::DType::kFloat32, false}}, 1, 24, 1)), + "logits for another speaker count are refused"); + check(!loads(io({{"inputs_embeds", {-1, 4}, trtmc::DType::kFloat16, true}, bias, logits}, 1, 24, + 1)), + "a float16 input is refused"); + check(!loads(io({embeds, logits}, 1, 24, 1)), "a missing input is refused"); + check(!loads( + io({embeds, bias, logits, {"extra", {-1}, trtmc::DType::kFloat32, false}}, 1, 24, 1)), + "an extra output is refused"); + check(!loads(io({embeds, bias, logits}, 2, 24, 1)), "a profile that needs two rows is refused"); + check(!loads(io({embeds, bias, logits}, 1, 23, 1)), + "a profile shorter than the longest step is refused"); + check(!loads(io({embeds, bias, logits}, 1, 24, 0)), "an engine without a profile is refused"); +} + +// An engine stand-in for host-side tests: forward() answers with what the test +// computes; nothing else of the interface is used by the pipeline. +class FakeEngine final : public trtmc::ITrtModule { + public: + using Respond = std::function&)>; + explicit FakeEngine(Respond respond) : respond_(std::move(respond)) {} + trtmc::TensorMap forward(const trtmc::TensorMap& inputs) override { + ++calls; + return respond_(inputs, buffer_); + } + trtmc::DeviceTensorMap forward_device(const trtmc::DeviceTensorMap&) override { + throw std::logic_error("unused"); + } + void forward_device_async(const trtmc::DeviceTensorMap&) override { + throw std::logic_error("unused"); + } + void forward_async(const trtmc::TensorMap&) override { throw std::logic_error("unused"); } + void sync() override {} + cudaStream_t stream() const override { return nullptr; } + void enable_cuda_graph() override {} + bool cuda_graph_active() const override { return false; } + bool cuda_graph_captured() const override { return false; } + int32_t profile_idx() const override { return 0; } + std::vector input_info() const override { return {}; } + std::vector output_info() const override { return {}; } + bool has_input(const std::string&) const override { return true; } + bool has_output(const std::string&) const override { return true; } + trtmc::DType tensor_dtype(const std::string&) const override { return trtmc::DType::kFloat32; } + std::vector tensor_shape(const std::string&) const override { return {}; } + std::vector input_profile_shape(const std::string&, int32_t, + trtmc::ProfileShapeSelector) const override { + return {}; + } + int32_t optimization_profile_count() const override { return 1; } + void* device_ptr(const std::string&) const override { return nullptr; } + void bind_external(const std::string&, void*) override {} + void bind_external(const std::string&, void*, const std::vector&) override {} + int32_t input_rank(const std::string&) const override { return 0; } + bool input_is_dynamic(const std::string&) const override { return true; } + void reset_execution_context() override {} + void set_timing_label(std::string) override {} + bool ok() const override { return true; } + void keep_alive(std::shared_ptr) override {} + + int calls{0}; + + private: + Respond respond_; + std::vector buffer_; +}; + +// Two speakers, a 4-wide encoder and chunks of 5 rows with 2 rows of +// look-ahead, so that one second of audio takes three encoder steps. +DiarizationConfig small_config() { + DiarizationConfig config; + config.front_end.window = read_f32("window.f32"); + config.front_end.mel_filters = read_f32("mel_filters.f32"); + config.cache = {2, 8, 4, 8, 1, 4, 3, 0.25F, 0.05F, 1, 1, 2}; + config.chunk_length = 5; + config.chunk_left_context = 0; + config.chunk_right_context = 2; + config.max_step_rows = 8 + 4 + 5 + 2; + config.labels = {"speaker_0", "speaker_1"}; + config.silence_embedding = std::vector(4, 0.0F); + return config; +} + +struct Faults { + bool nan_embedding{false}; + bool nan_lookahead_logit{false}; + bool transposed_logits{false}; +}; + +struct Rig { + FakeEngine* embedder{nullptr}; + FakeEngine* encoder{nullptr}; + std::unique_ptr pipeline; +}; + +Rig make_rig(const Faults& faults) { + auto embedder = std::make_unique( + [faults](const trtmc::TensorMap& inputs, std::vector& buffer) { + const auto rows = inputs.at("stacked_features").shape.at(0); + buffer.assign(static_cast(rows * 4), 0.1F); + if (faults.nan_embedding) + buffer[0] = std::numeric_limits::quiet_NaN(); + return trtmc::TensorMap{ + {"inputs_embeds", {buffer.data(), {rows, 4}, trtmc::DType::kFloat32}}}; + }); + auto calls = std::make_shared(0); + auto encoder = std::make_unique([faults, calls](const trtmc::TensorMap& inputs, + std::vector& buffer) { + const auto rows = inputs.at("inputs_embeds").shape.at(0); + buffer.assign(static_cast(rows * 8 * 2), -3.0F); + // The first step is the first chunk (rows 0-4) and its look-ahead + // (rows 5-6); only the chunk's logits are kept for the result. + if (faults.nan_lookahead_logit && (*calls)++ == 0) + buffer[static_cast(6 * 8 * 2)] = std::numeric_limits::quiet_NaN(); + const std::vector shape = faults.transposed_logits + ? std::vector{2, rows * 8} + : std::vector{rows * 8, 2}; + return trtmc::TensorMap{{"logits", {buffer.data(), shape, trtmc::DType::kFloat32}}}; + }); + Rig rig; + rig.embedder = embedder.get(); + rig.encoder = encoder.get(); + rig.pipeline = std::make_unique(std::move(embedder), std::move(encoder), + small_config()); + return rig; +} + +void test_pipeline_rejections() { + std::vector second(16000); + for (std::size_t i = 0; i < second.size(); ++i) + second[i] = 0.1F * std::sin(0.05F * static_cast(i)); + const auto run = [&](Rig& rig, const std::vector& samples) { + trtmc::internal::AudioToTimedLabelsRequest request; + request.audio = {{samples.data(), samples.size()}, 16000U, 1U}; + return rig.pipeline->run(request, {}); + }; + auto healthy = make_rig({}); + const auto result = run(healthy, second); + check(healthy.encoder->calls == 3 && result.frame_count == 100 && + result.frame_scores.size() == 200 && result.intervals.empty(), + "one second of audio takes three steps and yields 100 frames of two speakers"); + auto nan_sample = second; + nan_sample[8000] = std::numeric_limits::quiet_NaN(); + auto clean = make_rig({}); + check(refuses([&] { (void)run(clean, nan_sample); }), "a NaN audio sample is refused"); + auto infinite_sample = second; + infinite_sample[0] = std::numeric_limits::infinity(); + check(refuses([&] { (void)run(clean, infinite_sample); }), + "an infinite audio sample is refused"); + auto nan_embedding = make_rig({true, false, false}); + check(refuses([&] { (void)run(nan_embedding, second); }), "a NaN embedding is refused"); + auto nan_lookahead = make_rig({false, true, false}); + check(refuses([&] { (void)run(nan_lookahead, second); }), + "a NaN logit in the look-ahead, which the cache reads, is refused"); + auto transposed = make_rig({false, false, true}); + check(refuses([&] { (void)run(transposed, second); }), + "logits of the right size but transposed shape are refused"); + // The threshold is compared in float32: values that round to 0 or 1 are refused. + for (const double value : {1e-300, 0.999999999}) { + const trtmc::internal::ConfigEntry entry{"threshold", trtmc::internal::ConfigValue{value}}; + auto rounded = make_rig({}); + check(refuses([&] { + trtmc::internal::AudioToTimedLabelsRequest request; + request.audio = {{second.data(), second.size()}, 16000U, 1U}; + (void)rounded.pipeline->run(request, {&entry, 1}); + }), + "threshold " + std::to_string(value) + " rounds to an endpoint in float32"); + } + // Finite samples near the float32 limit overflow the pre-emphasis and the + // power spectrum; the features are refused before any engine runs. + auto loud = second; + for (std::size_t i = 0; i < loud.size(); ++i) + loud[i] = i % 2 == 0 ? 3.0e38F : -3.0e38F; + auto overflow = make_rig({}); + check(refuses([&] { (void)run(overflow, loud); }) && overflow.embedder->calls == 0 && + overflow.encoder->calls == 0, + "audio that overflows the front end is refused before any engine call"); +} + +void test_section_lengths() { + // Section lengths come from the bundle's table and are checked before a read. + check(!refuses([] { check_float_section(400 * 4, 400, "window.f32"); }), + "a float section of the expected length passes"); + check(refuses([] { check_float_section(std::uint64_t{1} << 62, 400, "window.f32"); }), + "an oversized float section is refused before it is read"); + check(refuses([] { + check_float_section(16, std::numeric_limits::max(), "window.f32"); + }), + "a float count whose byte size overflows is refused"); + check(refuses([] { check_section_limit(std::uint64_t{1} << 40, 1 << 20, "runtime.json"); }), + "an oversized runtime.json is refused before it is read"); +} + +void test_boost_needs_its_frames() { + // As torch.topk, a compression never boosts fewer frames than its budget. + SpeakerCache cache(small_config().cache, std::vector(4, 0.0F)); + std::vector embeddings(4, 0.0F), probs{0.9F, 0.1F}; + std::int64_t rows = 1; + check(refuses([&] { cache.compress(embeddings, probs, rows); }), + "a compression with fewer frames than a boost budget is refused"); +} + +void test_saturated_scores() { + // Probabilities of exactly 1 and 0: with a positive floor every log score + // stays finite or is the deliberate minus infinity of an inactive speaker. + SpeakerCache cache(small_config().cache, std::vector(4, 0.0F)); + const std::vector probs{1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F}; + const auto scores = cache.frame_scores(probs, 3); + check(std::none_of(scores.begin(), scores.end(), [](float value) { return std::isnan(value); }), + "saturated probabilities give no NaN score"); +} + +void test_policy_checked_at_load() { + const auto load = [](DiarizationConfig config) { + return !refuses([&] { + DiarizationPipeline pipeline(std::make_unique(FakeEngine::Respond{}), + std::make_unique(FakeEngine::Respond{}), + std::move(config)); + }); + }; + check(load(small_config()), "the small configuration loads"); + auto no_factor = small_config(); + no_factor.cache.subsampling_factor = 0; + check(!load(no_factor), "a zero subsampling factor is refused at load"); + auto huge_silence = small_config(); + huge_silence.cache.silence_frames_per_speaker = std::numeric_limits::max(); + check(!load(huge_silence), "a cache budget that would overflow is refused at load"); + auto huge_cache = small_config(); + huge_cache.cache.cache_length = std::numeric_limits::max(); + check(!load(huge_cache), "a step longer than max_step_rows is refused without overflow"); + auto nan_threshold = small_config(); + nan_threshold.cache.score_threshold = std::numeric_limits::quiet_NaN(); + check(!load(nan_threshold), "a NaN score threshold is refused at load"); + for (const float floor : {0.0F, -0.25F, 1.0F}) { + auto config = small_config(); + config.cache.score_threshold = floor; + check(!load(config), "a score floor of " + std::to_string(floor) + " is refused at load"); + } + auto big_boost = small_config(); + big_boost.cache.weak_boosted_frames = big_boost.cache.cache_length + 1; + check(!load(big_boost), "a boost budget past the cache length is refused at load"); + auto loud_preemphasis = small_config(); + loud_preemphasis.front_end.preemphasis = 1.5F; + check(!load(loud_preemphasis), "a pre-emphasis outside [0, 1) is refused at load"); +} + +} // namespace + +int main() { + try { + std::ifstream file(data_path("runtime_golden.json")); + const auto golden = json::parse(file); + test_top_k(); + test_front_end(golden.at("front_end")); + test_speaker_cache(golden.at("speaker_cache")); + test_intervals(golden.at("intervals")); + test_max_gap(); + test_runtime_json(); + test_engine_io(); + test_pipeline_rejections(); + test_policy_checked_at_load(); + test_saturated_scores(); + test_boost_needs_its_frames(); + test_section_lengths(); + } catch (const std::exception& error) { + std::cerr << "ERROR: " << error.what() << '\n'; + ++failures; + } + std::cerr << (failures == 0 ? "ALL PASSED\n" : "SOME FAILED\n"); + return failures == 0 ? 0 : 1; +} diff --git a/families/nemotron3_diarization/tests/data/librispeech-test-clean-6930-75918-0003.wav b/families/nemotron3_diarization/tests/data/librispeech-test-clean-6930-75918-0003.wav new file mode 100644 index 0000000000..890b2d805f Binary files /dev/null and b/families/nemotron3_diarization/tests/data/librispeech-test-clean-6930-75918-0003.wav differ diff --git a/families/nemotron3_diarization/tests/data/maintainer-recording-16k-mono.wav b/families/nemotron3_diarization/tests/data/maintainer-recording-16k-mono.wav new file mode 100644 index 0000000000..ba144817e6 Binary files /dev/null and b/families/nemotron3_diarization/tests/data/maintainer-recording-16k-mono.wav differ diff --git a/families/nemotron3_diarization/tests/data/mel_filters.f32 b/families/nemotron3_diarization/tests/data/mel_filters.f32 new file mode 100644 index 0000000000..7385377af2 Binary files /dev/null and b/families/nemotron3_diarization/tests/data/mel_filters.f32 differ diff --git a/families/nemotron3_diarization/tests/data/runtime_golden.json b/families/nemotron3_diarization/tests/data/runtime_golden.json new file mode 100644 index 0000000000..64ce5250dc --- /dev/null +++ b/families/nemotron3_diarization/tests/data/runtime_golden.json @@ -0,0 +1 @@ +{"front_end": {"samples": [0.07388005405664444, 0.3356519937515259, 0.268477201461792, 0.06696746498346329, 0.09508253633975983, 0.40717360377311707, 0.6742029786109924, 0.611707866191864, 0.34990164637565613, 0.26196321845054626, 0.47511470317840576, 0.7039092183113098, 0.6237598061561584, 0.2962137758731842, 0.08978965878486633, 0.19986401498317719, 0.39542919397354126, 0.323836088180542, -0.025089049711823463, -0.30259737372398376, -0.2538428008556366, -0.047887515276670456, -0.05341556668281555, -0.35356375575065613, -0.6344479322433472, -0.5932480692863464, -0.33224451541900635, -0.22355769574642181, -0.42152485251426697, -0.6604409217834473, -0.6021838188171387, -0.2791078984737396, -0.052984192967414856, -0.14364702999591827, -0.34371528029441833, -0.292400598526001, 0.04975110664963722, 0.34612226486206055, 0.320966511964798, 0.11671002209186554, 0.10444292426109314, 0.39552950859069824, 0.6931287050247192, 0.677885115146637, 0.4234714210033417, 0.29861223697662354, 0.48376747965812683, 0.7345730662345886, 0.7014201283454895, 0.3872372508049011, 0.14478713274002075, 0.21697968244552612, 0.4213157296180725, 0.39107295870780945, 0.05774489417672157, -0.25626829266548157, -0.2560264468193054, -0.056443482637405396, -0.028724931180477142, -0.31176844239234924, -0.6275938153266907, -0.6422618627548218, -0.40036141872406006, -0.2649211585521698, -0.4413793981075287, -0.7081835865974426, -0.7063528299331665, -0.40932711958885193, -0.15863767266273499, -0.21872049570083618, -0.4330289661884308, -0.4311109483242035, -0.11577169597148895, 0.2068527638912201, 0.2245056927204132, 0.023938199505209923, -0.025761641561985016, 0.241033673286438, 0.5669674873352051, 0.6056198477745056, 0.3722589313983917, 0.22201113402843475, 0.38405123353004456, 0.6610211730003357, 0.6867907643318176, 0.40547680854797363, 0.14526726305484772, 0.19048109650611877, 0.41147029399871826, 0.43631258606910706, 0.13969609141349792, -0.1904253214597702, -0.22643490135669708, -0.02641650289297104, 0.04490678012371063, -0.20382505655288696, -0.5374839305877686, -0.599316418170929, -0.37518006563186646, -0.21010597050189972, -0.3555813431739807, -0.6396415829658508, -0.6912413239479065, -0.42549222707748413, -0.15518836677074432, -0.182753786444664, -0.4062190651893616, -0.45447471737861633, -0.1748671531677246, 0.16458819806575775, 0.2228962928056717, 0.029056156054139137, -0.05890478193759918, 0.174821674823761, 0.5186600089073181, 0.607579231262207, 0.3979562819004059, 0.22243507206439972, 0.3531005382537842, 0.6442866325378418, 0.7221841216087341, 0.4733154773712158, 0.19308403134346008, 0.2001335322856903, 0.4208366572856903, 0.48728036880493164, 0.2205692082643509, -0.132651224732399, -0.219831645488739, -0.040380947291851044, 0.056937918066978455, -0.166421577334404, -0.5233641862869263, -0.6424806118011475, -0.4506344199180603, -0.26580357551574707, -0.3788609504699707, -0.671319305896759, -0.769020140171051, -0.5308403968811035, -0.23334763944149017, -0.20993845164775848, -0.41637957096099854, -0.49089109897613525, -0.23013906180858612, 0.14143472909927368, 0.26127657294273376, 0.09869903326034546, -0.009297478012740612, 0.19695739448070526, 0.5560939311981201, 0.6929590702056885, 0.5059522390365601, 0.29725757241249084, 0.3757707476615906, 0.652079164981842, 0.7552084922790527, 0.5184597969055176, 0.19893522560596466, 0.1435837298631668, 0.33838340640068054, 0.43007802963256836, 0.1918734908103943, -0.176106259226799, -0.3047085702419281, -0.13489452004432678, 0.008326388895511627, -0.15625512599945068, -0.4960189461708069, -0.6362526416778564, -0.4490581154823303, -0.22000886499881744, -0.27453699707984924, -0.5525535941123962, -0.6874969005584717, -0.4863329231739044, -0.1826961487531662, -0.13206493854522705, -0.34758734703063965, -0.48360201716423035, -0.28845450282096863, 0.06549005210399628, 0.206119567155838, 0.046735454350709915, -0.10246481746435165, 0.05756464973092079, 0.42075681686401367, 0.6113088130950928, 0.4714622497558594, 0.26395320892333984, 0.32459867000579834, 0.6196166276931763, 0.786880612373352, 0.607424795627594, 0.29081010818481445, 0.2013210505247116, 0.383135050535202, 0.5053994059562683, 0.29889950156211853, -0.0869867354631424, -0.27418947219848633, -0.14474113285541534, 0.010363765992224216, -0.12346019595861435, -0.46907567977905273, -0.655714750289917, -0.5022885203361511, -0.25382155179977417, -0.26164790987968445, -0.5253356695175171, -0.6950685977935791, -0.5310260057449341, -0.2186894565820694, -0.12749646604061127, -0.3283519744873047, -0.5010008811950684, -0.3525554835796356, -0.00011606993211898953, 0.182546466588974, 0.05337686464190483, -0.11352337896823883, 0.01118068303912878, 0.3777156174182892, 0.6175824403762817, 0.5200090408325195, 0.30185166001319885, 0.3185484707355499, 0.5947271585464478, 0.7888607978820801, 0.6385906934738159, 0.3045288920402527, 0.16287070512771606, 0.31772956252098083, 0.4704318940639496, 0.3160524070262909, -0.05207907035946846, -0.25952625274658203, -0.1368086338043213, 0.061058998107910156, -0.01128600537776947, -0.33838340640068054, -0.565252959728241, -0.46267738938331604, -0.22736817598342896, -0.22399435937404633, -0.5062156915664673, -0.7431818842887878, -0.6480202674865723, -0.3486110270023346, -0.21657221019268036, -0.37891337275505066, -0.551656186580658, -0.41336944699287415, -0.03009903058409691, 0.2244425117969513, 0.1498313546180725, -0.026945041492581367, 0.044515181332826614, 0.3743680715560913, 0.6161388158798218, 0.5191856622695923, 0.25797566771507263, 0.20683668553829193, 0.45378363132476807, 0.6882050037384033, 0.6084542870521545, 0.31585168838500977, 0.1798679530620575, 0.351336270570755, 0.5612416863441467, 0.4693741202354431, 0.10798807442188263, -0.15894487500190735, -0.10732778906822205, 0.06101985648274422, -0.008966827765107155, -0.35212206840515137, -0.6294153928756714, -0.5655695199966431, -0.30642983317375183, -0.2288724184036255, -0.45129165053367615, -0.683702826499939, -0.6120483875274658, -0.31272244453430176, -0.15420027077198029, -0.3140631318092346, -0.5434488654136658, -0.48806771636009216, -0.14748889207839966, 0.12638406455516815, 0.0884728655219078, -0.08362650871276855, -0.029756175354123116, 0.3119697868824005, 0.6142082214355469, 0.5801585912704468, 0.32664257287979126, 0.23029270768165588, 0.4377979040145874, 0.6795488595962524, 0.6286037564277649, 0.33357954025268555, 0.15777337551116943, 0.3033871650695801, 0.5433802604675293, 0.5129501819610596, 0.18142741918563843, -0.11047868430614471, -0.09524426609277725, 0.07702478021383286, 0.044049184769392014, -0.28370940685272217, -0.5952085256576538, -0.5775854587554932, -0.32166215777397156, -0.2043192982673645, -0.40065258741378784, -0.6618952751159668, -0.6470402479171753, -0.3722589313983917, -0.18914413452148438, -0.3203883767127991, -0.561671257019043, -0.5421016812324524, -0.20526732504367828, 0.11625174432992935, 0.12975458800792694, -0.04516863450407982, -0.04533599317073822, 0.249857559800148, 0.5533193945884705, 0.5436676740646362, 0.2886812090873718, 0.1631937474012375, 0.3659096658229828, 0.6640342473983765, 0.6976222991943359, 0.4452526867389679, 0.24353238940238953, 0.3378297984600067, 0.5551156997680664, 0.5293715596199036, 0.18571455776691437, -0.1510266810655594, -0.16816355288028717, 0.037512198090553284, 0.09335453063249588, -0.160842627286911, -0.46780189871788025, -0.49647584557533264, -0.2813449203968048, -0.1794595867395401, -0.3996814489364624, -0.7203742861747742, -0.7675331234931946, -0.4936188757419586, -0.2346126139163971, -0.27269068360328674, -0.4759332835674286, -0.48334231972694397, -0.18897023797035217, 0.11193472146987915, 0.10804141312837601, -0.11586574465036392, -0.18170671164989471, 0.09415481239557266, 0.4621724784374237, 0.5602356791496277, 0.37540656328201294, 0.24657422304153442, 0.40938737988471985, 0.6826717853546143, 0.7080780267715454, 0.42804956436157227, 0.17294582724571228, 0.23837102949619293, 0.5016372799873352, 0.577946662902832, 0.31436705589294434, -0.019704248756170273, -0.08959481865167618, 0.07024369388818741, 0.11248145997524261, -0.15325599908828735, -0.49687260389328003, -0.5603273510932922, -0.32614386081695557, -0.14795662462711334, -0.29866859316825867, -0.6214007139205933, -0.7353392839431763, -0.5263118147850037, -0.2835009694099426, -0.30913954973220825, -0.517366886138916, -0.5500414967536926, -0.25713029503822327, 0.09127669036388397, 0.1449752002954483, -0.07388005405664444, -0.1961846798658371, 0.021025685593485832, 0.3864659070968628, 0.5282711982727051, 0.3744865655899048, 0.23337893187999725, 0.3739679753780365, 0.6622675657272339, 0.7340115308761597, 0.47864851355552673, 0.19753170013427734, 0.22249679267406464, 0.4873456656932831, 0.6101747155189514, 0.3815724551677704, 0.026785217225551605, -0.09390993416309357, 0.049170248210430145, 0.13109007477760315, -0.08477792143821716, -0.4238837957382202, -0.5253908038139343, -0.3210068643093109, -0.1364629715681076, -0.275112122297287, -0.6218379735946655, -0.7838360071182251, -0.5885545015335083, -0.2955755591392517, -0.2526310980319977, -0.44821465015411377, -0.5422840118408203, -0.3269807696342468, -0.006886979565024376, 0.07129459828138351, -0.11669320613145828, -0.22911876440048218, -0.001004149322398007, 0.401689350605011, 0.5821111798286438, 0.4130688011646271, 0.1923704594373703, 0.25466489791870117, 0.545382022857666, 0.7061671614646912, 0.551001250743866, 0.305313378572464, 0.2974332571029663, 0.5139462351799011, 0.6098165512084961, 0.3651586174964905, -0.010981902480125427, -0.13557688891887665, 0.058452311903238297, 0.23296494781970978, 0.07537039369344711, -0.30511343479156494, -0.5243274569511414, -0.41665321588516235, -0.23334763944149017, -0.2959336042404175, -0.5676565170288086, -0.7072708606719971, -0.5302920341491699, -0.26439040899276733, -0.25558051466941833, -0.5068268775939941, -0.6583564281463623, -0.4461558759212494, -0.04775436967611313, 0.13591954112052917, -0.015161103568971157, -0.1978876143693924, -0.08408612757921219, 0.26085126399993896, 0.4772931933403015, 0.3875725567340851, 0.2203574925661087, 0.2931557893753052, 0.5787975788116455, 0.7337048053741455, 0.5547845959663391, 0.26154404878616333, 0.22280475497245789, 0.47586432099342346, 0.6660974621772766, 0.4945420026779175, 0.10026193410158157, -0.11525470018386841, 0.005270686931908131, 0.1888028234243393, 0.0980818122625351, -0.23310242593288422, -0.4584406912326813, -0.3825302720069885, -0.21346667408943176, -0.2742992639541626, -0.5605841279029846, -0.7354360222816467, -0.5750666856765747, -0.2776365876197815, -0.2191682755947113, -0.46451249718666077, -0.6710753440856934, -0.5202022790908813, -0.12533707916736603, 0.10911206156015396, -0.002680276520550251, -0.20386996865272522, -0.13729985058307648, 0.19603575766086578, 0.45313921570777893, 0.4050191640853882, 0.22819072008132935, 0.2542996108531952, 0.5182440280914307, 0.7079634666442871, 0.5836657881736755, 0.3085530698299408, 0.24451586604118347, 0.4725559949874878, 0.6701667904853821, 0.5196911096572876, 0.12516839802265167, -0.10722246766090393, 0.019839506596326828, 0.24655935168266296, 0.18957403302192688, -0.17150898277759552, -0.47641274333000183, -0.4486708641052246, -0.23775677382946014, -0.20485489070415497, -0.4455561935901642, -0.6758139729499817, -0.6196740865707397, -0.3770596385002136, -0.2840937077999115, -0.455718070268631, -0.62366783618927, -0.49199944734573364, -0.1422271877527237, 0.055640485137701035, -0.07703258097171783, -0.2829865515232086, -0.19131314754486084, 0.20028561353683472, 0.5088487863540649, 0.4459136426448822, 0.18175025284290314, 0.12640054523944855, 0.40823912620544434, 0.7169570922851562, 0.705045223236084, 0.42516404390335083, 0.24551433324813843, 0.36728039383888245, 0.5760725140571594, 0.5399317145347595, 0.24940183758735657, 0.020268727093935013, 0.06586384028196335, 0.21367330849170685, 0.14325165748596191, -0.17421363294124603, -0.4253461956977844, -0.36795198917388916, -0.1615428775548935, -0.16731831431388855, -0.4687412679195404, -0.7439677119255066, -0.6721013784408569, -0.3539995551109314, -0.19505447149276733, -0.3888393044471741, -0.6638471484184265, -0.6251156330108643, -0.25763124227523804, 0.053032729774713516, 0.009041211567819118, -0.22801601886749268, -0.2536962032318115, 0.05982505530118942, 0.4085787832736969, 0.45422905683517456, 0.25148674845695496, 0.15829774737358093, 0.36126795411109924, 0.6406724452972412, 0.6712421774864197, 0.45042192935943604, 0.2900320887565613, 0.3931398391723633, 0.5844894647598267, 0.5512228608131409, 0.2683263421058655, 0.037479087710380554, 0.08431626111268997, 0.25147223472595215, 0.20347878336906433, -0.12072436511516571, -0.4104614853858948, -0.38302692770957947, -0.1610499918460846, -0.12287572771310806, -0.40760740637779236, -0.7197186350822449, -0.7004762887954712, -0.3941129744052887, -0.20059220492839813, -0.3646288216114044, -0.6562625169754028, -0.6604978442192078, -0.3098469376564026, 0.024620389565825462, 0.004057632759213448, -0.24804937839508057, -0.30787402391433716, 0.003791029565036297, 0.39293667674064636, 0.46956518292427063, 0.2420203536748886, 0.09563051164150238, 0.2915865182876587, 0.6352364420890808, 0.7342240214347839, 0.5030279159545898, 0.2620721459388733, 0.3147437870502472, 0.5591534972190857, 0.6328883767127991, 0.38947635889053345, 0.08222950249910355, 0.02569548599421978, 0.18789488077163696, 0.24513764679431915, 0.016147548332810402, -0.3008726239204407, -0.3944215774536133, -0.24940183758735657, -0.1585259586572647, -0.3268720209598541, -0.5980831980705261, -0.6636919975280762, -0.4736967980861664, -0.301434725522995, -0.3775670528411865, -0.5813296437263489, -0.60096675157547, -0.35098984837532043, -0.09059715270996094, -0.08272731304168701, -0.24466170370578766, -0.2565402090549469, 0.01153414323925972, 0.3194802403450012, 0.36795565485954285, 0.19319526851177216, 0.12163656949996948, 0.3378297984600067, 0.6339136958122253, 0.6764190793037415, 0.44474005699157715, 0.2626810669898987, 0.37488800287246704, 0.6218122243881226, 0.6446272730827332, 0.3570851981639862, 0.06492581218481064, 0.07031469792127609, 0.27608999609947205, 0.31138506531715393, 0.01944531686604023, -0.330491304397583, -0.38924261927604675, -0.18245285749435425, -0.07732775062322617, -0.30057963728904724, -0.6370744705200195, -0.7065406441688538, -0.45947349071502686, -0.24285785853862762, -0.34672218561172485, -0.6234691143035889, -0.6797570586204529, -0.39194291830062866, -0.0704309493303299, -0.05613096430897713, -0.2763476073741913, -0.34212711453437805, -0.0603606216609478, 0.31012094020843506, 0.39432042837142944, 0.1888284981250763, 0.06250503659248352, 0.2699170410633087, 0.6158998608589172, 0.7102357149124146, 0.47706013917922974, 0.251099169254303, 0.3368026912212372, 0.6103293299674988, 0.6848210692405701, 0.4187200665473938, 0.09974764287471771, 0.06700009852647781, 0.27036216855049133, 0.3430953919887543, 0.08665250241756439, -0.2699689567089081, -0.3712117671966553, -0.19591020047664642, -0.07599159330129623, -0.2565142512321472, -0.5769994854927063, -0.6849538683891296, -0.4937293529510498, -0.2870701849460602, -0.3438294231891632, -0.5787975788116455, -0.6614697575569153, -0.4470251500606537, -0.1580991894006729, -0.09217720478773117, -0.2423848807811737, -0.31707173585891724, -0.12073810398578644, 0.1976742297410965, 0.33882656693458557, 0.23145709931850433, 0.11409331113100052, 0.22562703490257263, 0.5020331144332886, 0.6585150361061096, 0.547810971736908, 0.3435520529747009, 0.3206688463687897, 0.508120059967041, 0.6491215825080872, 0.5231116414070129, 0.22963492572307587, 0.0719805434346199, 0.17518173158168793, 0.31894418597221375, 0.21233482658863068, -0.12474751472473145, -0.3684345781803131, -0.30076518654823303, -0.10281556099653244, -0.1313871443271637, -0.4460974931716919, -0.7098997235298157, -0.6219168305397034, -0.32617467641830444, -0.23645006120204926, -0.4839392304420471, -0.7256391048431396, -0.5949073433876038, -0.20350953936576843, -0.005674086976796389, -0.18788881599903107, -0.41009655594825745, -0.26412785053253174, 0.16643229126930237, 0.4131922125816345, 0.2564288079738617, 0.019102254882454872, 0.12072685360908508, 0.506528913974762, 0.729436457157135, 0.5581136345863342, 0.2753414511680603, 0.27955126762390137, 0.5540183186531067, 0.7131215333938599, 0.5265849828720093, 0.20433613657951355, 0.09634020924568176, 0.24377965927124023, 0.35832494497299194, 0.20706936717033386, -0.1094902977347374, -0.3024754822254181, -0.2451065480709076, -0.10877267271280289, -0.15044930577278137, -0.406436562538147, -0.6392890810966492, -0.6113209128379822, -0.383994996547699, -0.26845914125442505, -0.43925386667251587, -0.6802711486816406, -0.636773407459259, -0.2957140803337097, -0.04130276292562485, -0.15112155675888062, -0.39627695083618164, -0.3338429927825928, 0.07388005405664444], "features": [[-7.541508674621582, -7.39021110534668, -7.241293907165527, -6.563910961151123, -6.696253776550293, -6.6567487716674805, -6.591009140014648, -6.121697425842285, -6.280077934265137, -5.933187484741211, -5.604507923126221, -4.246814250946045, -3.972249984741211, -3.3971285820007324, -2.924391031265259, -1.375331163406372, -0.9647427797317505, -0.7932735681533813, -0.5697038173675537, -0.49746984243392944, -1.5512244701385498, -1.9861606359481812, -2.7849347591400146, -3.1937074661254883, -3.7688136100769043, -4.033028602600098, -4.44089412689209, -4.567569732666016, -4.838278770446777, -4.958737373352051, -5.087372779846191, -5.30709981918335, -5.65811014175415, -5.715610504150391, -5.692986488342285, -5.83370304107666, -6.257436275482178, -6.314761638641357, -6.259284019470215, -6.346539497375488, -6.7738356590271, -6.837907791137695, -6.8293681144714355, -6.860772132873535, -7.244072437286377, -7.345771789550781, -7.480937957763672, -7.635374546051025, -7.774735450744629, -7.969235420227051, -8.156110763549805, -8.381999015808105, -8.671674728393555, -8.9229097366333, -9.195612907409668, -9.547764778137207, -9.940908432006836, -10.343915939331055, -10.674656867980957, -10.791163444519043, -10.630620956420898, -10.159771919250488, -9.710189819335938, -9.387989044189453, -9.028974533081055, -8.531845092773438, -8.394702911376953, -8.008772850036621, -7.772477626800537, -7.528970718383789, -7.272419452667236, -7.034703254699707, -6.8743486404418945, -6.526426315307617, -6.40561056137085, -6.182773590087891, -5.888215065002441, -5.682216644287109, -5.451155185699463, -5.192492485046387, -4.917396545410156, -4.6199798583984375, -4.291858196258545, -3.921961784362793, -3.4912397861480713, -2.964841365814209, -2.1751105785369873, -0.810877799987793, 1.1441906690597534, 1.5510385036468506, -0.058688532561063766, -1.762573003768921, -2.597355842590332, -3.092137336730957, -3.542656183242798, -3.881885528564453, -4.1645612716674805, -4.414302825927734, -4.637856483459473, -4.840539455413818, -5.026357650756836, -5.198275566101074, -5.350991725921631, -5.486159324645996, -5.651700496673584, -5.747835159301758, -5.9007368087768555, -6.011585235595703, -6.114051818847656, -6.230411052703857, -6.336563587188721, -6.434494495391846, -6.526137828826904, -6.628971099853516, -6.717873573303223, -6.794363975524902, -6.886251449584961, -6.964670181274414, -7.036479949951172, -7.106325149536133, -7.173305988311768, -7.236601829528809, -7.295433521270752, -7.33443546295166, -7.387361526489258, -7.415433406829834, -7.44050407409668, -7.459638595581055], [-12.76563549041748, -12.555656433105469, -12.363842964172363, -11.14450740814209, -11.028416633605957, -11.350821495056152, -11.872682571411133, -11.227686882019043, -11.769285202026367, -9.335137367248535, -8.575194358825684, -7.340487480163574, -7.012904167175293, -6.101183891296387, -5.504934787750244, -3.5255725383758545, -0.3021361231803894, 0.2991905212402344, 0.8006132245063782, 0.48381340503692627, -1.823108434677124, -2.9743261337280273, -7.466428279876709, -5.677549839019775, -5.495321273803711, -5.484522819519043, -5.430466651916504, -5.484006404876709, -5.35195779800415, -5.254326820373535, -5.065552234649658, -5.104487895965576, -5.15568208694458, -5.096719741821289, -4.93271017074585, -4.916030406951904, -5.030001163482666, -5.038308143615723, -4.970537185668945, -4.837945461273193, -5.07533073425293, -5.127868175506592, -5.163190841674805, -4.870725154876709, -5.33542537689209, -5.318416595458984, -5.3836236000061035, -5.519569396972656, -5.58682107925415, -5.809370517730713, -5.888923168182373, -6.235914707183838, -6.396547794342041, -6.845373630523682, -7.030266761779785, -7.621938705444336, -8.020524024963379, -8.637702941894531, -9.253992080688477, -9.831838607788086, -10.589457511901855, -11.057575225830078, -12.213268280029297, -12.072834014892578, -13.1770601272583, -12.271968841552734, -12.908478736877441, -12.236374855041504, -12.26014518737793, -11.95097541809082, -11.789750099182129, -11.543611526489258, -11.424349784851074, -11.078398704528809, -10.983759880065918, -10.756876945495605, -10.488977432250977, -10.265663146972656, -10.067816734313965, -9.785764694213867, -9.539206504821777, -9.226081848144531, -8.895892143249512, -8.555403709411621, -8.062387466430664, -7.542239189147949, -6.745047569274902, -3.70914363861084, 1.92811918258667, 2.5695579051971436, -1.0557780265808105, -6.265056610107422, -7.262277603149414, -7.738724231719971, -8.182743072509766, -8.52658462524414, -8.811176300048828, -9.060750961303711, -9.2833251953125, -9.484749794006348, -9.669282913208008, -9.840032577514648, -9.991772651672363, -10.12594223022461, -10.289987564086914, -10.385122299194336, -10.536422729492188, -10.645909309387207, -10.746767044067383, -10.861392974853516, -10.965862274169922, -11.061966896057129, -11.151618003845215, -11.252198219299316, -11.33895492553711, -11.413257598876953, -11.502547264099121, -11.578566551208496, -11.647831916809082, -11.71509075164795, -11.779487609863281, -11.840235710144043, -11.896599769592285, -11.933465003967285, -11.984254837036133, -12.010696411132812, -12.034456253051758, -12.052726745605469], [-15.143619537353516, -14.597596168518066, -14.2252197265625, -13.764427185058594, -15.121516227722168, -15.245445251464844, -15.346470832824707, -12.424551963806152, -11.688528060913086, -11.538299560546875, -11.364908218383789, -13.479852676391602, -9.556431770324707, -7.257100582122803, -6.464271068572998, -3.2640273571014404, -0.2722203731536865, 0.31280261278152466, 0.8064144849777222, 0.41814565658569336, -2.0207834243774414, -3.308126449584961, -6.504549503326416, -11.876699447631836, -10.197319984436035, -10.212471008300781, -10.269651412963867, -12.092833518981934, -10.713160514831543, -10.202259063720703, -9.668854713439941, -8.990392684936523, -8.683929443359375, -8.383357048034668, -7.963007926940918, -7.3552632331848145, -7.2974324226379395, -7.104689121246338, -6.7591471672058105, -6.253509998321533, -6.283742904663086, -6.130523681640625, -5.858206272125244, -5.398327827453613, -5.4283881187438965, -5.252772331237793, -5.078808784484863, -4.909468173980713, -4.748223781585693, -4.595427989959717, -4.429901123046875, -4.312707901000977, -4.228140830993652, -4.128534317016602, -4.012280464172363, -3.923151731491089, -3.880436897277832, -3.838168144226074, -3.811464309692383, -3.8020429611206055, -3.8095431327819824, -3.755675792694092, -3.7997703552246094, -3.9498212337493896, -4.025561809539795, -4.008395195007324, -4.343453884124756, -4.429224014282227, -4.695598125457764, -5.01252555847168, -5.340359687805176, -5.834112644195557, -6.430761814117432, -7.062849521636963, -8.044332504272461, -8.91645622253418, -9.946773529052734, -11.209808349609375, -12.388140678405762, -13.670929908752441, -14.616713523864746, -14.71927261352539, -14.640847206115723, -13.014010429382324, -12.863940238952637, -10.369016647338867, -9.018218994140625, -3.900826930999756, 1.9282708168029785, 2.5722951889038086, -1.097338318824768, -8.124340057373047, -10.675511360168457, -12.064048767089844, -14.066591262817383, -14.635090827941895, -15.459038734436035, -16.091745376586914, -16.24239730834961, -16.445261001586914, -16.546884536743164, -16.573360443115234, -16.59833526611328, -16.616331100463867, -16.623647689819336, -16.62699317932129, -16.630126953125, -16.63210678100586, -16.633291244506836, -16.63401222229004, -16.63445472717285, -16.6347599029541, -16.634981155395508, -16.635143280029297, -16.63525390625, -16.635324478149414, -16.63538360595703, -16.635421752929688, -16.635448455810547, -16.635469436645508, -16.635486602783203, -16.635496139526367, -16.63550567626953, -16.635509490966797, -16.635515213012695, -16.63551902770996, -16.635520935058594, -16.635520935058594], [-15.490790367126465, -14.940674781799316, -14.567117691040039, -14.000823974609375, -15.178128242492676, -15.365443229675293, -15.571340560913086, -12.530054092407227, -11.725296020507812, -11.550128936767578, -11.355676651000977, -13.345053672790527, -9.570716857910156, -7.256409168243408, -6.462667465209961, -3.262110710144043, -0.2726329267024994, 0.3126554489135742, 0.8064013719558716, 0.41893836855888367, -2.0226123332977295, -3.313415050506592, -6.514351844787598, -11.196369171142578, -10.899982452392578, -10.811342239379883, -10.654885292053223, -11.357954978942871, -13.21927547454834, -14.151963233947754, -15.9158296585083, -13.905252456665039, -14.247861862182617, -14.515639305114746, -15.09837532043457, -16.57301139831543, -16.060352325439453, -15.859884262084961, -15.568299293518066, -15.869546890258789, -16.460155487060547, -16.388031005859375, -16.104543685913086, -15.556678771972656, -15.709820747375488, -15.554826736450195, -15.105450630187988, -14.541584014892578, -14.011320114135742, -13.51915168762207, -12.872859001159668, -12.168638229370117, -11.530853271484375, -10.88395881652832, -10.168251037597656, -9.452957153320312, -8.799052238464355, -8.166242599487305, -7.575778007507324, -7.033714771270752, -6.543328762054443, -5.983534812927246, -5.541398525238037, -5.251056671142578, -4.921111106872559, -4.451939582824707, -4.342895984649658, -3.9905993938446045, -3.7979254722595215, -3.6109187602996826, -3.425851583480835, -3.2847821712493896, -3.2323834896087646, -3.0341994762420654, -3.0933804512023926, -3.0649452209472656, -3.0240390300750732, -3.1297569274902344, -3.2501611709594727, -3.408113718032837, -3.628317356109619, -3.9332494735717773, -4.3223114013671875, -4.844339370727539, -5.559525966644287, -6.37070894241333, -7.015172481536865, -3.8974897861480713, 1.9291508197784424, 2.571990728378296, -1.0955085754394531, -8.071463584899902, -10.634278297424316, -11.992757797241211, -13.988962173461914, -14.601604461669922, -15.400660514831543, -16.071613311767578, -16.229015350341797, -16.431333541870117, -16.542560577392578, -16.570802688598633, -16.595958709716797, -16.614946365356445, -16.623069763183594, -16.62654685974121, -16.629770278930664, -16.63187026977539, -16.63313865661621, -16.633901596069336, -16.63437271118164, -16.634706497192383, -16.63494110107422, -16.635114669799805, -16.635234832763672, -16.63530921936035, -16.635372161865234, -16.635412216186523, -16.63544273376465, -16.635465621948242, -16.635480880737305, -16.635494232177734, -16.6355037689209, -16.635509490966797, -16.635515213012695, -16.63551902770996, -16.635520935058594, -16.635520935058594], [-11.771695137023926, -11.742350578308105, -11.699126243591309, -11.2036714553833, -10.9730224609375, -10.889491081237793, -10.784286499023438, -10.437344551086426, -9.847328186035156, -9.523233413696289, -9.216561317443848, -9.369349479675293, -8.631705284118652, -6.847816467285156, -6.09560489654541, -3.2102837562561035, -0.26321905851364136, 0.3079870939254761, 0.7947037816047668, 0.42683055996894836, -2.0020461082458496, -3.269566535949707, -6.106786727905273, -8.869772911071777, -9.038741111755371, -8.932437896728516, -8.719609260559082, -9.133464813232422, -10.073461532592773, -10.123140335083008, -9.9518461227417, -9.852619171142578, -10.578879356384277, -10.704768180847168, -10.696460723876953, -10.508891105651855, -11.055718421936035, -11.182214736938477, -11.226698875427246, -11.10089111328125, -11.536189079284668, -11.638470649719238, -11.710612297058105, -11.640278816223145, -11.983931541442871, -12.10872745513916, -12.248664855957031, -12.370361328125, -12.462158203125, -12.629182815551758, -12.804177284240723, -12.94460678100586, -13.14424991607666, -13.351391792297363, -13.449878692626953, -13.597297668457031, -13.832340240478516, -13.867310523986816, -13.899880409240723, -14.030640602111816, -13.849739074707031, -13.60749340057373, -13.667649269104004, -13.252273559570312, -13.207551002502441, -12.874711990356445, -12.48007583618164, -12.654637336730957, -11.622690200805664, -11.905829429626465, -10.5044584274292, -10.115104675292969, -9.046677589416504, -8.003405570983887, -7.218774795532227, -6.370053291320801, -5.576629638671875, -4.975947380065918, -4.460518836975098, -4.013967990875244, -3.630520820617676, -3.3074469566345215, -3.042191982269287, -2.832209587097168, -2.679051160812378, -2.6019132137298584, -2.469630241394043, -2.382610321044922, 1.815216064453125, 2.541700601577759, -0.8466613292694092, -3.1642568111419678, -3.9507884979248047, -4.891759395599365, -5.6635260581970215, -6.461269855499268, -7.286982536315918, -7.968876838684082, -8.448758125305176, -8.787009239196777, -9.045100212097168, -9.256505966186523, -9.430217742919922, -9.574525833129883, -9.741032600402832, -9.832255363464355, -9.975486755371094, -10.073341369628906, -10.159627914428711, -10.25694465637207, -10.34210205078125, -10.417112350463867, -10.484071731567383, -10.560747146606445, -10.622424125671387, -10.670594215393066, -10.733352661132812, -10.782402038574219, -10.824712753295898, -10.865117073059082, -10.903364181518555, -10.939144134521484, -10.97227954864502, -10.987683296203613, -11.019908905029297, -11.03088092803955, -11.042927742004395, -11.053878784179688], [-0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0]], "features_float64": [[-7.541507472500746, -7.390209363837865, -7.241291666453172, -6.56391086650023, -6.69625473178018, -6.656748628413882, -6.59100822183309, -6.121697292972211, -6.280077790462384, -5.933187842748791, -5.604508439571536, -4.246814489702893, -3.9722499496489174, -3.3971287128673873, -2.924391102110612, -1.3753312827085964, -0.9647426779132998, -0.7932734767535109, -0.5697035877361448, -0.4974698888701662, -1.5512244528186752, -1.9861606952820061, -2.7849347275701395, -3.193707595327686, -3.768813529063664, -4.033028919452318, -4.440895103140002, -4.567569775154644, -4.838278631343524, -4.958737021779354, -5.087372803530319, -5.307099797288235, -5.658110071419696, -5.715610578583159, -5.692986049267748, -5.833704113281981, -6.25743756851301, -6.314762924895576, -6.259284351144714, -6.346540678517414, -6.773834563787793, -6.83790646199002, -6.829367332363366, -6.860770616575709, -7.244071567834279, -7.345771146572486, -7.48093635712469, -7.635371038066444, -7.7747329819099855, -7.969234708669059, -8.15610857251055, -8.382002884301976, -8.671675762646514, -8.922905159168483, -9.19561376080051, -9.547762688141058, -9.940904685253933, -10.343913658653616, -10.674649286268007, -10.791160263619805, -10.630620520865492, -10.15976702043653, -9.71019215386089, -9.387988304092492, -9.028975186661867, -8.53184646053002, -8.394705182226177, -8.008773540572282, -7.772476588554079, -7.528969797213157, -7.272418903300117, -7.034703853471715, -6.874348543380251, -6.526426338171638, -6.40561122013435, -6.1827726755520365, -5.888215458436349, -5.6822169871320645, -5.451155159002437, -5.192492598520664, -4.917396458318912, -4.619979530208896, -4.291858145795755, -3.921961660696975, -3.491239856050788, -2.9648416381333567, -2.175110752424376, -0.810877710069096, 1.1441907044926005, 1.5510385760659924, -0.05868839676257077, -1.7625731029467637, -2.5973559864549234, -3.0921373673508095, -3.5426562632665113, -3.881885106554553, -4.164561125295747, -4.414302612305039, -4.637856221291744, -4.840539143627118, -5.026357478710242, -5.198275679506717, -5.350991705106389, -5.486159585024151, -5.65170050037449, -5.747835285762217, -5.900736360292387, -6.011585429380868, -6.114051882542615, -6.230410444890575, -6.33656369147235, -6.434493839826597, -6.526137938865822, -6.628970596291786, -6.717873722559462, -6.794363412981623, -6.8862517574201, -6.964670580509979, -7.03648059624755, -7.10632554763517, -7.173306159773815, -7.236602310461899, -7.295433219690236, -7.3344350794558055, -7.3873619192391535, -7.415433170808703, -7.440503840950363, -7.459638568622409], [-12.765614515430984, -12.555638218746466, -12.363827048957832, -11.144504560153024, -11.028361474898277, -11.350780200636663, -11.872679821590017, -11.227692122168598, -11.769270661897066, -9.335136518752895, -8.575193915895957, -7.340487209319662, -7.012904598388953, -6.101183748103072, -5.504934364081979, -3.525572643606634, -0.3021362442320495, 0.29919061270987485, 0.8006133592324458, 0.4838133443338289, -1.8231084191115263, -2.974326213233145, -7.466427774723995, -5.677550768132222, -5.495322784191403, -5.484523710015662, -5.430467053630247, -5.484006201081862, -5.351958485198352, -5.254327744150085, -5.065552912740492, -5.104488306846836, -5.1556816761091335, -5.096718877695569, -4.932709297360772, -4.916029974833828, -5.030003712743953, -5.038310883201346, -4.97053865745075, -4.8379472065175335, -5.075330303613262, -5.12786763671757, -5.163191195052185, -4.8707255903453595, -5.335426363962014, -5.318417899408271, -5.383624693128601, -5.5195700511884604, -5.5868217405693725, -5.80937045768723, -5.888923301016763, -6.2359140667843045, -6.3965487213958365, -6.8453725234130856, -7.030266368213434, -7.621935375885599, -8.02052609155822, -8.637706460509877, -9.253994669818805, -9.83184018985379, -10.589453993958786, -11.057581681031682, -12.213252240650498, -12.072828971850678, -13.177053628783693, -12.271956508483784, -12.908509425531943, -12.236373461432839, -12.260128834223602, -11.95096433313001, -11.7897415256106, -11.543615771432611, -11.424349145447227, -11.078378693372605, -10.98376139389304, -10.756883807164948, -10.488980021588862, -10.265666902493681, -10.067818875577315, -9.785766867887322, -9.539207107178896, -9.22606877970007, -8.89589245521382, -8.555403851082737, -8.062387076317334, -7.542237443034648, -6.745046645831157, -3.709143390094315, 1.9281190921995248, 2.5695579409854075, -1.055778105527577, -6.265055800586814, -7.262276265479622, -7.738723013242035, -8.182742411597715, -8.52657801380294, -8.81117783473733, -9.060750244055056, -9.283323007847434, -9.484750677374134, -9.66928346815183, -9.840031888041947, -9.99177165644551, -10.125939564595203, -10.289986140116973, -10.385123681496845, -10.536420079651256, -10.645916566501123, -10.746767560484281, -10.861397866620049, -10.965869508699, -11.061971909439142, -11.151618996867569, -11.252190363396968, -11.338952428935558, -11.413247246141223, -11.502550861279103, -11.578562212400469, -11.647828137616445, -11.715092379006617, -11.779483776218717, -11.840240753056818, -11.896606081188505, -11.93346290168129, -11.984254011499981, -12.010688842220471, -12.034464668817757, -12.0527331726671], [-15.143481056235421, -14.597623211845566, -14.225316428281465, -13.764212983061604, -15.121450870203097, -15.245430841699635, -15.346517231412685, -12.424554847794067, -11.688523356717234, -11.538299996048792, -11.364913999506388, -13.479829978884474, -9.556433125048041, -7.257099054428402, -6.464269526668858, -3.2640274032800156, -0.27222024203325873, 0.3128027394440646, 0.8064145295831256, 0.4181455581989273, -2.0207836111127486, -3.3081264805092006, -6.50454929501638, -11.876707847751845, -10.197328811566193, -10.212477552562088, -10.269652422070111, -12.092855559815552, -10.713156973778652, -10.20225904660303, -9.668857273853027, -8.990389382903736, -8.683928582405297, -8.38335819135671, -7.963010265546284, -7.355262509029366, -7.297433775531153, -7.104690084341318, -6.759148104686843, -6.253509514786529, -6.283744421861826, -6.1305247638755445, -5.858207198388507, -5.398327666203467, -5.42838849142388, -5.252773142327545, -5.078808639600619, -4.9094672120042375, -4.748222849081046, -4.595427555904456, -4.429901018843485, -4.3127076864187845, -4.228141003411744, -4.128534195524775, -4.012280036352614, -3.9231516411352545, -3.880436842333737, -3.838168214075277, -3.811464596560606, -3.8020430103051126, -3.809542936540868, -3.755675729985052, -3.79977026115941, -3.9498210426613407, -4.025561898898522, -4.008394829569679, -4.34345350380242, -4.429223234983275, -4.695598561567443, -5.012526379143757, -5.3403591624402615, -5.834113042647201, -6.43076316758858, -7.062852901523067, -8.04433205479541, -8.916456202551318, -9.946774941536175, -11.20981423239705, -12.38813137651472, -13.6709401988835, -14.61667171135305, -14.71920395265413, -14.640826857163605, -13.014017300100296, -12.863946769283118, -10.36901884134434, -9.018218150322273, -3.900827216558534, 1.9282706412623791, 2.5722952963586776, -1.0973381551858528, -8.124338976107337, -10.675514907351145, -12.064058091567523, -14.066536737216449, -14.635062621317994, -15.45902325813846, -16.091723557679362, -16.242433564756716, -16.445357312163182, -16.546887402675093, -16.573378527529815, -16.598320333815867, -16.616337266963264, -16.623658463009722, -16.62698452990071, -16.630129778038416, -16.632109335527293, -16.63329267363035, -16.6339994021048, -16.634446314023105, -16.634760628513114, -16.63497862921459, -16.635142885493583, -16.635255044277226, -16.635325557695328, -16.63538375359454, -16.6354219726806, -16.635449176709106, -16.63546998310856, -16.63548556065321, -16.635496881618078, -16.635504598689742, -16.635510050092, -16.63551483239732, -16.63551839563756, -16.635520230070203, -16.63552129167046], [-15.49073203438402, -14.940661745016966, -14.567123602362194, -14.00075325167292, -15.178269297603812, -15.365530113978247, -15.571330898255425, -12.530023475816206, -11.725320785402374, -11.550141502222331, -11.355679325334734, -13.34507943333924, -9.570714925826667, -7.256409572764812, -6.462668000067289, -3.2621107741218967, -0.2726329158651566, 0.3126555858057894, 0.8064016163856198, 0.4189382336919698, -2.0226124156943346, -3.313415136482533, -6.514351293365161, -11.196335513093041, -10.899964861115931, -10.811332509581947, -10.654884095596667, -11.357965541485118, -13.219275993709475, -14.151964871592789, -15.915979389623953, -13.905247865697953, -14.247854270963447, -14.515643419197335, -15.098432699226088, -16.57303330761971, -16.060053106066032, -15.859714113751133, -15.568319162948248, -15.869433234442905, -16.46011334320794, -16.388004884543932, -16.10451651661298, -15.556618684028303, -15.70986392871342, -15.554897194429685, -15.105487317527874, -14.541582122773061, -14.011305910590112, -13.519148728062886, -12.872864811810231, -12.168619485705124, -11.530832720861682, -10.883964278718441, -10.16826016069837, -9.45296213026312, -8.79905637974817, -8.166242663468907, -7.575778712944573, -7.033715709840049, -6.5433283792019346, -5.983532731654793, -5.541399152488532, -5.251056273859827, -4.9211116411647655, -4.451939740639279, -4.3428956601321484, -3.990599910430574, -3.79792613770559, -3.610918845546008, -3.4258516228508173, -3.2847822687128105, -3.2323833653578973, -3.0341999692105994, -3.093380518335896, -3.0649452772593935, -3.0240389602086015, -3.1297571375773994, -3.2501612259341197, -3.408113744332853, -3.6283176901498275, -3.9332491691988682, -4.322310726510812, -4.844338720110031, -5.559525347041284, -6.370708599784602, -7.0151717750026, -3.897489704879895, 1.9291508509211301, 2.5719907430799935, -1.0955085364176909, -8.071462939175186, -10.634280256421537, -11.992762326200651, -13.988926888831, -14.601587592576033, -15.400666225117138, -16.071639796921517, -16.229064686902422, -16.431318267598968, -16.542628503252885, -16.57084731608653, -16.59595924632732, -16.614945421210365, -16.623077960857973, -16.626557246910973, -16.629768561823493, -16.631871302439396, -16.633137123819665, -16.63390278806006, -16.634375980773367, -16.634707987439917, -16.63494181786837, -16.635113202227423, -16.635235238428347, -16.63531007791561, -16.635373576024193, -16.635413955750167, -16.635443720088283, -16.635466498031015, -16.63548303178761, -16.63549497415948, -16.635503602422578, -16.63550952548829, -16.6355147986778, -16.6355186951971, -16.63552060543451, -16.635521644745065], [-11.77166810741494, -11.74233329029815, -11.699118170094401, -11.203691716081691, -10.973050044962445, -10.889503032051374, -10.784283740609768, -10.437337985411789, -9.847325024622553, -9.523231863094336, -9.216560901698617, -9.369354289916533, -8.631705555194186, -6.847815675485596, -6.095603963644387, -3.210284065854993, -0.2632190291691871, 0.3079870622778916, 0.7947037879518242, 0.4268306333391835, -2.0020460202184465, -3.2695663434515243, -6.106786920796022, -8.869789922492403, -9.038742756567313, -8.932436830502933, -8.71960584466293, -9.133465546639803, -10.073463789099272, -10.123140713894077, -9.951842608860838, -9.852613503028516, -10.578890933529062, -10.70477972145563, -10.696465629843058, -10.50888486556721, -11.055725150508742, -11.18220664985969, -11.22665397948825, -11.100894100445645, -11.536171170038648, -11.638454542823467, -11.710611507250436, -11.640310792559182, -11.983927824695693, -12.108690799858152, -12.24859100596247, -12.37029768437193, -12.46221247604578, -12.629185098841196, -12.804155439887673, -12.944602923372736, -13.144251503727693, -13.351376655034539, -13.449878098610771, -13.597316471921728, -13.832320419364716, -13.867309625372407, -13.899912213020967, -14.030631850403157, -13.849751047144217, -13.607502811566533, -13.667751695870972, -13.252290750627667, -13.207542585221324, -12.87471795750217, -12.480073001352237, -12.654621836101857, -11.622693700122674, -11.905824451159866, -10.50445707522623, -10.115104378844624, -9.046673591239815, -8.003406497948196, -7.218775530320812, -6.37005358927725, -5.576629917754049, -4.975947083124206, -4.460518708390819, -4.013967735538721, -3.6305206700038117, -3.307446968325186, -3.042191783270463, -2.832209620218145, -2.6790511336647236, -2.6019135050791817, -2.469630344206392, -2.3826105749602906, 1.8152161035256038, 2.5417007479949456, -0.846661407602222, -3.1642566166635593, -3.950788352914063, -4.8917596853738425, -5.663526185627741, -6.461270464276876, -7.286982695512377, -7.968876248774127, -8.448758738048893, -8.787008455614925, -9.045100537008594, -9.256508138548496, -9.430218716379214, -9.574527654442667, -9.741034480091667, -9.832254420844519, -9.975488980184924, -10.073344346836743, -10.159629204755152, -10.256939160780387, -10.342104277365527, -10.417112701534924, -10.48407380442704, -10.560743841851837, -10.62242263005266, -10.670598014908109, -10.73335247471775, -10.782403011007068, -10.824716898200112, -10.865119038888965, -10.903364918639074, -10.939143509852538, -10.972276151155869, -10.987683431071703, -11.019901849125473, -11.030879419684537, -11.042920775171803, -11.053877646031678], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], "valid_frames": 5}, "speaker_cache": {"policy": {"num_speakers": 3, "subsampling_factor": 2, "hidden_size": 6, "cache_length": 12, "silence_frames_per_speaker": 1, "fifo_length": 4, "update_period": 3, "score_threshold": 0.25, "latest_frames_boost": 0.05, "min_positive_scores": 1, "strong_boosted_frames": 2, "weak_boosted_frames": 4}, "silence": [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], "steps": [{"step_input": [[-1.6902153491973877, 1.7454077005386353, -1.4815342426300049, 0.4056456685066223, 2.380732774734497, 1.2582863569259644], [-1.0405282974243164, -0.3898184597492218, 0.6496017575263977, -1.7215901613235474, 0.5778094530105591, 0.8384053707122803], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [1.253964900970459, 0.7886534929275513, -1.6647926568984985, 1.2520029544830322, 0.448635995388031, 1.0780999660491943], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [3.397941827774048, 0.3272615969181061, -0.28815609216690063, -0.2434522658586502, 0.5819754004478455, 0.9288422465324402], [-1.0730987787246704, -0.24100561439990997, -1.0433144569396973, -0.8116680383682251, -0.3700059950351715, -0.5408837199211121]], "logits": [[3.332747459411621, -0.2833798825740814, -1.4651880264282227], [6.504363059997559, -0.09826083481311798, -2.1877787113189697], [2.2195379734039307, -1.3158278465270996, 1.3706742525100708], [4.746417999267578, -1.6731948852539062, -0.6818966865539551], [8.72099494934082, -3.672879219055176, 3.2624073028564453], [-0.70078444480896, -6.578463554382324, -3.3321897983551025], [1.2810249328613281, -0.06531903147697449, 1.160973310470581], [4.79768705368042, -1.0974986553192139, -4.4707512855529785], [-0.9778323173522949, 0.14408932626247406, 5.860234260559082], [4.8692946434021, 0.9346688985824585, -2.4035398960113525], [1.4514614343643188, 2.648237466812134, 3.032196044921875], [1.4301526546478271, -2.701425075531006, 3.4017720222473145], [2.1302595138549805, -3.43179988861084, -2.0205254554748535], [1.3885791301727295, 1.8023350238800049, 4.27439022064209]], "valid": [1, 1, 1, 1, 1, 1, 1], "chunk_frames": 5, "lookback_frames": 0, "cache_rows": 3, "fifo_rows": 2, "compressed": false, "cache": [[-1.6902153491973877, 1.7454077005386353, -1.4815342426300049, 0.4056456685066223, 2.380732774734497, 1.2582863569259644], [-1.0405282974243164, -0.3898184597492218, 0.6496017575263977, -1.7215901613235474, 0.5778094530105591, 0.8384053707122803], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452]], "cache_probs": [[0.9820203185081482, 0.45253992080688477, 0.14426422119140625], [0.9466912150382996, 0.18475598096847534, 0.5666635632514954], [0.6657376289367676, 0.01308097131550312, 0.4987998306751251]], "fifo": [[1.253964900970459, 0.7886534929275513, -1.6647926568984985, 1.2520029544830322, 0.448635995388031, 1.0780999660491943], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083]]}, {"step_input": [[-1.6902153491973877, 1.7454077005386353, -1.4815342426300049, 0.4056456685066223, 2.380732774734497, 1.2582863569259644], [-1.0405282974243164, -0.3898184597492218, 0.6496017575263977, -1.7215901613235474, 0.5778094530105591, 0.8384053707122803], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [1.253964900970459, 0.7886534929275513, -1.6647926568984985, 1.2520029544830322, 0.448635995388031, 1.0780999660491943], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.40674862265586853, -0.07591209560632706, 0.07073015719652176, -0.62159663438797, 0.2137121707201004, -0.8957604169845581], [-1.5906429290771484, 1.2326383590698242, -0.5130079388618469, 0.04086293652653694, -0.5561856031417847, -2.3698203563690186], [-1.5125060081481934, 1.336596965789795, 0.8586768507957458, 0.523654043674469, -0.4376985430717468, -0.13509657979011536], [0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [0.05285830423235893, -2.052243232727051, 0.27110710740089417, -1.2543226480484009, -0.18498015403747559, 0.0008936904487200081], [-1.5873304605484009, 0.4325268268585205, -1.2522718906402588, -1.2017256021499634, 0.1559959352016449, -2.227620840072632], [-0.1138024851679802, -0.8704981207847595, 1.4741312265396118, 0.45486071705818176, 0.5376980304718018, -0.12902222573757172]], "logits": [[-1.833423137664795, 1.974473476409912, 0.5432952046394348], [1.041804313659668, 2.954545497894287, 4.507049083709717], [-4.241372108459473, 4.886767387390137, 2.0834333896636963], [-1.3281309604644775, -1.220567226409912, 0.07615967839956284], [-0.7590917348861694, 3.6690964698791504, 1.5589568614959717], [2.968843460083008, 1.7887835502624512, -0.08149003982543945], [-1.9991865158081055, 4.925793170928955, -4.507297515869141], [-0.16935068368911743, -0.775557279586792, 0.8669920563697815], [2.742936611175537, 0.27675795555114746, -3.4094791412353516], [1.836807131767273, 0.7949733734130859, -2.5332820415496826], [1.0065339803695679, 8.76756763458252, 1.7694025039672852], [-4.99381685256958, 1.955883264541626, 0.45051300525665283], [3.922380208969116, 0.8041913509368896, -2.3651986122131348], [1.9286773204803467, 9.983572006225586, -2.5073742866516113], [1.6296720504760742, 2.0421457290649414, -0.2820594310760498], [0.010609951801598072, -0.2798006534576416, -3.8158040046691895], [-0.3589290976524353, 6.76906156539917, -3.150224447250366], [-2.180927276611328, 0.12159991264343262, -1.6307398080825806], [2.4454803466796875, 4.04958963394165, 1.904606580734253], [2.3620524406433105, 0.9491770267486572, -0.6401419639587402], [-0.8478649854660034, 1.051281452178955, 3.557401657104492], [-1.9529225826263428, 8.662725448608398, 3.2547597885131836], [-1.1669318675994873, 4.840293884277344, -1.450810194015503], [4.128586769104004, -2.36899995803833, -1.1018785238265991]], "valid": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], "chunk_frames": 5, "lookback_frames": 0, "cache_rows": 6, "fifo_rows": 4, "compressed": false, "cache": [[-1.6902153491973877, 1.7454077005386353, -1.4815342426300049, 0.4056456685066223, 2.380732774734497, 1.2582863569259644], [-1.0405282974243164, -0.3898184597492218, 0.6496017575263977, -1.7215901613235474, 0.5778094530105591, 0.8384053707122803], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [1.253964900970459, 0.7886534929275513, -1.6647926568984985, 1.2520029544830322, 0.448635995388031, 1.0780999660491943], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.40674862265586853, -0.07591209560632706, 0.07073015719652176, -0.62159663438797, 0.2137121707201004, -0.8957604169845581]], "cache_probs": [[0.43851447105407715, 0.914284348487854, 0.8108340501785278], [0.11182622611522675, 0.6101736426353455, 0.7041566371917725], [0.6349950432777405, 0.9159563779830933, 0.652921199798584], [0.28852578997612, 0.6540367603302002, 0.3575136661529541], [0.9010419249534607, 0.6288247108459473, 0.052779097110033035], [0.36953768134117126, 0.9379655122756958, 0.7325722575187683]], "fifo": [[-1.5906429290771484, 1.2326383590698242, -0.5130079388618469, 0.04086293652653694, -0.5561856031417847, -2.3698203563690186], [-1.5125060081481934, 1.336596965789795, 0.8586768507957458, 0.523654043674469, -0.4376985430717468, -0.13509657979011536], [0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [0.05285830423235893, -2.052243232727051, 0.27110710740089417, -1.2543226480484009, -0.18498015403747559, 0.0008936904487200081]]}, {"step_input": [[-1.6902153491973877, 1.7454077005386353, -1.4815342426300049, 0.4056456685066223, 2.380732774734497, 1.2582863569259644], [-1.0405282974243164, -0.3898184597492218, 0.6496017575263977, -1.7215901613235474, 0.5778094530105591, 0.8384053707122803], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [1.253964900970459, 0.7886534929275513, -1.6647926568984985, 1.2520029544830322, 0.448635995388031, 1.0780999660491943], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.40674862265586853, -0.07591209560632706, 0.07073015719652176, -0.62159663438797, 0.2137121707201004, -0.8957604169845581], [-1.5906429290771484, 1.2326383590698242, -0.5130079388618469, 0.04086293652653694, -0.5561856031417847, -2.3698203563690186], [-1.5125060081481934, 1.336596965789795, 0.8586768507957458, 0.523654043674469, -0.4376985430717468, -0.13509657979011536], [0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [0.05285830423235893, -2.052243232727051, 0.27110710740089417, -1.2543226480484009, -0.18498015403747559, 0.0008936904487200081], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [0.6952648162841797, 0.3742130398750305, -0.6744688153266907, -1.5201603174209595, 1.2268528938293457, 0.9549810886383057], [1.0687527656555176, 1.257512092590332, -0.3164335787296295, 2.164961338043213, 0.8648388981819153, 0.22065207362174988], [-1.1159002780914307, 0.5649962425231934, -0.6164774894714355, 0.16569273173809052, -0.4569424092769623, -0.5900519490242004], [1.793763518333435, 1.2944889068603516, -1.4929441213607788, -0.1778257042169571, -0.8731200695037842, 0.43291595578193665], [0.9492765665054321, -0.7180567979812622, 1.23494291305542, -0.28170403838157654, -0.9079329967498779, 0.26732420921325684]], "logits": [[-0.7534216642379761, 3.5208487510681152, 7.7209086418151855], [3.3145713806152344, -1.874617338180542, 4.154484272003174], [-0.15954963862895966, 3.209312915802002, 4.308387279510498], [2.8537397384643555, 3.6038026809692383, 4.125831604003906], [-4.463710308074951, -1.3689228296279907, 0.685883641242981], [-3.4924540519714355, 0.9791895747184753, 2.674970865249634], [-1.4688949584960938, -1.1218117475509644, 2.3426148891448975], [2.5724973678588867, 2.954824924468994, 4.963052749633789], [-3.8583319187164307, -4.975775241851807, 1.279454231262207], [-1.2509369850158691, 0.07499754428863525, 8.650825500488281], [6.426395416259766, -0.10542252659797668, 1.4847135543823242], [0.42564988136291504, -5.1455912590026855, 1.3904190063476562], [1.002366542816162, -4.5505523681640625, 0.9034597873687744], [0.24209672212600708, 0.5782992243766785, 5.403799533843994], [0.09879275411367416, 4.609100341796875, 3.588392972946167], [-1.1448585987091064, -0.43621861934661865, 2.667421340942383], [5.131195068359375, 0.7274320125579834, 3.1503281593322754], [0.3748135566711426, 2.063570499420166, 4.571181297302246], [1.300386905670166, 0.4191652536392212, 2.510648012161255], [-0.9204772710800171, -3.5026493072509766, 2.1051764488220215], [2.5304765701293945, 2.087944746017456, 4.367121696472168], [0.1663452684879303, -3.733224868774414, 3.463184356689453], [5.862518310546875, -4.716890335083008, 0.5575982332229614], [-1.0880273580551147, -1.0938128232955933, 3.29085373878479], [0.9494152665138245, 1.0737202167510986, 2.64176607131958], [-2.64542818069458, -6.471377849578857, -0.34392261505126953], [-3.3988759517669678, -2.2343149185180664, -0.14009642601013184], [-3.318230628967285, 0.426339715719223, 0.631676435470581], [-2.209656238555908, -0.6297301054000854, 5.841035842895508], [-0.23052214086055756, 1.2634422779083252, 0.5188207626342773], [5.191611289978027, 1.3522716760635376, 1.8377796411514282], [-0.6296523809432983, 0.3666650652885437, 4.679913520812988], [0.31741178035736084, -0.6148509979248047, 4.497945308685303], [2.5218138694763184, 0.6112229824066162, -3.999948501586914]], "valid": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], "chunk_frames": 5, "lookback_frames": 0, "cache_rows": 11, "fifo_rows": 4, "compressed": false, "cache": [[-1.6902153491973877, 1.7454077005386353, -1.4815342426300049, 0.4056456685066223, 2.380732774734497, 1.2582863569259644], [-1.0405282974243164, -0.3898184597492218, 0.6496017575263977, -1.7215901613235474, 0.5778094530105591, 0.8384053707122803], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [1.253964900970459, 0.7886534929275513, -1.6647926568984985, 1.2520029544830322, 0.448635995388031, 1.0780999660491943], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.40674862265586853, -0.07591209560632706, 0.07073015719652176, -0.62159663438797, 0.2137121707201004, -0.8957604169845581], [-1.5906429290771484, 1.2326383590698242, -0.5130079388618469, 0.04086293652653694, -0.5561856031417847, -2.3698203563690186], [-1.5125060081481934, 1.336596965789795, 0.8586768507957458, 0.523654043674469, -0.4376985430717468, -0.13509657979011536], [0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [0.05285830423235893, -2.052243232727051, 0.27110710740089417, -1.2543226480484009, -0.18498015403747559, 0.0008936904487200081], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066]], "cache_probs": [[0.6425007581710815, 0.5521417856216431, 0.9920526742935181], [0.702854335308075, 0.9673422574996948, 0.985414981842041], [0.020458027720451355, 0.4648706316947937, 0.8002920746803284], [0.5580905675888062, 0.5980831980705261, 0.952701210975647], [0.12160249799489975, 0.2627982199192047, 0.891090989112854], [0.8016093969345093, 0.23973001539707184, 0.8079712986946106], [0.645876944065094, 0.3255634903907776, 0.8535903692245483], [0.3830537796020508, 0.6913899183273315, 0.9540887475013733], [0.7933734059333801, 0.7807765603065491, 0.9743409156799316], [0.5353803634643555, 0.3162602186203003, 0.9081450700759888], [0.733870804309845, 0.4565414488315582, 0.9785466194152832]], "fifo": [[0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [0.6952648162841797, 0.3742130398750305, -0.6744688153266907, -1.5201603174209595, 1.2268528938293457, 0.9549810886383057], [1.0687527656555176, 1.257512092590332, -0.3164335787296295, 2.164961338043213, 0.8648388981819153, 0.22065207362174988], [-1.1159002780914307, 0.5649962425231934, -0.6164774894714355, 0.16569273173809052, -0.4569424092769623, -0.5900519490242004]]}, {"step_input": [[-1.6902153491973877, 1.7454077005386353, -1.4815342426300049, 0.4056456685066223, 2.380732774734497, 1.2582863569259644], [-1.0405282974243164, -0.3898184597492218, 0.6496017575263977, -1.7215901613235474, 0.5778094530105591, 0.8384053707122803], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [1.253964900970459, 0.7886534929275513, -1.6647926568984985, 1.2520029544830322, 0.448635995388031, 1.0780999660491943], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.40674862265586853, -0.07591209560632706, 0.07073015719652176, -0.62159663438797, 0.2137121707201004, -0.8957604169845581], [-1.5906429290771484, 1.2326383590698242, -0.5130079388618469, 0.04086293652653694, -0.5561856031417847, -2.3698203563690186], [-1.5125060081481934, 1.336596965789795, 0.8586768507957458, 0.523654043674469, -0.4376985430717468, -0.13509657979011536], [0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [0.05285830423235893, -2.052243232727051, 0.27110710740089417, -1.2543226480484009, -0.18498015403747559, 0.0008936904487200081], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [0.6952648162841797, 0.3742130398750305, -0.6744688153266907, -1.5201603174209595, 1.2268528938293457, 0.9549810886383057], [1.0687527656555176, 1.257512092590332, -0.3164335787296295, 2.164961338043213, 0.8648388981819153, 0.22065207362174988], [-1.1159002780914307, 0.5649962425231934, -0.6164774894714355, 0.16569273173809052, -0.4569424092769623, -0.5900519490242004], [0.42424437403678894, 0.06914714723825455, -1.3488868474960327, -0.7861173748970032, 1.4853514432907104, -1.4962661266326904], [1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-0.2435186207294464, -1.122119426727295, 0.10720892250537872, 1.3441134691238403, 0.45590105652809143, 0.2122616022825241], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-1.7136646509170532, 0.046180132776498795, 0.6605033874511719, 0.10925961285829544, -0.46304941177368164, -0.027518324553966522], [-0.9178438186645508, -0.19409053027629852, 0.23364897072315216, 0.12930609285831451, 1.3218845129013062, -1.0915040969848633], [-0.1305038034915924, 0.6167216300964355, -0.14053493738174438, 0.21913616359233856, -1.307775855064392, 0.09747019410133362]], "logits": [[2.503241539001465, -1.7236583232879639, 4.743233680725098], [4.551877021789551, 2.2005209922790527, -0.6551765203475952], [1.405540108680725, -2.12567400932312, 6.281678199768066], [4.687885284423828, 4.823338508605957, -2.078395128250122], [3.252899646759033, 0.454933226108551, -5.261227607727051], [6.384177207946777, 3.14829158782959, 0.2940674424171448], [6.28945255279541, -2.233464241027832, -5.105018615722656], [5.493113994598389, -2.4142000675201416, 3.967470169067383], [0.6614594459533691, 5.0114874839782715, -2.476158380508423], [-1.6283464431762695, -2.0540859699249268, 2.7304744720458984], [0.6581761837005615, 2.6754446029663086, -0.15668922662734985], [6.616547107696533, -2.7305188179016113, 0.18740937113761902], [0.6055446863174438, -1.3432562351226807, -0.6411342024803162], [4.212994575500488, 0.6440837979316711, -3.1358792781829834], [4.1901445388793945, -3.267246723175049, -1.3981716632843018], [2.0251615047454834, -1.8378506898880005, 0.7976312637329102], [5.49704647064209, -2.864301919937134, 0.4655529260635376], [0.26782941818237305, -5.25242805480957, -5.030498504638672], [2.2694251537323, 0.6542725563049316, 3.728637456893921], [5.300790786743164, -1.0547441244125366, -1.6962487697601318], [1.5029420852661133, -1.0564250946044922, -3.616149425506592], [7.885618209838867, -4.657582759857178, 0.19590885937213898], [1.5266128778457642, -0.4288359582424164, -1.2435448169708252], [1.0613512992858887, -3.3729801177978516, -5.782381534576416], [1.3482791185379028, 2.876063346862793, -3.960692882537842], [1.5950299501419067, -0.23044642806053162, -4.186795234680176], [5.347599029541016, -2.649867534637451, -3.356020927429199], [-0.5527887344360352, 2.5478734970092773, 1.548437476158142], [-1.4953336715698242, 2.4519104957580566, -2.476649284362793], [5.601138591766357, -0.12909092009067535, 3.6377153396606445], [5.228738307952881, 0.6712325811386108, 3.5292413234710693], [3.5605688095092773, 0.5783892869949341, 1.5234882831573486], [2.7582595348358154, 4.056671142578125, -2.4914891719818115], [-3.1604199409484863, -2.0369017124176025, -3.5129334926605225], [2.0351083278656006, 0.9337090253829956, -4.1988396644592285], [7.963776588439941, -4.006573677062988, -1.7533632516860962], [3.309432029724121, 3.987633228302002, 3.043501853942871], [4.973423480987549, -1.7732187509536743, -1.596555233001709], [3.0967209339141846, -3.1159310340881348, -3.028690814971924], [2.3251969814300537, -0.6268085837364197, 2.0116186141967773], [-1.2492196559906006, 0.2781885266304016, -4.86328125], [4.83669376373291, 2.350429058074951, -3.395780324935913], [6.554507255554199, -0.9775488376617432, -1.4089293479919434], [1.5527552366256714, 0.10067912936210632, -2.2589805126190186]], "valid": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], "chunk_frames": 5, "lookback_frames": 0, "cache_rows": 12, "fifo_rows": 4, "compressed": true, "cache": [[0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.6952648162841797, 0.3742130398750305, -0.6744688153266907, -1.5201603174209595, 1.2268528938293457, 0.9549810886383057], [-1.1159002780914307, 0.5649962425231934, -0.6164774894714355, 0.16569273173809052, -0.4569424092769623, -0.5900519490242004], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.42424437403678894, 0.06914714723825455, -1.3488868474960327, -0.7861173748970032, 1.4853514432907104, -1.4962661266326904], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799]], "cache_probs": [[0.7812389135360718, 0.02957712858915329, 0.31041187047958374], [0.9088184237480164, 0.13369669020175934, 0.28750160336494446], [0.7822294235229492, 0.21377751231193542, 0.11344572901725769], [0.0, 0.0, 0.0], [0.9805459976196289, 0.7853264808654785, 0.28907686471939087], [0.4118225872516632, 0.5535116195678711, 0.5081738233566284], [0.8125853538513184, 0.6946461796760559, 0.01683063432574272], [0.5897212028503418, 0.6942365169525146, 0.5259368419647217], [0.0, 0.0, 0.0], [0.4118225872516632, 0.5535116195678711, 0.5081738233566284], [0.9835156202316284, 0.6512379050254822, 0.8962799906730652], [0.0, 0.0, 0.0]], "fifo": [[1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-0.2435186207294464, -1.122119426727295, 0.10720892250537872, 1.3441134691238403, 0.45590105652809143, 0.2122616022825241], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-1.7136646509170532, 0.046180132776498795, 0.6605033874511719, 0.10925961285829544, -0.46304941177368164, -0.027518324553966522]]}, {"step_input": [[0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [-0.6356996297836304, 0.3010067343711853, 1.126539945602417, 0.07906576991081238, -1.9458744525909424, 2.296760320663452], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.6952648162841797, 0.3742130398750305, -0.6744688153266907, -1.5201603174209595, 1.2268528938293457, 0.9549810886383057], [-1.1159002780914307, 0.5649962425231934, -0.6164774894714355, 0.16569273173809052, -0.4569424092769623, -0.5900519490242004], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.42424437403678894, 0.06914714723825455, -1.3488868474960327, -0.7861173748970032, 1.4853514432907104, -1.4962661266326904], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-0.2435186207294464, -1.122119426727295, 0.10720892250537872, 1.3441134691238403, 0.45590105652809143, 0.2122616022825241], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-1.7136646509170532, 0.046180132776498795, 0.6605033874511719, 0.10925961285829544, -0.46304941177368164, -0.027518324553966522], [-1.2451261281967163, -1.1563832759857178, -1.5994023084640503, 0.9830917119979858, 0.7380546927452087, -1.3016506433486938], [-0.4897269904613495, 1.8988444805145264, -0.9842662811279297, -0.5755122900009155, -0.3748170733451843, 0.6378623247146606], [-0.840380847454071, -0.09056520462036133, 1.3736121654510498, 0.41764917969703674, 0.5997155904769897, 1.9647345542907715], [0.2743159532546997, 1.7766473293304443, 0.5598903894424438, 0.6046450734138489, -1.3222686052322388, -0.4441923201084137], [-0.5993315577507019, -0.7904966473579407, 0.8936244249343872, -0.2177838534116745, -1.3166440725326538, 0.7842789888381958], [0.7018584609031677, 0.8043138980865479, 0.0914752334356308, -0.4805726706981659, -1.5009185075759888, -0.5037550926208496], [1.0383493900299072, 1.0707063674926758, -0.5258471965789795, -1.2205287218093872, -1.77851402759552, 2.0632190704345703], [-0.8853461146354675, -0.34146931767463684, -0.22966556251049042, -0.5506711602210999, 1.1783535480499268, 1.7222931385040283], [0.7040802836418152, 1.1108148097991943, 0.9722220301628113, -0.5468391180038452, -0.9182370901107788, 0.9882752895355225]], "logits": [[-4.787031650543213, 3.3534486293792725, -0.6943947672843933], [1.3497254848480225, 1.3994067907333374, 3.6858608722686768], [-3.420480251312256, 3.9424312114715576, -6.503752708435059], [-4.433969020843506, 5.772899150848389, 6.479060173034668], [-0.6605767011642456, -1.2987961769104004, -1.365485429763794], [1.7202539443969727, 2.389423131942749, 7.610750198364258], [-2.917419672012329, 6.264142036437988, 0.9627153873443604], [-3.493429660797119, 4.653619289398193, -3.4370675086975098], [1.0085642337799072, -3.388016700744629, 0.8279916048049927], [7.599745750427246, 3.1099419593811035, 0.7032343149185181], [-4.193524360656738, 0.7644572257995605, 1.5411384105682373], [-2.472372055053711, 4.074675559997559, -3.6218948364257812], [0.34641608595848083, 4.5077948570251465, -1.7687389850616455], [-4.750247001647949, 0.12065529823303223, -4.483001708984375], [-3.8231053352355957, 1.6957131624221802, -1.2785584926605225], [2.943575382232666, 1.571988821029663, 0.969272255897522], [2.479696035385132, 2.679151773452759, 0.5139451622962952], [-3.4084339141845703, 4.306418418884277, -0.48551782965660095], [0.5239125490188599, 7.6422576904296875, -2.770801544189453], [3.6146817207336426, 3.7905774116516113, -0.3372223377227783], [6.218173027038574, 2.8597569465637207, 2.009993553161621], [1.524434208869934, 0.5969090461730957, -3.8238797187805176], [0.6144019365310669, -2.274883270263672, 2.763460874557495], [-6.5612993240356445, -0.9374313354492188, -0.1379416286945343], [-2.357755422592163, 3.298849582672119, -2.2691540718078613], [0.13110117614269257, 1.929901123046875, -2.444277286529541], [1.990114450454712, 9.085611343383789, 2.5529651641845703], [6.537545204162598, 0.2579944133758545, 1.8666975498199463], [-2.038367748260498, 0.01885843276977539, 3.7430810928344727], [0.1745298057794571, 4.013845443725586, 4.059203147888184], [3.171194553375244, 6.3382649421691895, -1.9263925552368164], [3.96567440032959, 0.5513620376586914, 0.2603304088115692], [-0.7478705644607544, 3.8860526084899902, -3.690133571624756], [-2.7274622917175293, 1.4396737813949585, 3.061180591583252], [0.4962514638900757, 2.629911184310913, 1.4435815811157227], [-2.7000856399536133, 2.7938501834869385, 4.284135341644287], [-0.5609252452850342, 0.5514012575149536, 0.10574191808700562], [8.59115982055664, 3.0117645263671875, 2.4417643547058105], [5.655513286590576, 2.033966064453125, 0.9830617904663086], [0.3272237181663513, -1.2595868110656738, 1.5904366970062256], [-4.34719181060791, 0.12213945388793945, 4.9700422286987305], [2.7443137168884277, 9.23498821258545, 2.3609321117401123], [-1.3918964862823486, -3.3823671340942383, -2.0922679901123047], [-2.704470634460449, 1.636886477470398, -3.4485836029052734], [4.32444953918457, 7.111091136932373, 0.7632972002029419], [1.338625192642212, -0.853729248046875, -2.1650495529174805], [3.4712114334106445, 0.44049620628356934, -3.7489521503448486], [1.2429630756378174, -0.3246757984161377, 3.045936107635498], [0.040896836668252945, 2.600682020187378, 0.12058253586292267], [1.561011791229248, 3.0126521587371826, 6.25045108795166]], "valid": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], "chunk_frames": 5, "lookback_frames": 2, "cache_rows": 12, "fifo_rows": 4, "compressed": true, "cache": [[0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [-1.1159002780914307, 0.5649962425231934, -0.6164774894714355, 0.16569273173809052, -0.4569424092769623, -0.5900519490242004], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.42424437403678894, 0.06914714723825455, -1.3488868474960327, -0.7861173748970032, 1.4853514432907104, -1.4962661266326904], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799]], "cache_probs": [[0.7812389135360718, 0.02957712858915329, 0.31041187047958374], [0.9088184237480164, 0.13369669020175934, 0.28750160336494446], [0.7822294235229492, 0.21377751231193542, 0.11344572901725769], [0.0, 0.0, 0.0], [0.30958986282348633, 0.9188138246536255, 0.08678404241800308], [0.0, 0.0, 0.0], [0.4118225872516632, 0.5535116195678711, 0.5081738233566284], [0.5897212028503418, 0.6942365169525146, 0.5259368419647217], [0.4118225872516632, 0.5535116195678711, 0.5081738233566284], [0.9835156202316284, 0.6512379050254822, 0.8962799906730652], [0.32937753200531006, 0.7434855699539185, 0.9799484610557556], [0.0, 0.0, 0.0]], "fifo": [[0.2743159532546997, 1.7766473293304443, 0.5598903894424438, 0.6046450734138489, -1.3222686052322388, -0.4441923201084137], [-0.5993315577507019, -0.7904966473579407, 0.8936244249343872, -0.2177838534116745, -1.3166440725326538, 0.7842789888381958], [0.7018584609031677, 0.8043138980865479, 0.0914752334356308, -0.4805726706981659, -1.5009185075759888, -0.5037550926208496], [1.0383493900299072, 1.0707063674926758, -0.5258471965789795, -1.2205287218093872, -1.77851402759552, 2.0632190704345703]]}, {"step_input": [[0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [-1.1159002780914307, 0.5649962425231934, -0.6164774894714355, 0.16569273173809052, -0.4569424092769623, -0.5900519490242004], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [0.42424437403678894, 0.06914714723825455, -1.3488868474960327, -0.7861173748970032, 1.4853514432907104, -1.4962661266326904], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [0.2743159532546997, 1.7766473293304443, 0.5598903894424438, 0.6046450734138489, -1.3222686052322388, -0.4441923201084137], [-0.5993315577507019, -0.7904966473579407, 0.8936244249343872, -0.2177838534116745, -1.3166440725326538, 0.7842789888381958], [0.7018584609031677, 0.8043138980865479, 0.0914752334356308, -0.4805726706981659, -1.5009185075759888, -0.5037550926208496], [1.0383493900299072, 1.0707063674926758, -0.5258471965789795, -1.2205287218093872, -1.77851402759552, 2.0632190704345703], [0.44695502519607544, 1.015185832977295, 0.6037925481796265, -0.11315421015024185, 0.9681838154792786, -0.49095630645751953], [1.061123013496399, -1.2450910806655884, -1.0589408874511719, -0.6534969210624695, -0.9024079442024231, 0.06367028504610062], [2.556917428970337, 0.6856318116188049, 0.46879762411117554, 1.4793628454208374, -3.258319139480591, -0.7654128074645996], [-0.5074830651283264, 1.4497058391571045, -1.5088374614715576, -1.228659749031067, -0.7858580350875854, 0.9914764761924744], [-0.2724103629589081, -0.3734554052352905, 1.4249223470687866, 0.4242926836013794, 0.9260433912277222, 0.4665665626525879], [0.8463976979255676, 0.08119219541549683, 0.7238510847091675, 0.9735305309295654, -0.4601098895072937, 0.8738967776298523], [1.9952893257141113, 1.569277048110962, -0.05878959223628044, 0.34840404987335205, -2.890872001647949, -0.14565879106521606]], "logits": [[-5.000382900238037, 0.8548416495323181, -1.3622031211853027], [3.6699938774108887, 4.086727142333984, 0.9291083812713623], [-2.7536635398864746, -0.38356995582580566, 1.8623754978179932], [1.559436559677124, -5.442570686340332, 7.758718490600586], [0.8565113544464111, -0.6741048693656921, 3.5298011302948], [-1.1858587265014648, 2.94587779045105, 4.641037940979004], [5.513378620147705, -2.003289222717285, 6.460779190063477], [-5.3528218269348145, 3.0085248947143555, 1.5494110584259033], [-1.678382158279419, -2.617216110229492, 4.659170627593994], [1.4249179363250732, 1.6804044246673584, 4.167962074279785], [-0.9339020848274231, 2.8932430744171143, -1.3641934394836426], [2.551342487335205, 1.8134136199951172, -3.2252731323242188], [-4.055978775024414, -1.5071735382080078, 2.7140326499938965], [1.5714330673217773, -2.7801058292388916, 0.9185359477996826], [-2.2320339679718018, 0.48759645223617554, 1.7344781160354614], [0.6074382066726685, 2.690277099609375, 7.993544578552246], [1.7579097747802734, 0.49452775716781616, 2.258758306503296], [-5.438628196716309, 1.5395255088806152, 4.306466102600098], [-2.3479723930358887, 1.985898494720459, 3.2967474460601807], [-1.8145091533660889, -0.013900954276323318, 1.486249566078186], [0.4993065297603607, 3.345850944519043, -0.9648551940917969], [2.8645238876342773, 2.469774007797241, 2.8130369186401367], [2.8575520515441895, 0.8796789050102234, 6.69610071182251], [-0.031740952283144, -4.302735805511475, 3.333454132080078], [0.5204753875732422, 4.0486297607421875, 6.816430568695068], [2.5139827728271484, -0.38016265630722046, -0.6388950347900391], [-4.1864423751831055, -1.49822199344635, 10.559343338012695], [0.7656621336936951, -2.472991943359375, 1.0896623134613037], [1.4163191318511963, 1.0780829191207886, 4.62526798248291], [-1.879234790802002, -2.6577279567718506, 1.662057638168335], [-1.0035473108291626, 2.092805862426758, 0.028812646865844727], [-2.3876938819885254, 0.7046600580215454, 1.1239389181137085], [3.6611108779907227, -3.530424118041992, 1.2320061922073364], [5.852504253387451, -3.938724994659424, -1.1269595623016357], [-0.11510695517063141, -0.4381541609764099, 6.26320743560791], [3.4892773628234863, 1.3646658658981323, 4.968005180358887], [-1.7735097408294678, -2.306077480316162, 2.398969888687134], [-3.6152944564819336, 2.1512012481689453, 0.32842016220092773], [0.3184199929237366, -1.8316526412963867, 7.766601085662842], [2.69527006149292, -1.5918864011764526, -2.0169801712036133], [0.959099292755127, 2.177903413772583, 0.6065657138824463], [2.046065330505371, 1.3694803714752197, 3.29177188873291], [1.8277041912078857, -0.45013099908828735, 0.37488579750061035], [-0.5604332089424133, -0.35014620423316956, 6.058136940002441], [-0.5433617830276489, -3.0106630325317383, 0.18776917457580566], [-2.1947035789489746, -0.4435049295425415, -1.027167797088623]], "valid": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], "chunk_frames": 5, "lookback_frames": 0, "cache_rows": 12, "fifo_rows": 4, "compressed": true, "cache": [[0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-0.5993315577507019, -0.7904966473579407, 0.8936244249343872, -0.2177838534116745, -1.3166440725326538, 0.7842789888381958], [0.7018584609031677, 0.8043138980865479, 0.0914752334356308, -0.4805726706981659, -1.5009185075759888, -0.5037550926208496], [1.0383493900299072, 1.0707063674926758, -0.5258471965789795, -1.2205287218093872, -1.77851402759552, 2.0632190704345703], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799]], "cache_probs": [[0.7812389135360718, 0.02957712858915329, 0.31041187047958374], [0.9088184237480164, 0.13369669020175934, 0.28750160336494446], [0.7822294235229492, 0.21377751231193542, 0.11344572901725769], [0.0, 0.0, 0.0], [0.30958986282348633, 0.9188138246536255, 0.08678404241800308], [0.0, 0.0, 0.0], [0.4118225872516632, 0.5535116195678711, 0.5081738233566284], [0.32937753200531006, 0.7434855699539185, 0.9799484610557556], [0.34877723455429077, 0.13023211061954498, 0.8741461038589478], [0.468618780374527, 0.4058226943016052, 0.9154040813446045], [0.17618024349212646, 0.7797110080718994, 0.6309606432914734], [0.0, 0.0, 0.0]], "fifo": [[1.061123013496399, -1.2450910806655884, -1.0589408874511719, -0.6534969210624695, -0.9024079442024231, 0.06367028504610062], [2.556917428970337, 0.6856318116188049, 0.46879762411117554, 1.4793628454208374, -3.258319139480591, -0.7654128074645996], [-0.5074830651283264, 1.4497058391571045, -1.5088374614715576, -1.228659749031067, -0.7858580350875854, 0.9914764761924744], [-0.2724103629589081, -0.3734554052352905, 1.4249223470687866, 0.4242926836013794, 0.9260433912277222, 0.4665665626525879]]}, {"step_input": [[0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [0.9024322032928467, -0.7969126105308533, -0.5576652884483337, 0.16577960550785065, 0.9792015552520752, 0.3818894624710083], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-0.5993315577507019, -0.7904966473579407, 0.8936244249343872, -0.2177838534116745, -1.3166440725326538, 0.7842789888381958], [0.7018584609031677, 0.8043138980865479, 0.0914752334356308, -0.4805726706981659, -1.5009185075759888, -0.5037550926208496], [1.0383493900299072, 1.0707063674926758, -0.5258471965789795, -1.2205287218093872, -1.77851402759552, 2.0632190704345703], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [1.061123013496399, -1.2450910806655884, -1.0589408874511719, -0.6534969210624695, -0.9024079442024231, 0.06367028504610062], [2.556917428970337, 0.6856318116188049, 0.46879762411117554, 1.4793628454208374, -3.258319139480591, -0.7654128074645996], [-0.5074830651283264, 1.4497058391571045, -1.5088374614715576, -1.228659749031067, -0.7858580350875854, 0.9914764761924744], [-0.2724103629589081, -0.3734554052352905, 1.4249223470687866, 0.4242926836013794, 0.9260433912277222, 0.4665665626525879], [0.6929898858070374, 0.08448377996683121, 0.4424872398376465, -0.32604068517684937, -0.19188553094863892, 0.9930005669593811], [1.1654731035232544, -1.214758276939392, 0.5635733008384705, 0.22173051536083221, 1.3892722129821777, 0.9315764307975769], [0.5697554349899292, -0.6565861105918884, -0.42663446068763733, 1.173394799232483, 0.6290553212165833, -0.19401024281978607], [-1.8778800964355469, 0.5248855352401733, -1.0588781833648682, -2.975342035293579, -1.4850341081619263, 0.8276671767234802], [-0.8680244088172913, -0.006709573790431023, -0.447217732667923, 0.4494435489177704, 0.2511596083641052, -0.5018554329872131], [0.2115136682987213, 0.3186006247997284, -0.2325514703989029, -0.6238334774971008, -0.5930987596511841, -0.959082305431366], [1.0196298360824585, 0.9591760635375977, -0.6367778778076172, 0.8205168843269348, 0.1230950653553009, -0.9059924483299255]], "logits": [[3.600308895111084, -1.748015284538269, -0.8551101684570312], [8.456670761108398, 1.3187696933746338, 1.3906710147857666], [1.0878580808639526, 1.4214303493499756, 2.1851816177368164], [4.795213222503662, -1.7006254196166992, -0.5682893395423889], [0.8599581718444824, 2.68461275100708, 0.67127525806427], [-0.19907760620117188, 6.984652519226074, -7.598925590515137], [4.90913724899292, -4.675086975097656, 0.38016289472579956], [1.5465388298034668, -6.843184471130371, 1.2576876878738403], [2.5268146991729736, -0.6119933128356934, -1.029311180114746], [3.053049087524414, 0.37643203139305115, 2.111891508102417], [0.8694939613342285, -1.2401186227798462, -4.467080593109131], [5.6756510734558105, -4.268278121948242, -0.3009662628173828], [1.360121726989746, 0.040539778769016266, 4.596200942993164], [-1.026655673980713, 3.27518892288208, 1.980753779411316], [-3.2896370887756348, 3.8019471168518066, -3.7457332611083984], [1.8721933364868164, -1.506913423538208, -3.760160446166992], [2.4694559574127197, 0.32561397552490234, 0.8309942483901978], [9.053400039672852, 4.147973537445068, -4.245768070220947], [4.256559371948242, 1.6217176914215088, 1.615293264389038], [0.574714183807373, 0.07064774632453918, 3.8179984092712402], [1.3653793334960938, 2.2514572143554688, -0.6223729848861694], [1.0123200416564941, -0.9729315042495728, -6.57993221282959], [4.833309173583984, -2.1057815551757812, -0.6687596440315247], [0.7690342664718628, 3.4139275550842285, 0.9103875160217285], [5.7060112953186035, 2.3242101669311523, -1.1493687629699707], [0.9355058670043945, 4.51788854598999, -5.981680393218994], [-0.23199987411499023, 7.583091735839844, 1.5514671802520752], [3.649960517883301, 3.0563700199127197, 0.21060296893119812], [-3.940884590148926, -0.7302297353744507, -4.123499870300293], [-1.6775422096252441, 5.995151519775391, -2.642718553543091], [-1.0863487720489502, -2.246281623840332, 0.8925864696502686], [1.149524211883545, 1.2186936140060425, 3.5369045734405518], [-0.3032643795013428, 0.5445455312728882, -0.3421691954135895], [2.0900139808654785, -2.3227763175964355, -5.39419412612915], [3.8838138580322266, -3.056264877319336, -3.1750478744506836], [-1.731471061706543, -6.0953779220581055, 2.8544087409973145], [0.7562367916107178, 2.1430001258850098, 0.17872804403305054], [-0.0017120838165283203, 1.1619505882263184, 2.4570090770721436], [-3.7074708938598633, 1.6969549655914307, -2.366912364959717], [2.6772665977478027, 1.5273138284683228, -2.904724597930908], [0.9182100296020508, 3.102688789367676, -0.7060596942901611], [-0.3545539379119873, -0.7794097065925598, -0.06610759347677231], [3.875372886657715, 2.7913851737976074, 1.7634706497192383], [2.6786141395568848, -2.749636650085449, -0.2824207544326782], [7.806468963623047, 4.344639301300049, -1.345752239227295], [3.153459072113037, -5.764528751373291, 3.408998966217041]], "valid": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], "chunk_frames": 5, "lookback_frames": 0, "cache_rows": 12, "fifo_rows": 4, "compressed": true, "cache": [[0.0696493610739708, 0.9005182981491089, 1.2016130685806274, 1.211750864982605, -1.0529237985610962, 1.1147193908691406], [-1.6106637716293335, 1.273051142692566, -0.014803544618189335, 0.855499267578125, 1.4498313665390015, -0.2431132197380066], [0.40114885568618774, -1.8922643661499023, -0.5302258133888245, -1.9539605379104614, -0.8860653638839722, 0.8056542277336121], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [1.1313265562057495, 0.2975533604621887, 0.41504451632499695, 0.8354741334915161, -0.40668460726737976, 1.2365680932998657], [-0.5074830651283264, 1.4497058391571045, -1.5088374614715576, -1.228659749031067, -0.7858580350875854, 0.9914764761924744], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799], [-1.2780824899673462, -0.8342481851577759, -0.08963795006275177, 1.000892996788025, 1.3773802518844604, -0.15861335396766663], [-0.5993315577507019, -0.7904966473579407, 0.8936244249343872, -0.2177838534116745, -1.3166440725326538, 0.7842789888381958], [0.7018584609031677, 0.8043138980865479, 0.0914752334356308, -0.4805726706981659, -1.5009185075759888, -0.5037550926208496], [-0.2724103629589081, -0.3734554052352905, 1.4249223470687866, 0.4242926836013794, 0.9260433912277222, 0.4665665626525879], [-1.5074418783187866, 0.8150096535682678, -1.8353625535964966, -1.2661962509155273, 0.5179117918014526, 0.2733738422393799]], "cache_probs": [[0.7812389135360718, 0.02957712858915329, 0.31041187047958374], [0.9088184237480164, 0.13369669020175934, 0.28750160336494446], [0.7822294235229492, 0.21377751231193542, 0.11344572901725769], [0.0, 0.0, 0.0], [0.30958986282348633, 0.9188138246536255, 0.08678404241800308], [0.08824092894792557, 0.6613298654556274, 0.04118455573916435], [0.0, 0.0, 0.0], [0.32937753200531006, 0.7434855699539185, 0.9799484610557556], [0.34877723455429077, 0.13023211061954498, 0.8741461038589478], [0.468618780374527, 0.4058226943016052, 0.9154040813446045], [0.505865216255188, 0.4337521195411682, 0.8405716419219971], [0.0, 0.0, 0.0]], "fifo": [[1.1654731035232544, -1.214758276939392, 0.5635733008384705, 0.22173051536083221, 1.3892722129821777, 0.9315764307975769], [0.5697554349899292, -0.6565861105918884, -0.42663446068763733, 1.173394799232483, 0.6290553212165833, -0.19401024281978607], [-1.8778800964355469, 0.5248855352401733, -1.0588781833648682, -2.975342035293579, -1.4850341081619263, 0.8276671767234802], [-0.8680244088172913, -0.006709573790431023, -0.447217732667923, 0.4494435489177704, 0.2511596083641052, -0.5018554329872131]]}]}, "intervals": {"logits": [[1.1470868587493896, -0.9743822813034058, 0.5929034948348999, 0.9481996893882751], [1.509750485420227, -0.08609167486429214, 0.5233832001686096, 0.5706121325492859], [1.3498390913009644, 0.5879894495010376, 1.360661268234253, 0.23455174267292023], [0.6782858371734619, 1.2141737937927246, 0.9578199982643127, 0.5692542791366577], [0.9459209442138672, 0.665550172328949, 1.1259559392929077, 0.5518970489501953], [1.4383896589279175, -0.39780959486961365, 0.24595293402671814, 1.207498550415039], [2.1742026805877686, -0.1009593978524208, 0.178264319896698, 0.6309084296226501], [2.723989725112915, 0.1481093019247055, 0.04664125293493271, 0.3858431577682495], [2.068213701248169, 1.1562926769256592, 1.366072177886963, 0.5636276006698608], [2.117889165878296, 0.9599775671958923, 1.3185830116271973, 1.9902116060256958], [3.0991408824920654, 0.28450462222099304, 1.5602105855941772, 2.795293092727661], [3.621391534805298, 0.5842851996421814, 1.5478626489639282, 2.047516345977783], [2.713538885116577, 2.1190192699432373, 0.929915189743042, 2.487607002258301], [1.57918119430542, 2.4073410034179688, -0.10046885907649994, 1.7125980854034424], [0.6350300312042236, 2.7958457469940186, -0.585702121257782, 2.536611795425415], [1.8754010200500488, 2.9995031356811523, -0.34655770659446716, 2.6316754817962646], [3.5161054134368896, 2.138460159301758, -0.04924503341317177, 2.555163621902466], [4.253912925720215, 3.04360294342041, 0.6992104053497314, 2.36051082611084], [2.9745986461639404, 3.6261520385742188, 1.238724946975708, 3.4596002101898193], [2.9006056785583496, 3.5437183380126953, 1.036805510520935, 4.366393089294434], [1.651552677154541, 4.4668989181518555, 0.851259708404541, 5.502831935882568], [1.6039541959762573, 4.624392032623291, 2.196784496307373, 5.559344291687012], [0.7478833198547363, 5.418528079986572, 2.1531858444213867, 6.76416540145874], [1.6035197973251343, 4.608634948730469, 1.683984637260437, 7.817223072052002], [0.9241948127746582, 4.772351264953613, 1.9301457405090332, 8.203167915344238], [-0.14968745410442352, 5.378261089324951, 1.0959899425506592, 7.968174457550049], [-1.2067128419876099, 5.0194172859191895, 0.5395836234092712, 7.722256660461426], [-2.1502163410186768, 5.258495330810547, -0.1014295443892479, 7.826318740844727], [-1.4560636281967163, 5.9024739265441895, 1.301782488822937, 9.2769775390625], [-1.6850402355194092, 5.210235118865967, 1.3833850622177124, 9.732364654541016], [-2.0532937049865723, 5.302010536193848, 0.5043702721595764, 9.44528865814209], [-0.7704678773880005, 4.628326416015625, 0.6489788889884949, 9.727225303649902], [-0.15733978152275085, 3.8854963779449463, 1.7984662055969238, 9.724725723266602], [0.09004193544387817, 3.6355104446411133, 2.082017183303833, 10.031248092651367], [-0.0414881706237793, 3.8032798767089844, 0.8749096989631653, 10.02773666381836], [-0.4320075809955597, 3.48264479637146, 0.4082876741886139, 9.90185832977295], [-0.37691834568977356, 2.9271771907806396, 2.0662841796875, 10.095755577087402], [-0.858564019203186, 2.8628287315368652, 1.8221267461776733, 9.485546112060547], [-0.34348899126052856, 1.9387421607971191, 1.52129065990448, 9.850532531738281], [-0.7843999266624451, 1.568189024925232, 2.0621864795684814, 9.864487648010254], [-0.5157825350761414, 0.6240209341049194, 4.474272727966309, 9.49423599243164], [-0.8281633853912354, 0.4456140100955963, 3.712113857269287, 10.635717391967773], [-1.3299715518951416, 1.9456793069839478, 2.7391114234924316, 11.028097152709961], [-1.1645538806915283, 2.1189444065093994, 3.174691677093506, 11.697427749633789], [-1.4938490390777588, 2.492541790008545, 3.0343754291534424, 12.605993270874023], [-1.582737922668457, 3.184903383255005, 4.153197765350342, 13.160225868225098], [0.08578267693519592, 2.5037174224853516, 2.885540723800659, 13.621075630187988], [0.6412014961242676, 3.2616851329803467, 2.6223599910736084, 14.047070503234863], [0.38481077551841736, 3.7974026203155518, 4.095241069793701, 14.60000991821289], [1.003463864326477, 3.4754559993743896, 4.0083699226379395, 14.96820068359375], [1.2270348072052002, 3.3554224967956543, 3.396589756011963, 14.711254119873047], [1.3038254976272583, 4.082902908325195, 3.690544366836548, 14.490509986877441], [1.6825635433197021, 5.054654598236084, 3.4267308712005615, 14.054551124572754], [1.0138392448425293, 5.100736141204834, 2.73201584815979, 13.176189422607422], [1.9550719261169434, 5.806630611419678, 2.968243360519409, 14.281139373779297], [1.8973544836044312, 5.819139003753662, 3.1199705600738525, 14.713614463806152], [3.6053712368011475, 4.693901538848877, 4.576476097106934, 14.941925048828125], [3.62672758102417, 4.282202243804932, 4.37857723236084, 14.917071342468262], [3.7234749794006348, 4.182017803192139, 4.446337699890137, 14.40312671661377], [3.522998809814453, 4.563117504119873, 3.4571728706359863, 15.241546630859375]], "cases": [{"threshold": 0.5, "segments": [[0.0, 0.25, 0], [0.0, 0.13, 2], [0.0, 0.6, 3], [0.02, 0.05, 1], [0.07, 0.6, 1], [0.17, 0.27, 2], [0.28, 0.6, 2], [0.33, 0.34, 0], [0.46, 0.6, 0]]}, {"threshold": 0.3, "segments": [[0.0, 0.26, 0], [0.0, 0.6, 2], [0.0, 0.6, 3], [0.01, 0.6, 1], [0.31, 0.37, 0], [0.38, 0.42, 0], [0.46, 0.6, 0]]}]}} diff --git a/families/nemotron3_diarization/tests/data/window.f32 b/families/nemotron3_diarization/tests/data/window.f32 new file mode 100644 index 0000000000..268b1c70ba Binary files /dev/null and b/families/nemotron3_diarization/tests/data/window.f32 differ diff --git a/families/nemotron3_diarization/tests/generate_runtime_golden.py b/families/nemotron3_diarization/tests/generate_runtime_golden.py new file mode 100644 index 0000000000..6cf3a1363f --- /dev/null +++ b/families/nemotron3_diarization/tests/generate_runtime_golden.py @@ -0,0 +1,176 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Regenerate the golden data of ``tests/cpp/test_runtime.cpp`` from the reference. + + PYTHONPATH=core/builder:. python3 -m families.nemotron3_diarization.tests.generate_runtime_golden + +Needs torch, librosa and transformers (the release in ``requirements.txt``). +Writes ``tests/data/runtime_golden.json`` with three reference cases and the +front-end constants the family's Python side ships in a bundle: + +- ``front_end``: a deterministic signal and the reference feature extractor's + log-mel features and valid frame count; +- ``speaker_cache``: a small speaker-cache policy driven through the reference + ``Nemotron3DiarizationSpeakerCache`` with random logits, and its state after + every step, compressions included; +- ``intervals``: random logits and the reference processor's speaker segments, + at two thresholds; + +and ``tests/data/mel_filters.f32`` / ``tests/data/window.f32`` from +``frontend.py``, which ``tests/test_model.py`` holds equal to the files. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import torch +from transformers.models.nemotron3_diarization.configuration_nemotron3_diarization import ( + Nemotron3DiarizationStreamingConfig, +) +from transformers.models.nemotron3_diarization.modeling_nemotron3_diarization import ( + Nemotron3DiarizationSpeakerCache, +) +from transformers.models.nemotron3_diarization.processing_nemotron3_diarization import ( + Nemotron3DiarizationProcessor, +) +from transformers.models.nemotron_asr_streaming.feature_extraction_nemotron_asr_streaming import ( + NemotronAsrStreamingFeatureExtractor, +) + +from families.nemotron3_diarization import frontend + +DATA = Path(__file__).resolve().parent / "data" +SAMPLE_RATE, N_FFT, WIN_LENGTH, HOP, MELS = 16000, 512, 400, 160, 128 + + +def _extractor() -> NemotronAsrStreamingFeatureExtractor: + return NemotronAsrStreamingFeatureExtractor( + feature_size=MELS, sampling_rate=SAMPLE_RATE, hop_length=HOP, n_fft=N_FFT, + win_length=WIN_LENGTH, preemphasis=0.97) + + +def _float64_features(samples: np.ndarray, valid_frames: int) -> np.ndarray: + """The reference's front end with a float64 transform. + + Pre-emphasis and the windowing products are rounded to float32 where the + reference rounds them; the transform, the power, the mel sums and the log + are exact to float64. The reference itself transforms in float32, which + puts its own features up to 2.4e-4 away from these at the mel bins whose + energy sits near the 2**-24 floor. + """ + previous = (np.float32(0.97) * samples[:-1]).astype(np.float32) + emphasised = np.concatenate([samples[:1], (samples[1:] - previous).astype(np.float32)]) + padded = np.concatenate([np.zeros(N_FFT // 2, np.float32), emphasised, + np.zeros(N_FFT // 2, np.float32)]) + window = np.zeros(N_FFT, np.float32) + offset = (N_FFT - WIN_LENGTH) // 2 + window[offset: offset + WIN_LENGTH] = frontend.symmetric_hann(WIN_LENGTH) + filters = frontend.mel_filters(MELS, N_FFT, SAMPLE_RATE).astype(np.float64) + features = np.zeros((1 + samples.size // HOP, MELS)) + for frame in range(valid_frames): + windowed = (padded[frame * HOP: frame * HOP + N_FFT] * window).astype(np.float64) + power = np.abs(np.fft.rfft(windowed)) ** 2 + features[frame] = np.log(filters @ power + 2.0**-24) + return features + + +def front_end_case() -> dict: + # 0.05 s plus one sample: six frames, the last of them past the audio. + time = np.arange(801, dtype=np.float64) / SAMPLE_RATE + signal = (0.5 * np.sin(2 * np.pi * 440.0 * time) + + 0.25 * np.sin(2 * np.pi * 3100.0 * time + 0.3) + + 0.05 * np.sin(2 * np.pi * 900.0 * time * time * 40.0)) + samples = signal.astype(np.float32) + output = _extractor()(samples, sampling_rate=SAMPLE_RATE, return_tensors="pt") + valid = int(output["attention_mask"][0].sum()) + return { + "samples": samples.tolist(), + "features": output["input_features"][0].numpy().tolist(), + "features_float64": _float64_features(samples, valid).tolist(), + "valid_frames": valid, + } + + +def speaker_cache_case() -> dict: + # The FIFO overflows by less than the update period at first and by more + # later, so frames stay queued between steps and both pop sizes occur. + policy = { + "num_speakers": 3, "subsampling_factor": 2, "hidden_size": 6, + "cache_length": 12, "silence_frames_per_speaker": 1, "fifo_length": 4, + "update_period": 3, "score_threshold": 0.25, "latest_frames_boost": 0.05, + } + config = Nemotron3DiarizationStreamingConfig( + fifo_length=policy["fifo_length"], + speaker_cache_update_period=policy["update_period"], + speaker_cache_length=policy["cache_length"], + speaker_cache_silence_frames_per_speaker=policy["silence_frames_per_speaker"], + prediction_score_threshold=policy["score_threshold"], + latest_frames_score_boost=policy["latest_frames_boost"], + num_speakers=policy["num_speakers"], subsampling_factor=policy["subsampling_factor"]) + cache = Nemotron3DiarizationSpeakerCache(config) + policy.update(min_positive_scores=cache.min_positive_scores, + strong_boosted_frames=cache.num_strong_boosted_frames, + weak_boosted_frames=cache.num_weak_boosted_frames) + + generator = torch.Generator().manual_seed(234) + width, factor, speakers = policy["hidden_size"], policy["subsampling_factor"], 3 + silence = torch.randn(width, generator=generator) + chunk, lookahead, steps = 5, 2, [] + for index in range(7): + # One step carries look-back frames between the queued rows and the chunk. + lookback = 2 if index == 4 else 0 + chunk_embeds = torch.randn(1, lookback + chunk + lookahead, width, generator=generator) + cached = cache.get_embeds(chunk_embeds) + step_input = torch.cat([cached, chunk_embeds], dim=1) + rows = step_input.shape[1] + # Speaker activity that changes over the steps, so every speaker is + # sometimes speaking, sometimes overlapped and sometimes silent. + logits = torch.randn(1, rows * factor, speakers, generator=generator) * 3.0 + logits[..., index % speakers] += 2.5 + mask = torch.ones(1, rows, dtype=torch.bool) + if index == 6: + mask[0, -1] = False # a padding frame at the end of the recording + cache.update(step_input, logits, silence, chunk, mask=mask, num_lookback_frames=lookback) + steps.append({ + "step_input": step_input[0].tolist(), + "logits": logits[0].tolist(), + "valid": mask[0].int().tolist(), + "chunk_frames": chunk, + "lookback_frames": lookback, + "cache_rows": cache.num_cache_frames, + "fifo_rows": cache.num_fifo_frames, + "compressed": cache.is_compressed, + "cache": cache.embeds[0, : cache.num_cache_frames].tolist(), + "cache_probs": cache.probs[0, : cache.num_cache_frames].tolist(), + "fifo": cache.fifo[0, : cache.num_fifo_frames].tolist(), + }) + return {"policy": policy, "silence": silence.tolist(), "steps": steps} + + +def intervals_case() -> dict: + processor = Nemotron3DiarizationProcessor(feature_extractor=_extractor()) + generator = torch.Generator().manual_seed(53) + logits = torch.randn(1, 60, 4, generator=generator).cumsum(dim=1) * 0.7 + cases = [] + for threshold in (0.5, 0.3): + segments = processor.extract_speaker_dict(logits, threshold=threshold)[0] + cases.append({"threshold": threshold, "segments": [ + [segment["Start"], segment["End"], segment["Speaker"]] for segment in segments]}) + return {"logits": logits[0].tolist(), "cases": cases} + + +def main() -> None: + DATA.mkdir(parents=True, exist_ok=True) + golden = {"front_end": front_end_case(), "speaker_cache": speaker_cache_case(), + "intervals": intervals_case()} + (DATA / "runtime_golden.json").write_text(json.dumps(golden) + "\n", encoding="utf-8") + frontend.mel_filters(MELS, N_FFT, SAMPLE_RATE).tofile(DATA / "mel_filters.f32") + frontend.symmetric_hann(WIN_LENGTH).tofile(DATA / "window.f32") + + +if __name__ == "__main__": + main() diff --git a/families/nemotron3_diarization/tests/manifests/nemotron-3-diarization.json b/families/nemotron3_diarization/tests/manifests/nemotron-3-diarization.json new file mode 100644 index 0000000000..393a7fbd41 --- /dev/null +++ b/families/nemotron3_diarization/tests/manifests/nemotron-3-diarization.json @@ -0,0 +1,24 @@ +{ + "name": "nemotron-3-diarization", + "hf_id": "nvidia/Nemotron-3-Diarization", + "hf_revision": "52a432672732425e4c19765b9fec9b5810e6f4ba", + "bundle": "nemotron-3-diarization.bundle", + "family": "nemotron3_diarization", + "task": "audio_to_timed_labels", + "precision": "fp32", + "testcases": [ + { + "name": "nemotron-3-diarization-conversation", + "premerge": true, + "test_input": "conversation", + "logit_tolerance": 0.001 + }, + { + "name": "nemotron-3-diarization-single-speaker", + "premerge": false, + "test_input": "single_speaker", + "logit_tolerance": 0.001 + } + ], + "tensor_parallel_size": 1 +} diff --git a/families/nemotron3_diarization/tests/sdk_consumer.c b/families/nemotron3_diarization/tests/sdk_consumer.c new file mode 100644 index 0000000000..53bf03a5ed --- /dev/null +++ b/families/nemotron3_diarization/tests/sdk_consumer.c @@ -0,0 +1,183 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +/* Public C11 SDK consumer for the family-owned Nemotron 3 Diarization E2E. + * Reads mono float32 PCM, runs audio_to_timed_labels with the family defaults, + * releases the model, then prints the owned result in the JSON layout of the + * family's diarize command. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +_Static_assert(sizeof(float) == 4, "input uses float32"); + +static trtmc_string_view text(const char* value) { + const trtmc_string_view result = {value, (uint64_t)strlen(value)}; + return result; +} + +static uint32_t positive(const char* value) { + char* end = NULL; + uintmax_t parsed; + errno = 0; + parsed = strtoumax(value, &end, 10); + if (errno || end == value || *end || !parsed || parsed > UINT32_MAX) + return 0; + return (uint32_t)parsed; +} + +static float* read_pcm(const char* path, size_t* count) { + FILE* file = fopen(path, "rb"); + float* samples = NULL; + long bytes; + if (!file) + return NULL; + if (fseek(file, 0, SEEK_END) == 0 && (bytes = ftell(file)) > 0 && + bytes % (long)sizeof(float) == 0 && fseek(file, 0, SEEK_SET) == 0) { + *count = (size_t)bytes / sizeof(float); + samples = (float*)malloc((size_t)bytes); + if (samples && fread(samples, sizeof(float), *count, file) != *count) { + free(samples); + samples = NULL; + } + } + fclose(file); + return samples; +} + +static int valid_view(const trtmc_timed_labels_view_v1* view) { + uint64_t i; + if (!view->labels.size || (view->interval_count && !view->intervals)) + return 0; + if (view->frame_scores.rows * view->frame_scores.columns != view->frame_scores.count || + view->frame_scores.columns != view->labels.size || view->score_kind != TRTMC_SCORE_LOGIT || + !(view->frame_seconds > 0)) + return 0; + for (i = 0; i < view->interval_count; ++i) { + const trtmc_timed_label_v1* item = &view->intervals[i]; + if (!(item->end_seconds > item->start_seconds) || item->label >= view->labels.size) + return 0; + } + for (i = 0; i < view->frame_scores.count; ++i) + if (!isfinite(view->frame_scores.data[i])) + return 0; + return 1; +} + +static void print_json(const trtmc_timed_labels_view_v1* view) { + uint64_t i, j; + fputs("{\"task\":\"audio_to_timed_labels\",\"labels\":[", stdout); + for (i = 0; i < view->labels.size; ++i) + printf("%s\"%.*s\"", i ? "," : "", (int)view->labels.data[i].size, + view->labels.data[i].data); + printf("],\"vocabulary_id\":\"%.*s\",\"intervals\":[", (int)view->vocabulary_id.size, + view->vocabulary_id.data ? view->vocabulary_id.data : ""); + for (i = 0; i < view->interval_count; ++i) + printf("%s{\"start_seconds\":%.17g,\"end_seconds\":%.17g,\"label\":%" PRIu32 "}", + i ? "," : "", view->intervals[i].start_seconds, view->intervals[i].end_seconds, + view->intervals[i].label); + printf("],\"frame_seconds\":%.17g,\"score_kind\":\"logit\",\"frame_scores\":[", + view->frame_seconds); + for (i = 0; i < view->frame_scores.rows; ++i) { + fputs(i ? ",[" : "[", stdout); + for (j = 0; j < view->frame_scores.columns; ++j) + printf("%s%.*g", j ? "," : "", FLT_DECIMAL_DIG, + (double)view->frame_scores.data[i * view->frame_scores.columns + j]); + putchar(']'); + } + puts("]}"); +} + +int main(int argc, char** argv) { + const trtmc_core_api_v1* core = NULL; + const trtmc_api_header* header = NULL; + const trtmc_audio_to_timed_labels_api_v1* task = NULL; + trtmc_model* model = NULL; + trtmc_result* result = NULL; + trtmc_error* error = NULL; + trtmc_load_options_v1 options = {0}; + trtmc_audio_to_timed_labels_request_v1 request = {0}; + trtmc_timed_labels_view_v1 view = {0}; + float* samples = NULL; + size_t count = 0; + uint32_t sample_rate; + uint64_t field_count = 0; + int status = 1; + + if (argc != 5) { + fprintf(stderr, "Usage: %s BUNDLE RUNTIME_ROOT PCM_F32 SAMPLE_RATE\n", argv[0]); + return 2; + } + sample_rate = positive(argv[4]); + samples = read_pcm(argv[3], &count); + if (!sample_rate || !samples) { + fprintf(stderr, "input must be nonempty mono float32 PCM with a positive sample rate\n"); + goto cleanup; + } + if (trtmc_get_api(1, 0, &core) != TRTMC_OK || !core) { + fprintf(stderr, "unable to obtain the v1 C API\n"); + goto cleanup; + } + options.struct_size = sizeof(options); + options.runtime_root = text(argv[2]); + if (core->model_load(text(argv[1]), &options, &model, &error) != TRTMC_OK) + goto cleanup; + if (core->model_get_task_api(model, text(TRTMC_TASK_AUDIO_TO_TIMED_LABELS), 1, 0, &header, + &error) != TRTMC_OK) + goto cleanup; + if (!header || header->byte_size < sizeof(*task)) { + fprintf(stderr, "incomplete audio_to_timed_labels C table\n"); + goto cleanup; + } + task = (const trtmc_audio_to_timed_labels_api_v1*)header; + if (core->config_field_count(model, text(TRTMC_TASK_AUDIO_TO_TIMED_LABELS), 1, 0, &field_count, + &error) != TRTMC_OK) + goto cleanup; + if (field_count != 1) { + fprintf(stderr, "Nemotron 3 Diarization must expose exactly its threshold Config\n"); + goto cleanup; + } + + request.audio = (trtmc_audio_view_v1){samples, (uint64_t)count, 1, sample_rate, 1}; + if (task->run(model, &request, NULL, &result, &error) != TRTMC_OK) + goto cleanup; + /* The result must stay readable after its input and model are gone. */ + free(samples); + samples = NULL; + core->model_release(model); + model = NULL; + + if (task->result_view(result, &view, &error) != TRTMC_OK) + goto cleanup; + if (!valid_view(&view)) { + fprintf(stderr, "timed labels result breaks its contract\n"); + goto cleanup; + } + print_json(&view); + status = fflush(stdout) == 0 && !ferror(stdout) ? 0 : 1; + +cleanup: + if (error && core) { + const trtmc_string_view message = core->error_message(error); + fprintf(stderr, "C API error %d: ", (int)core->error_code(error)); + fwrite(message.data, 1, (size_t)message.size, stderr); + fputc('\n', stderr); + core->error_release(error); + } + if (core) { + core->result_release(result); + core->model_release(model); + } + free(samples); + return status; +} diff --git a/families/nemotron3_diarization/tests/sdk_consumer.cpp b/families/nemotron3_diarization/tests/sdk_consumer.cpp new file mode 100644 index 0000000000..f2d22e2704 --- /dev/null +++ b/families/nemotron3_diarization/tests/sdk_consumer.cpp @@ -0,0 +1,124 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Public C++17 SDK consumer for the family-owned Nemotron 3 Diarization E2E. +// Reads mono float32 PCM, runs audio_to_timed_labels with an explicit +// threshold, releases the model, then prints the owned result in the JSON +// layout of the family's diarize command. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +std::uint32_t positive(const char* argument) { + const std::string text(argument); + std::size_t consumed = 0; + const auto value = std::stoull(text, &consumed); + if (consumed != text.size() || !value || value > std::numeric_limits::max()) + throw std::invalid_argument("the sample rate must be a positive uint32 value"); + return static_cast(value); +} + +std::vector read_pcm(const char* path) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + const auto bytes = file ? static_cast(file.tellg()) : std::streamoff{0}; + if (bytes <= 0 || bytes % static_cast(sizeof(float)) != 0) + throw std::runtime_error("input must be nonempty mono float32 PCM"); + std::vector samples(static_cast(bytes) / sizeof(float)); + file.seekg(0); + file.read(reinterpret_cast(samples.data()), bytes); + if (!file) + throw std::runtime_error("failed to read the float32 PCM input"); + return samples; +} + +void check(const trtmc::TimedLabelsResult& result) { + const auto labels = result.labels(); + const auto scores = result.frame_scores(); + if (labels.empty() || scores.columns != labels.size() || + scores.rows * scores.columns != scores.values.size() || + result.score_kind() != TRTMC_SCORE_LOGIT || !(result.frame_seconds() > 0)) + throw std::runtime_error("timed labels result breaks its contract"); + for (const auto& interval : result.intervals()) + if (!(interval.end_seconds > interval.start_seconds) || interval.label >= labels.size()) + throw std::runtime_error("timed label interval breaks its contract"); + for (const float value : scores.values) + if (!std::isfinite(value)) + throw std::runtime_error("timed label frame score is not finite"); +} + +void print(const trtmc::TimedLabelsResult& result) { + auto& out = std::cout; + out << "{\"task\":\"audio_to_timed_labels\",\"labels\":["; + const auto labels = result.labels(); + for (std::size_t i = 0; i < labels.size(); ++i) + out << (i ? "," : "") << '"' << labels[i] << '"'; + out << "],\"vocabulary_id\":\"" << result.vocabulary_id() << "\",\"intervals\":["; + out.precision(std::numeric_limits::max_digits10); + const auto intervals = result.intervals(); + for (std::size_t i = 0; i < intervals.size(); ++i) + out << (i ? "," : "") << "{\"start_seconds\":" << intervals[i].start_seconds + << ",\"end_seconds\":" << intervals[i].end_seconds + << ",\"label\":" << intervals[i].label << '}'; + out << "],\"frame_seconds\":" << result.frame_seconds() + << ",\"score_kind\":\"logit\",\"frame_scores\":["; + out.precision(std::numeric_limits::max_digits10); + const auto scores = result.frame_scores(); + for (std::uint64_t row = 0; row < scores.rows; ++row) { + out << (row ? ",[" : "["); + for (std::uint64_t column = 0; column < scores.columns; ++column) + out << (column ? "," : "") << scores.values[row * scores.columns + column]; + out << ']'; + } + out << "]}\n"; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 5) { + std::cerr << "Usage: " << argv[0] << " BUNDLE RUNTIME_ROOT PCM_F32 SAMPLE_RATE\n"; + return 2; + } + try { + static_assert(sizeof(float) == 4, "input uses float32"); + const auto sample_rate = positive(argv[4]); + auto samples = read_pcm(argv[3]); + + // The model and its input go out of scope before the result is read. + auto result = [&] { + trtmc::LoadOptions options; + options.runtime_root = argv[2]; + auto model = trtmc::Model::load(argv[1], options); + const auto task = model.task(); + const auto fields = task.config_fields(); + if (fields.size() != 1 || fields[0].name != "threshold") + throw std::runtime_error( + "Nemotron 3 Diarization must expose exactly its threshold Config"); + // The family default, supplied explicitly through the typed Config. + return task.run({{{samples.data(), samples.size()}, sample_rate, 1}}, + {{"threshold", 0.5}}); + }(); + samples.clear(); + samples.shrink_to_fit(); + + check(result); + print(result); + std::cout.flush(); + if (!std::cout) + throw std::runtime_error("failed to write timed labels output"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/nemotron3_diarization/tests/test_cli.py b/families/nemotron3_diarization/tests/test_cli.py new file mode 100644 index 0000000000..258f6ec420 --- /dev/null +++ b/families/nemotron3_diarization/tests/test_cli.py @@ -0,0 +1,77 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The family's command declaration (cli.json), without a model or a GPU.""" + +from __future__ import annotations + +import pytest + +from tensorrt_model_connect import family_cli + +FAMILY = "nemotron3_diarization" +HEAVY = {"torch", "tensorrt", "transformers", "huggingface_hub"} + + +@pytest.fixture +def no_model_imports(monkeypatch): + """Fail any import of the family's modules or of a heavy dependency.""" + original = family_cli.importlib.import_module + + def guarded(name, *args, **kwargs): + assert not name.startswith(f"families.{FAMILY}.") and name not in HEAVY, name + return original(name, *args, **kwargs) + + monkeypatch.setattr(family_cli.importlib, "import_module", guarded) + + +@pytest.fixture +def executed(monkeypatch): + """Record the native hand-off instead of replacing the test process.""" + calls = [] + + def execv(path, argv): + calls.append(argv[1:]) + raise SystemExit(0) + + monkeypatch.setattr(family_cli.os, "execv", execv) + return calls + + +def test_declares_one_native_diarize_command(): + (command,) = family_cli.load_family_cli(FAMILY)["commands"] + assert (command["name"], command["executor"], command["handler"]) == ( + "diarize", "native", "diarize") + arguments = {argument["name"]: argument for argument in command["arguments"]} + assert set(arguments) == {"bundle", "audio", "runtime_root", "threshold"} + assert arguments["audio"]["required"] is True + # Without a declared default, an absent threshold keeps the family's own. + assert arguments["threshold"]["type"] == "float" and "default" not in arguments["threshold"] + + +def test_help_loads_no_model(no_model_imports, capsys): + with pytest.raises(SystemExit) as caught: + family_cli.main([FAMILY, "diarize", "--help"]) + assert caught.value.code == 0 + help_text = capsys.readouterr().out + assert "--audio" in help_text and "--threshold" in help_text + + +def test_a_valid_call_reaches_the_native_handler(no_model_imports, executed): + argv = [FAMILY, "diarize", "model.bundle", "--audio", "speech.wav", "--threshold", "0.3"] + with pytest.raises(SystemExit) as caught: + family_cli.main(argv) + assert caught.value.code == 0 and executed == [argv] + + +@pytest.mark.parametrize("arguments", [ + ["model.bundle"], + ["model.bundle", "--audio", "speech.wav", "--threshold", "nan"], + ["model.bundle", "--audio", "speech.wav", "--threshold", "0.3", "--threshold", "0.4"], + ["model.bundle", "--audio", "speech.wav", "--set", "threshold=0.3"], +]) +def test_invalid_calls_are_refused_before_the_native_handler( + no_model_imports, executed, arguments): + with pytest.raises(SystemExit) as caught: + family_cli.main([FAMILY, "diarize", *arguments]) + assert caught.value.code == 2 and executed == [] diff --git a/families/nemotron3_diarization/tests/test_e2e.py b/families/nemotron3_diarization/tests/test_e2e.py new file mode 100644 index 0000000000..2c43a18d43 --- /dev/null +++ b/families/nemotron3_diarization/tests/test_e2e.py @@ -0,0 +1,645 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Direct build, native-runtime, public-SDK and official-reference E2E for Nemotron 3 Diarization.""" + +from __future__ import annotations + +import json +import math +import os +import subprocess +import wave +from fnmatch import fnmatch +from pathlib import Path + +import pytest + +from tensorrt_model_connect import BuildRequest, build +from tools.e2e_evidence import record_evidence + +FAMILY = "nemotron3_diarization" +TASKS = frozenset({"audio_to_timed_labels"}) +TEST_ROOT = Path(__file__).resolve().parent +MANIFEST_ROOT = TEST_ROOT / "manifests" +SAMPLE_RATE = 16000 +# Two people from two public recordings: a LibriSpeech test-clean reader and +# the project maintainer. Both are 16 kHz mono PCM16. +FIRST_SPEAKER = "data/librispeech-test-clean-6930-75918-0003.wav" +SECOND_SPEAKER = "data/maintainer-recording-16k-mono.wav" +# The one case of a testcase-only selection that names none of this family's +# cases: another collected family may own it, or it is a typo. +UNMATCHED = "unmatched-testcase-selection" + + +def _manifest_value(container: dict, key: str, kinds: tuple[type, ...]): + """A manifest value of its own JSON type, never coerced (a boolean is not a number).""" + value = container[key] + if isinstance(value, bool) or not isinstance(value, kinds): + names = " or ".join(kind.__name__ for kind in kinds) + raise TypeError(f"{FAMILY} manifest {key} must be a JSON {names}, not {value!r}") + return value + + +def _case_index() -> dict[str, tuple[Path, dict, dict]]: + result = {} + for path in sorted(MANIFEST_ROOT.glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["family"] == FAMILY + assert manifest["task"] in TASKS + for case in manifest["testcases"]: + name = _manifest_value(case, "name", (str,)) + assert name not in result + result[name] = (path, manifest, case) + return result + + +CASES = _case_index() + + +def _filters(config) -> tuple[set[str], set[str]]: + model_filters = set() + for raw in config.getoption("--e2e-model") or []: + model_filters.update(item.strip() for item in str(raw).split(",") if item.strip()) + models_file = config.getoption("--e2e-models-file") + if models_file: + model_filters.update( + line.strip() + for line in Path(models_file).read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ) + testcase_filters = set() + for raw in config.getoption("--e2e-testcase") or []: + testcase_filters.update(item.strip() for item in str(raw).split(",") if item.strip()) + return model_filters, testcase_filters + + +def _selected_cases(config) -> tuple[list[str], bool]: + model_filters, testcase_filters = _filters(config) + if not model_filters and not testcase_filters: + return sorted(CASES), False + selected = [] + for name, (_, manifest, _) in CASES.items(): + model_match = ( + not model_filters + or FAMILY in model_filters + or name in model_filters + or manifest["name"] in model_filters + ) + if model_match and (not testcase_filters or name in testcase_filters): + selected.append(name) + named = FAMILY in model_filters or any( + name in model_filters or manifest["name"] in model_filters + for name, (_, manifest, _) in CASES.items() + ) + if named and not selected: + # Pytest skips an empty parametrization, so a selection that names this + # family but matches none of its cases would pass without testing. + raise pytest.UsageError( + f"the E2E selection names {FAMILY}, but --e2e-testcase " + f"{', '.join(sorted(testcase_filters))} matches none of its cases: " + f"{', '.join(sorted(CASES))}" + ) + return sorted(selected), True + + +def _resolve_unmatched(request) -> None: + """Skip when another collected family's E2E owns the selected testcase; fail otherwise.""" + _, wanted = _filters(request.config) + owned = set() + for item in request.session.items: + params = getattr(getattr(item, "callspec", None), "params", {}) + name = getattr(item, "originalname", None) or item.name + if fnmatch(name, "test_*e2e*") and params.get("case_name") not in (None, UNMATCHED): + owned.add(params["case_name"]) + if wanted & owned: + pytest.skip(f"another collected family owns --e2e-testcase {', '.join(sorted(wanted))}") + pytest.fail( + f"--e2e-testcase {', '.join(sorted(wanted))} matches no collected E2E case; " + f"{FAMILY} has {', '.join(sorted(CASES))}" + ) + + +def pytest_generate_tests(metafunc) -> None: + if "case_name" in metafunc.fixturenames: + names, enabled = _selected_cases(metafunc.config) + model_filters, testcase_filters = _filters(metafunc.config) + parameters = names + if enabled and not names and testcase_filters and not model_filters: + # Pytest would skip the empty parametrization; whether the testcase + # is a typo is known only once the whole session is collected. + parameters = names = [UNMATCHED] + if not enabled: + parameters = [ + pytest.param( + name, + marks=pytest.mark.skip( + reason="direct E2E requires one of the three explicit E2E selectors" + ), + ) + for name in names + ] + metafunc.parametrize("case_name", parameters, ids=names) + + +def _required_path(value: str | None, label: str) -> Path: + assert value, f"selected {FAMILY} E2E requires {label}" + path = Path(value) + assert path.exists(), f"selected {FAMILY} E2E {label} does not exist: {path}" + return path + + +def _model_dir(manifest: dict) -> Path: + explicit = os.environ.get(f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + if explicit: + return _required_path(explicit, f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + from huggingface_hub import snapshot_download + + try: + snapshot = snapshot_download( + repo_id=manifest["hf_id"], revision=manifest.get("hf_revision"), local_files_only=True + ) + except Exception as error: + raise AssertionError( + f"selected {FAMILY} E2E requires the exact cached checkpoint {manifest['hf_id']}" + ) from error + return Path(snapshot) + + +def _runtime() -> tuple[Path, Path, Path]: + binary = _required_path(os.environ.get("TRTMC_BINARY"), "TRTMC_BINARY") + runtime_root = _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + native_build = _required_path( + os.environ.get("TRTMC_NATIVE_BUILD_DIR"), "TRTMC_NATIVE_BUILD_DIR" + ) + assert (runtime_root / "libtrtmc_backend_trt.so").is_file() + assert (runtime_root / f"libtrtmc_model_{FAMILY}.so").is_file() + import torch + + assert torch.cuda.is_available(), f"selected {FAMILY} E2E requires CUDA" + return binary, runtime_root, native_build + + +def _build(model_dir: Path, bundle: Path, manifest: dict) -> None: + build( + BuildRequest( + model_dir=model_dir, + output_path=bundle, + family=FAMILY, + task=manifest["task"], + precision=manifest["precision"], + tensor_parallel_size=_manifest_value(manifest, "tensor_parallel_size", (int,)), + ) + ) + + +def _asset(raw: str) -> Path: + path = TEST_ROOT / raw + assert path.is_file(), f"selected {FAMILY} E2E asset does not exist: {path}" + return path + + +def _read_pcm16(path: Path): + import numpy as np + + with wave.open(str(path)) as handle: + assert handle.getsampwidth() == 2 and handle.getnchannels() == 1 + assert handle.getframerate() == SAMPLE_RATE + raw = np.frombuffer(handle.readframes(handle.getnframes()), dtype=" dict: + env = os.environ.copy() + env["LD_LIBRARY_PATH"] = os.pathsep.join( + value for value in (str(runtime_root), env.get("LD_LIBRARY_PATH", "")) if value + ) + return env + + +def _native(binary: Path, runtime_root: Path, bundle: Path, wav: Path) -> dict: + """The family's own command, `trtmc nemotron3_diarization diarize` (cli.json).""" + completed = subprocess.run( + [str(binary), FAMILY, "diarize", str(bundle), "--runtime-root", str(runtime_root), + "--audio", str(wav)], + check=True, capture_output=True, text=True, env=_environment(runtime_root), timeout=3600, + ) + payloads = [line for line in completed.stdout.splitlines() if line.startswith("{")] + assert len(payloads) == 1, f"native diarize returned no single JSON: {completed.stdout[-1000:]}" + result = json.loads(payloads[0]) + assert result["task"] == "audio_to_timed_labels" + return result + + +def _sdk_results(native_build: Path, runtime_root: Path, bundle: Path, samples, + directory: Path) -> list[dict]: + """The public C and C++ consumers on the same float32 samples the binary decoded.""" + raw = directory / "sdk-input.f32" + samples.tofile(raw) + outputs = [] + for language in ("c", "cpp"): + consumer = native_build / f"test_{FAMILY}_sdk_{language}" + assert consumer.is_file(), f"build the family-owned SDK consumer: {consumer.name}" + completed = subprocess.run( + [str(consumer), str(bundle), str(runtime_root), str(raw), str(SAMPLE_RATE)], + check=True, capture_output=True, text=True, env=_environment(runtime_root), + timeout=3600, + ) + payloads = [line for line in completed.stdout.splitlines() if line.startswith("{")] + assert len(payloads) == 1, f"the {language} consumer must print one result" + outputs.append(json.loads(payloads[0])) + return outputs + + +def _official_reference(model_dir: Path, samples): + """Transformers' own Nemotron3Diarization in float32 on the GPU, TF32 off. + + The speaker cache keeps the frames its scores rank highest. The native + runtime breaks an exact tie deterministically, by the first index seen + (`top_k_first_seen`). PyTorch does not guarantee the order of tied + indices in torch.topk; on CUDA the reference's selections agree with that + rule on the E2E inputs, so the reference runs on CUDA, not the CPU. A tie + broken differently changes the frames the cache keeps: the first chunk, + which runs before any cache state, is gated on its own, and the + later-chunk gate then fails with a message that points at the cache. + """ + import torch + from transformers import AutoModelForAudioFrameClassification, AutoProcessor + + # TF32 is process-wide: off for this run only, and restored even when it + # fails. Matmul goes through the float32 matmul precision alone: setting + # it after `matmul.allow_tf32` mixes PyTorch's two APIs, and the next + # reference run in the process then fails to read the precision. + saved = torch.get_float32_matmul_precision(), torch.backends.cudnn.allow_tf32 + torch.set_float32_matmul_precision("highest") + torch.backends.cudnn.allow_tf32 = False + try: + assert not torch.backends.cuda.matmul.allow_tf32 and not torch.backends.cudnn.allow_tf32 + processor = AutoProcessor.from_pretrained(str(model_dir)) + model = AutoModelForAudioFrameClassification.from_pretrained( + str(model_dir), dtype=torch.float32).to("cuda").eval() + inputs = processor(samples, sampling_rate=SAMPLE_RATE).to("cuda") + with torch.inference_mode(): + logits = model(**inputs).logits + mask = inputs["attention_mask"] + valid = int(mask[0].sum()) + segments = processor.extract_speaker_dict(logits, mask)[0] + reference = logits[0, :valid].double().cpu().numpy() + del model + torch.cuda.empty_cache() + finally: + torch.set_float32_matmul_precision(saved[0]) + torch.backends.cudnn.allow_tf32 = saved[1] + return reference, [(item["Start"], item["End"], item["Speaker"]) for item in segments] + + +def _active(logits): + """The processor's rule: the float32 logistic of the logit above 0.5.""" + import numpy as np + + values = logits.astype(np.float32) + return np.float32(1.0) / (np.float32(1.0) + np.exp(-values)) > np.float32(0.5) + + +def _runs(active) -> list[tuple[int, int, int]]: + runs = [] + for speaker in range(active.shape[1]): + start = None + for frame in range(active.shape[0] + 1): + on = frame < active.shape[0] and bool(active[frame, speaker]) + if on and start is None: + start = frame + if not on and start is not None: + runs.append((start, frame, speaker)) + start = None + return sorted(runs) + + +def _frames(intervals) -> list[tuple[int, int, int]]: + return sorted((round(start * 100), round(end * 100), int(label)) + for start, end, label in intervals) + + +# A native endpoint is a whole frame times the 10 ms hop, divided once in +# double precision, so it lies on the grid to about 1e-12 of a frame. Rounding +# to frames alone would hide an endpoint that is off by less than 5 ms. +GRID_TOLERANCE_FRAMES = 1e-6 + + +def _native_frames(intervals) -> list[tuple[int, int, int]]: + """Native intervals as frames, after checking every endpoint against the 10 ms grid.""" + intervals = list(intervals) + for start, end, label in intervals: + for seconds in (start, end): + offset = abs(seconds * 100 - round(seconds * 100)) + assert offset <= GRID_TOLERANCE_FRAMES, ( + f"native interval endpoint {seconds!r} s of label {label} is {offset:.3g} frames " + "off the 10 ms frame grid") + return _frames(intervals) + + +def _check(name: str, label: str, actual, operator: str, expected) -> dict: + """One row of a reference_comparison record, with the verdict its values state.""" + passed = actual <= expected if operator == "<=" else actual == expected + return {"name": name, "label": label, "scope": "independent_reference", "actual": actual, + "operator": operator, "expected": expected, "passed": bool(passed)} + + +def _timeline(path: Path, native_active, reference_active) -> tuple[Path, int]: + """A PNG of who is active when: per speaker, the native row above the reference row. + + Returns the file and the frames one pixel column covers. Written with zlib, + so the report needs no plotting package. + """ + import struct + import zlib + + import numpy as np + + frames = native_active.shape[0] + speakers = [speaker for speaker in range(native_active.shape[1]) + if native_active[:, speaker].any() or reference_active[:, speaker].any()] + step = max(1, -(-frames // 1200)) + columns = max(1, -(-frames // step)) + lane, gap = 10, 6 + image = np.full((max(1, len(speakers)) * (2 * lane + gap), columns, 3), 255, dtype=np.uint8) + for row, speaker in enumerate(speakers): + for offset, active, color in ((0, native_active, (31, 119, 180)), + (lane, reference_active, (255, 127, 14))): + padded = np.zeros(columns * step, dtype=bool) + padded[:frames] = active[:, speaker] + on = padded.reshape(columns, step).any(axis=1) + top = row * (2 * lane + gap) + offset + band = image[top:top + lane - 1] + band[:, ~on] = (230, 230, 230) + band[:, on] = color + + def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + rows = b"".join(b"\x00" + line.tobytes() for line in image) + header = struct.pack(">IIBBBBB", columns, image.shape[0], 8, 2, 0, 0, 0) + path.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")) + return path, step + + +def _first_chunk_frames(model_dir: Path) -> int: + """Spectrogram frames of the first offline chunk, which runs before any cache state.""" + config = json.loads((model_dir / "config.json").read_text(encoding="utf-8")) + return int(config["chunk_length"]) * int(config["audio_config"]["subsampling_factor"]) + + +def _assert_parity(native: dict, reference, segments, case: dict, first_chunk: int, + evidence: tuple[Path, Path] | None = None) -> None: + """The native result against the reference; `evidence` names the retained native and + reference logits files, next to which the comparison records keep their interval tables.""" + import numpy as np + + assert native["labels"] == [f"speaker_{index}" for index in range(8)] + assert native["vocabulary_id"] == "", "speakers are result-local, not a vocabulary" + assert native["score_kind"] == "logit" and native["frame_seconds"] == 0.01 + logits = np.asarray(native["frame_scores"], dtype=np.float64) + assert logits.shape == reference.shape, ( + f"frame count differs: native={logits.shape} reference={reference.shape}") + + # The gate is on every logit of every frame and speaker, not on the + # segments: a segment boundary moves only when a logit crosses zero. + # Calibration of the manifests' 1e-3 on one B300, float32 against the + # float32 reference: healthy builds stay at 1.6e-4 (conversation, 3 runs of + # 44,800 logits) and 5.2e-5 (single speaker, 3 runs of 18,648 logits); + # builds made defective on purpose miss it on the conversation by orders: + # 0.10 (tanh GELU), 0.45 (periodic Hann window), 3.7 (no latest-frames + # boost in the cache), 39 (interleaved RoPE pairs). + tolerance = _manifest_value(case, "logit_tolerance", (int, float)) + assert math.isfinite(tolerance) and tolerance > 0, f"unusable logit_tolerance {tolerance!r}" + gap = np.abs(logits - reference) + worst = np.unravel_index(int(np.argmax(gap)), gap.shape) + first = float(gap[:first_chunk].max()) + print(f"{case['name']}: {logits.shape[0]} frames, worst logit gap {gap[worst]:.3e} at " + f"frame {worst[0]} speaker {worst[1]}, mean gap {gap.mean():.3e}, first chunk " + f"{first:.3e}") + if evidence is not None: + record_evidence("reference_comparison", { + "label": "Frame logits against the Transformers reference", + "scope": "independent_reference", "enforced": True, + "native": evidence[0], "reference": evidence[1], + "checks": [ + _check("first_chunk_logit_gap", "First chunk: max |native - reference| logit", + first, "<=", float(tolerance)), + _check("logit_gap", "All frames and speakers: max |native - reference| logit", + float(gap[worst]), "<=", float(tolerance)), + ], + }) + # The first chunk sees no speaker-cache state, so a gap there is the front + # end, the engines or the step input, never the cache. + assert first <= tolerance, f"first-chunk logit gap {first:.3e} exceeds {tolerance}" + # Later chunks add what the first never reaches: the cached and queued rows + # ahead of the chunk, positions past the first step, the padding mask at + # the end, and which frames the cache kept. Its selections break float32 + # near-ties among nearly saturated frames identically in the native and + # reference runs, so a gap here is not rounding: a float64 reference, which + # keeps other frames, moves these logits by about 0.4 without changing a + # decision. + assert gap[worst] <= tolerance, ( + f"logit gap {gap[worst]:.3e} at frame {worst[0]} (first chunk {first:.3e}) exceeds " + f"{tolerance}: look at the later steps' cached and queued rows, positions past the " + "first step, the padding mask and the frames the speaker cache kept") + + native_active, reference_active = _active(logits), _active(reference) + native_frames = _native_frames((item["start_seconds"], item["end_seconds"], item["label"]) + for item in native["intervals"]) + reference_frames = _frames(segments) + assert native_frames == _runs(native_active), ( + "native intervals are not the runs of its own frame decisions") + assert reference_frames == _runs(reference_active), ( + "the reference segments are not the runs of its frame decisions") + # A decision may differ only where the reference itself sits within the + # logit tolerance of the threshold; anywhere else it is a defect. + flipped = np.argwhere(native_active != reference_active) + if evidence is not None: + directory = evidence[0].parent + tables = (directory / "native_intervals.npy", directory / "reference_intervals.npy") + for table, frames in zip(tables, (native_frames, reference_frames)): + np.save(table, np.asarray(frames, dtype=np.int64).reshape(-1, 3)) + beyond = sum(1 for frame, speaker in flipped if abs(reference[frame, speaker]) > tolerance) + checks = [_check("decisions_flipped_beyond_tolerance", + "Frame decisions that differ where |reference logit| exceeds the tolerance", + beyond, "==", 0)] + if not len(flipped): + differing = len(set(native_frames) ^ set(reference_frames)) + checks.append(_check("intervals_differing", + "Intervals, as [start frame, end frame, speaker], not in both results", + differing, "==", 0)) + record_evidence("reference_comparison", { + "label": "Speaker intervals against the Transformers reference segments", + "scope": "independent_reference", "enforced": True, + "native": tables[0], "reference": tables[1], "checks": checks, + }) + for frame, speaker in flipped: + assert abs(reference[frame, speaker]) <= tolerance, ( + f"frame {frame} speaker {speaker} flipped with reference logit " + f"{reference[frame, speaker]:.4f}") + if not len(flipped): + assert native_frames == reference_frames + speakers = sorted({speaker for _, _, speaker in segments}) + print(f"{case['name']}: {len(native['intervals'])} intervals, reference speakers {speakers}, " + f"{len(flipped)} near-threshold decisions differ; setup {native['setup_ms']:.1f} ms, " + f"inference {native['inference_ms']:.1f} ms") + if case["test_input"] == "conversation": + assert speakers[:2] == [0, 1], "the conversation must exercise two speakers" + + +def test_e2e(tmp_path: Path, case_name: str, request) -> None: + if case_name == UNMATCHED: + _resolve_unmatched(request) + manifest_path, manifest, case = CASES[case_name] + assert manifest_path.is_file() + binary, runtime_root, native_build = _runtime() + model_dir = _model_dir(manifest) + bundle = tmp_path / _manifest_value(manifest, "bundle", (str,)) + _build(model_dir, bundle, manifest) + assert bundle.is_file(), f"{FAMILY} bundle was not produced: {bundle}" + + import numpy as np + + wav, samples = _input_audio(case, tmp_path) + record_evidence("inputs", { + "case": case, "audio": wav, "sample_rate": SAMPLE_RATE, + "seconds": round(len(samples) / SAMPLE_RATE, 3), + "checkpoint": f"{manifest['hf_id']}@{manifest['hf_revision']}", + }) + native = _native(binary, runtime_root, bundle, wav) + # The consumers print float32 scores with nine digits, the CLI with the + # double that holds them; both name the same float32 values exactly. + native_scores = np.asarray(native["frame_scores"], dtype=np.float32) + for sdk in _sdk_results(native_build, runtime_root, bundle, samples, tmp_path): + for key in ("labels", "vocabulary_id", "intervals", "frame_seconds", "score_kind"): + assert sdk[key] == native[key], f"the public SDK result differs from the CLI's {key}" + assert np.array_equal(np.asarray(sdk["frame_scores"], dtype=np.float32), native_scores), ( + "the public SDK frame scores differ from the CLI's") + reference, segments = _official_reference(model_dir, samples) + native_file, reference_file = tmp_path / "native_logits.npy", tmp_path / "reference_logits.npy" + np.save(native_file, native_scores) + np.save(reference_file, reference) + timeline, step = _timeline(tmp_path / "speaker_timeline.png", _active(native_scores), + _active(reference)) + record_evidence("native", { + "intervals": native["intervals"], "labels": native["labels"], + "frame_seconds": native["frame_seconds"], "score_kind": native["score_kind"], + "frame_scores": native_file, "timeline": timeline, + "setup_ms": native["setup_ms"], "inference_ms": native["inference_ms"], + }) + record_evidence("reference", { + "mode": "hf_transformers", "logits": reference_file, + "segments": [{"start_seconds": float(start), "end_seconds": float(end), + "speaker": int(speaker)} for start, end, speaker in segments], + }) + record_evidence("thresholds", { + "logit_tolerance": _manifest_value(case, "logit_tolerance", (int, float))}) + record_evidence("views", [{ + "title": "Speaker timeline", + "caption": "One row pair per active speaker: native above (blue), reference below " + f"(orange); a pixel column covers {step * 10} ms.", + }]) + _assert_parity(native, reference, segments, case, _first_chunk_frames(model_dir), + evidence=(native_file, reference_file)) + + +def test_parity_refuses_native_endpoints_off_the_frame_grid() -> None: + """An endpoint off the 10 ms grid fails even when rounding to frames would hide it.""" + import numpy as np + + logits = np.full((6, 8), -5.0) + logits[1:4, 0] = 5.0 + case = {"name": "frame-grid", "logit_tolerance": 1e-3, "test_input": "single_speaker"} + segments = [(0.01, 0.04, 0)] + + def native(start: float, end: float) -> dict: + return {"labels": [f"speaker_{index}" for index in range(8)], "vocabulary_id": "", + "score_kind": "logit", "frame_seconds": 0.01, "frame_scores": logits.tolist(), + "intervals": [{"start_seconds": start, "end_seconds": end, "label": 0}], + "setup_ms": 0.0, "inference_ms": 0.0} + + _assert_parity(native(0.01, 0.04), logits, segments, case, first_chunk=6) + # 2 ms and 4.9 ms off the grid: both still round to frames 1 and 4. + for start, end in ((0.012, 0.04), (0.01, 0.0449)): + with pytest.raises(AssertionError, match="off the 10 ms frame grid"): + _assert_parity(native(start, end), logits, segments, case, first_chunk=6) + + +def test_the_reference_run_restores_the_tf32_settings(monkeypatch) -> None: + """The reference turns TF32 off for its own run only, also when that run fails, + and the next reference run in the same process works too.""" + torch = pytest.importorskip("torch") + transformers = pytest.importorskip("transformers") + + def fail(*args, **kwargs): + raise RuntimeError("reference failed") + + monkeypatch.setattr(transformers.AutoProcessor, "from_pretrained", fail) + precision, cudnn = torch.get_float32_matmul_precision(), torch.backends.cudnn.allow_tf32 + try: + for incoming in ("highest", "medium"): + torch.set_float32_matmul_precision(incoming) + torch.backends.cudnn.allow_tf32 = True + for _ in range(2): + with pytest.raises(RuntimeError, match="reference failed"): + _official_reference(Path("unused"), None) + assert torch.get_float32_matmul_precision() == incoming + assert torch.backends.cuda.matmul.allow_tf32 == (incoming != "highest") + assert torch.backends.cudnn.allow_tf32 + finally: + torch.set_float32_matmul_precision(precision) + torch.backends.cudnn.allow_tf32 = cudnn diff --git a/families/nemotron3_diarization/tests/test_e2e_selection.py b/families/nemotron3_diarization/tests/test_e2e_selection.py new file mode 100644 index 0000000000..7f9bda1ff8 --- /dev/null +++ b/families/nemotron3_diarization/tests/test_e2e_selection.py @@ -0,0 +1,118 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""E2E harness checks without a GPU: case selection and manifest value types.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from families.nemotron3_diarization.tests import test_e2e + +CONVERSATION = "nemotron-3-diarization-conversation" + + +class _Config: + def __init__(self, options: dict[str, list[str]]) -> None: + self._options = options + + def getoption(self, name: str): + return self._options.get(name) + + +def _select(**options: list[str]) -> tuple[list[str], bool]: + names = {"model": "--e2e-model", "testcase": "--e2e-testcase"} + return test_e2e._selected_cases(_Config({names[key]: value for key, value in options.items()})) + + +@pytest.mark.parametrize( + "model", ["nemotron3_diarization", "nemotron-3-diarization", CONVERSATION] +) +def test_naming_the_family_with_an_unknown_case_fails(model): + with pytest.raises(pytest.UsageError, match="matches none of its cases"): + _select(model=[model], testcase=["nemotron-3-diarization-conversaton"]) + + +def test_known_case_is_selected(): + assert _select(model=["nemotron3_diarization"], testcase=[CONVERSATION]) == ( + [CONVERSATION], + True, + ) + + +def test_selection_of_another_family_skips_this_file(): + assert _select(model=["whisper"], testcase=["whisper-tiny-en"]) == ([], True) + assert _select(testcase=["whisper-tiny-en"]) == ([], True) + + +class _Metafunc: + fixturenames = ("case_name",) + + def __init__(self, options: dict[str, list[str]]) -> None: + self.config = _Config(options) + self.calls = [] + + def parametrize(self, name, parameters, ids): + self.calls.append((name, list(parameters), list(ids))) + + +def _item(name: str, case_name: str): + return SimpleNamespace(name=name, originalname=name, + callspec=SimpleNamespace(params={"case_name": case_name})) + + +def _request(testcases: list[str], items: list) -> SimpleNamespace: + return SimpleNamespace(config=_Config({"--e2e-testcase": testcases}), + session=SimpleNamespace(items=items)) + + +def test_a_testcase_only_selection_of_no_own_case_runs_one_placeholder(): + metafunc = _Metafunc({"--e2e-testcase": ["nemotron-3-diarization-conversaton"]}) + test_e2e.pytest_generate_tests(metafunc) + assert metafunc.calls == [("case_name", [test_e2e.UNMATCHED], [test_e2e.UNMATCHED])] + + +def test_a_selection_of_another_family_keeps_its_empty_parametrization(): + metafunc = _Metafunc({"--e2e-model": ["whisper"], "--e2e-testcase": ["whisper-tiny-en"]}) + test_e2e.pytest_generate_tests(metafunc) + assert metafunc.calls == [("case_name", [], [])] + + +def test_an_unmatched_testcase_fails_when_no_collected_e2e_owns_it(): + typo = "nemotron-3-diarization-conversaton" + items = [_item("test_e2e", test_e2e.UNMATCHED), + _item("test_official_checkpoint_e2e", "whisper-tiny-en"), + _item("test_selection", typo)] + with pytest.raises(pytest.fail.Exception, match="matches no collected E2E case"): + test_e2e._resolve_unmatched(_request([typo], items)) + + +def test_an_unmatched_testcase_skips_when_another_family_owns_it(): + items = [_item("test_e2e", test_e2e.UNMATCHED), + _item("test_official_checkpoint_e2e", "whisper-tiny-en")] + with pytest.raises(pytest.skip.Exception, match="another collected family"): + test_e2e._resolve_unmatched(_request(["whisper-tiny-en"], items)) + + +def test_without_a_selector_every_case_is_listed_but_disabled(): + names, enabled = _select() + assert CONVERSATION in names and not enabled + + +@pytest.mark.parametrize("value", [True, "1e-3", None]) +def test_manifest_numbers_are_not_coerced(value): + with pytest.raises(TypeError, match="logit_tolerance"): + test_e2e._manifest_value({"logit_tolerance": value}, "logit_tolerance", (int, float)) + + +def test_manifest_values_of_their_own_type_pass(): + assert test_e2e._manifest_value({"logit_tolerance": 0.001}, "logit_tolerance", + (int, float)) == 0.001 + assert test_e2e._manifest_value({"tensor_parallel_size": 1}, "tensor_parallel_size", + (int,)) == 1 + with pytest.raises(TypeError): + test_e2e._manifest_value({"tensor_parallel_size": 1.0}, "tensor_parallel_size", (int,)) + with pytest.raises(TypeError): + test_e2e._manifest_value({"bundle": 3}, "bundle", (str,)) diff --git a/families/nemotron3_diarization/tests/test_model.py b/families/nemotron3_diarization/tests/test_model.py new file mode 100644 index 0000000000..00b3c4cc64 --- /dev/null +++ b/families/nemotron3_diarization/tests/test_model.py @@ -0,0 +1,302 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Geometry resolution, front-end constants and rotary tables, without TensorRT. + +The comparisons against librosa, torch and transformers run where those are +installed; the pinned literals next to them were measured from the same +originals, so the CPU lane keeps the checks without the dependencies. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import numpy as np +import pytest + +from families.nemotron3_diarization import config as config_module +from families.nemotron3_diarization import frontend, rotary + +DATA = Path(__file__).resolve().parent / "data" + +# The released checkpoint's config.json and processor_config.json, reduced to +# what the family reads. +CONFIG = { + "architectures": ["Nemotron3DiarizationForAudioFrameClassification"], + "model_type": "nemotron3_diarization", + "audio_config": { + "hidden_act": "gelu", "hidden_size": 512, "intermediate_size": 2048, + "max_position_embeddings": 5000, "num_attention_heads": 8, "num_hidden_layers": 31, + "num_key_value_heads": 8, "num_mel_bins": 128, "subsampling_factor": 8, + "rope_parameters": {"partial_rotary_factor": 1.0, "rope_theta": 10000.0, + "rope_type": "default"}, + }, + "head_config": {"audio_hidden_size": 512, "hidden_size": 192, "num_speakers": 8, + "subsampling_factor": 8}, + "streaming_config": { + "fifo_length": 264, "latest_frames_score_boost": 0.05, "min_positive_scores_rate": 0.5, + "num_speakers": 8, "prediction_score_threshold": 0.25, "speaker_cache_length": 264, + "speaker_cache_silence_frames_per_speaker": 1, "speaker_cache_update_period": 222, + "strong_boost_rate": 0.75, "subsampling_factor": 8, "weak_boost_rate": 1.5, + }, + "chunk_length": 340, "chunk_right_context": 40, "fifo_length": 40, + "speaker_cache_update_period": 300, +} +PROCESSOR = { + "feature_extractor": { + "feature_extractor_type": "NemotronAsrStreamingFeatureExtractor", "feature_size": 128, + "hop_length": 160, "n_fft": 512, "padding_value": 0.0, "preemphasis": 0.97, + "sampling_rate": 16000, "win_length": 400, + }, + "subsampling_factor": 8, +} + + +def _shapes(layers: int = 31) -> dict: + shapes = { + "model.audio_tower.embedder.projection.weight": (512, 1024), + "model.audio_tower.layers.0.mlp.fc1.weight": (2048, 512), + "model.proj.weight": (192, 512), + "model.upsampler.conv.weight": (1536, 192, 3), + "classifier.dense.weight": (192, 192), + "classifier.out_proj.weight": (8, 192), + "silence_embeds": (512,), + } + for index in range(layers): + shapes[f"model.audio_tower.layers.{index}.self_attn.q_proj.weight"] = (512, 512) + return shapes + + +def _write(directory: Path, config: dict, processor: dict) -> Path: + (directory / "config.json").write_text(json.dumps(config), encoding="utf-8") + (directory / "processor_config.json").write_text(json.dumps(processor), encoding="utf-8") + return directory + + +def test_resolve_reads_the_released_geometry(tmp_path): + cfg = config_module.resolve(_write(tmp_path, CONFIG, PROCESSOR), _shapes()) + assert (cfg["hidden_size"], cfg["num_heads"], cfg["head_dim"], cfg["num_layers"]) == ( + 512, 8, 64, 31) + assert (cfg["head_hidden_size"], cfg["num_speakers"], cfg["subsampling_factor"]) == (192, 8, 8) + # Offline mode uses the top-level FIFO sizes, not the streaming ones. + assert (cfg["chunk_length"], cfg["chunk_left_context"], cfg["chunk_right_context"]) == ( + 340, 0, 40) + assert (cfg["fifo_length"], cfg["speaker_cache_update_period"]) == (40, 300) + # 264 // 8 - 1 = 32 frames per speaker: half, three quarters and 1.5 of it. + assert (cfg["min_positive_scores"], cfg["strong_boosted_frames"], + cfg["weak_boosted_frames"]) == (16, 24, 48) + # Cache, FIFO, chunk and look-ahead: the longest step one engine call sees. + assert cfg["max_step_rows"] == 264 + 40 + 340 + 40 + assert (cfg["sample_rate"], cfg["n_fft"], cfg["win_length"], cfg["hop_length"]) == ( + 16000, 512, 400, 160) + assert cfg["log_guard"] == 2.0**-24 + + +def test_runtime_config_names_every_speaker(tmp_path): + cfg = config_module.resolve(_write(tmp_path, CONFIG, PROCESSOR), _shapes()) + runtime = config_module.runtime_config(cfg) + assert set(runtime) == set(config_module.RUNTIME_KEYS) | {"labels"} + assert runtime["labels"] == [f"speaker_{index}" for index in range(8)] + + +def _variant(path: tuple, value): + config, processor = copy.deepcopy(CONFIG), copy.deepcopy(PROCESSOR) + target = {"config": config, "processor": processor}[path[0]] + for key in path[1:-1]: + target = target[key] + target[path[-1]] = value + return config, processor + + +@pytest.mark.parametrize("path, value", [ + (("config", "audio_config", "rope_parameters", "partial_rotary_factor"), 0.5), + (("config", "audio_config", "rope_parameters", "rope_type"), "dynamic"), + (("config", "audio_config", "num_key_value_heads"), 4), + (("config", "audio_config", "hidden_act"), "relu"), + (("config", "head_config", "subsampling_factor"), 4), + (("config", "streaming_config", "speaker_cache_length"), 8), + (("config", "chunk_right_context"), 340), + (("processor", "feature_extractor", "mel_filters_dtype"), "bfloat16"), + (("processor", "feature_extractor", "n_fft"), 500), + # JSON numbers only: a boolean, a numeric string or an explicit null is + # refused even where its coerced value would be the supported one. + (("config", "audio_config", "rope_parameters", "partial_rotary_factor"), True), + (("config", "audio_config", "rope_parameters", "partial_rotary_factor"), "1.0"), + (("config", "audio_config", "rope_parameters", "partial_rotary_factor"), None), + (("processor", "feature_extractor", "padding_value"), False), + (("processor", "feature_extractor", "padding_value"), "0.0"), + (("processor", "feature_extractor", "padding_value"), None), + # Values the float32 engines and runtime cannot honor are refused before + # either engine is compiled. + (("config", "audio_config", "rope_parameters", "rope_theta"), 1e-50), + (("config", "audio_config", "rope_parameters", "rope_theta"), 1e40), + (("config", "speaker_cache_update_period"), 2**31), + (("config", "streaming_config", "prediction_score_threshold"), 0.0), + (("config", "streaming_config", "prediction_score_threshold"), -0.25), + (("config", "streaming_config", "prediction_score_threshold"), 1.0), + (("config", "streaming_config", "weak_boost_rate"), -1.5), + (("config", "streaming_config", "weak_boost_rate"), 1e300), + (("processor", "feature_extractor", "preemphasis"), 1e40), + (("processor", "feature_extractor", "preemphasis"), 1.5), + (("processor", "feature_extractor", "win_length"), 1), + # Bounds hold after rounding to float32: these pass in float64 only. + (("config", "streaming_config", "prediction_score_threshold"), 1e-50), + (("config", "streaming_config", "prediction_score_threshold"), 1 - 1e-9), + (("config", "audio_config", "rope_parameters", "rope_theta"), 1 + 1e-9), + (("config", "audio_config", "rope_parameters", "rope_theta"), 10**400), + # A boost budget past the cache length (32 * 10 = 320 > 264 frames). + (("config", "streaming_config", "weak_boost_rate"), 10.0), +]) +def test_resolve_refuses_what_the_graph_does_not_implement(tmp_path, path, value): + config, processor = _variant(path, value) + with pytest.raises(ValueError): + config_module.resolve(_write(tmp_path, config, processor), _shapes()) + + +def _released_headers(cfg: dict) -> dict: + return {name: ("F32", shape) for name, shape in config_module.expected_tensors(cfg).items()} + + +def test_expected_tensors_are_the_released_checkpoint(tmp_path): + cfg = config_module.resolve(_write(tmp_path, CONFIG, PROCESSOR), _shapes()) + expected = config_module.expected_tensors(cfg) + # The released model.safetensors holds 417 float32 tensors: 13 per encoder + # layer, the query, key and value projections without bias. + assert len(expected) == 417 + assert expected["model.audio_tower.layers.30.mlp.fc2.weight"] == (512, 2048) + assert expected["model.upsampler.conv.weight"] == (1536, 192, 3) + assert "model.audio_tower.layers.0.self_attn.q_proj.bias" not in expected + config_module.check_tensors(cfg, _released_headers(cfg)) + + +@pytest.mark.parametrize("damage", ["missing", "unexpected", "bfloat16", "later_layer_width"]) +def test_check_tensors_refuses_a_malformed_checkpoint(tmp_path, damage): + cfg = config_module.resolve(_write(tmp_path, CONFIG, PROCESSOR), _shapes()) + headers = _released_headers(cfg) + layer = "model.audio_tower.layers.20" + if damage == "missing": + del headers[f"{layer}.mlp.fc1.bias"] + elif damage == "unexpected": + headers["model.audio_tower.layers.0.self_attn.q_proj.bias"] = ("F32", (512,)) + elif damage == "bfloat16": + headers["classifier.dense.weight"] = ("BF16", (192, 192)) + else: + # A self-consistent layer whose MLP width contradicts the configuration. + headers[f"{layer}.mlp.fc1.weight"] = ("F32", (1024, 512)) + headers[f"{layer}.mlp.fc1.bias"] = ("F32", (1024,)) + headers[f"{layer}.mlp.fc2.weight"] = ("F32", (512, 1024)) + with pytest.raises(ValueError, match="checkpoint tensor"): + config_module.check_tensors(cfg, headers) + + +def test_resolve_refuses_an_odd_head_width(tmp_path): + config = copy.deepcopy(CONFIG) + config["audio_config"]["num_attention_heads"] = 512 + config["audio_config"]["num_key_value_heads"] = 512 + with pytest.raises(ValueError, match="even head width"): + config_module.resolve(_write(tmp_path, config, PROCESSOR), _shapes()) + + +def test_resolve_refuses_repeated_keys(tmp_path): + # json.loads keeps the last of repeated keys; the resolver refuses them at + # every level instead of validating whichever value came last. + directory = _write(tmp_path, CONFIG, PROCESSOR) + (directory / "config.json").write_text( + '{"chunk_length": 340, ' + json.dumps(CONFIG)[1:], encoding="utf-8") + with pytest.raises(ValueError, match="repeats the key 'chunk_length'"): + config_module.resolve(directory, _shapes()) + _write(tmp_path, CONFIG, PROCESSOR) + nested = json.dumps(PROCESSOR).replace('"feature_extractor": {', + '"feature_extractor": {"n_fft": 512, ') + (directory / "processor_config.json").write_text(nested, encoding="utf-8") + with pytest.raises(ValueError, match="repeats the key 'n_fft'"): + config_module.resolve(directory, _shapes()) + + +def test_resolve_checks_the_tensors(tmp_path): + directory = _write(tmp_path, CONFIG, PROCESSOR) + with pytest.raises(ValueError, match="encoder layer count"): + config_module.resolve(directory, _shapes(layers=30)) + shapes = _shapes() + shapes["model.upsampler.conv.weight"] = (1536, 192, 5) + with pytest.raises(ValueError, match="upsampler"): + config_module.resolve(directory, shapes) + (directory / "processor_config.json").unlink() + with pytest.raises(FileNotFoundError): + config_module.resolve(directory, _shapes()) + + +def test_mel_filters_are_slaney_triangles_over_the_whole_band(): + filters = frontend.mel_filters(128, 512, 16000) + assert filters.shape == (128, 257) and filters.dtype == np.float32 + # Measured from librosa.filters.mel(sr=16000, n_fft=512, n_mels=128, + # fmin=0, fmax=8000, norm="slaney"), which the values equal bit for bit. + assert float(filters.astype(np.float64).sum()) == pytest.approx(4.09048765, abs=1e-8) + assert np.nonzero(filters[0])[0].tolist() == [1] + assert np.nonzero(filters[127])[0].tolist() == list(range(244, 256)) + assert float(filters[10, 8]) == pytest.approx(0.029578963294625282, rel=1e-7) + librosa = pytest.importorskip("librosa") + reference = librosa.filters.mel(sr=16000, n_fft=512, n_mels=128, fmin=0.0, fmax=8000.0, + norm="slaney") + assert np.array_equal(filters, reference) + + +def test_window_is_the_symmetric_hann(): + window = frontend.symmetric_hann(400) + assert window.shape == (400,) and window.dtype == np.float32 + # Symmetric, not periodic: zero at both ends, the peak shared by 199 and 200. + assert window[0] == 0.0 and window[-1] == 0.0 + assert window[199] == window[200] == pytest.approx(0.9999845, abs=1e-7) + periodic = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(400) / 400) + assert np.abs(window - periodic).max() > 1e-3 + torch = pytest.importorskip("torch") + reference = torch.hann_window(400, periodic=False).numpy() + # float32 cosines from two libraries: within one unit in the last place. + assert np.abs(window - reference).max() <= 6e-8 + + +def test_shipped_test_constants_are_the_family_constants(): + # tests/cpp/test_runtime.cpp loads these files as the bundle would. + filters = np.fromfile(DATA / "mel_filters.f32", dtype=np.float32).reshape(128, 257) + window = np.fromfile(DATA / "window.f32", dtype=np.float32) + assert np.array_equal(filters, frontend.mel_filters(128, 512, 16000)) + assert np.array_equal(window, frontend.symmetric_hann(400)) + + +def test_rotary_tables_follow_the_reference_rounding(): + inverse = rotary.inverse_frequencies(64, 10000.0) + assert inverse.dtype == np.float32 and inverse[0] == 1.0 + assert float(inverse[1]) == 0.7498942017555237 + cos, sin = rotary.rotary_tables(64, 10000.0, 684) + assert cos.shape == sin.shape == (684, 64) + assert np.all(cos[0] == 1.0) and np.all(sin[0] == 0.0) + # rotate_half pairs dimension i with i + 32, so both halves share angles. + assert np.array_equal(cos[:, :32], cos[:, 32:]) and np.array_equal(sin[:, :32], sin[:, 32:]) + assert float(cos[683, 0]) == pytest.approx(-0.29208114743232727, abs=1e-7) + torch = pytest.importorskip("torch") + modeling = pytest.importorskip( + "transformers.models.nemotron3_diarization.modeling_nemotron3_diarization") + configuration = pytest.importorskip( + "transformers.models.nemotron3_diarization.configuration_nemotron3_diarization") + audio = configuration.Nemotron3DiarizationAudioConfig( + rope_parameters=CONFIG["audio_config"]["rope_parameters"]) + embedding = modeling.Nemotron3DiarizationRotaryEmbedding(audio) + # The inverse frequencies are the correctly rounded float32 values within one + # ulp. Torch builds evaluate the float32 power with different scalar or + # vector code, so the reference's own values move with the build: measured + # 0 ulp from these with torch 2.12, up to 2 ulp with torch 2.15. + exact = (1.0 / 10000.0 ** (np.arange(0, 64, 2) / 64.0)).astype(np.float32) + np.testing.assert_array_max_ulp(inverse, exact, maxulp=1) + reference_inverse = embedding.inv_freq.numpy() + np.testing.assert_array_max_ulp(inverse, reference_inverse, maxulp=2) + reference_cos, reference_sin = embedding(torch.zeros(1, 684, 512), torch.arange(684)[None]) + # With equal frequencies the tables differ by one rounding of cos and sin. + # Unequal ones can move a float32 angle near position 683 by one ulp of the + # angle (6.1e-5; the tables then differ by 3.0e-5 with torch 2.15). + bound = 6e-8 if np.array_equal(inverse, reference_inverse) else float( + np.spacing(np.float32(683.0))) + assert np.abs(cos - reference_cos[0].numpy()).max() <= bound + assert np.abs(sin - reference_sin[0].numpy()).max() <= bound diff --git a/families/nemotron3_diarization/tests/test_support.py b/families/nemotron3_diarization/tests/test_support.py new file mode 100644 index 0000000000..f0bb19ab86 --- /dev/null +++ b/families/nemotron3_diarization/tests/test_support.py @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Dependency-free semantic Task discovery for Nemotron 3 Diarization.""" + +from families.nemotron3_diarization.support import describe +from tensorrt_model_connect.model_support import ModelMetadata + + +def test_speaker_diarization_is_offered(): + support = describe(ModelMetadata(config={"model_type": "nemotron3_diarization"}, model_index={})) + assert support is not None + assert support.tasks == ("audio_to_timed_labels",) + assert support.default_task == "audio_to_timed_labels" + assert support.default_precision == "fp32" + + +def test_architecture_also_resolves(): + support = describe( + ModelMetadata( + config={"architectures": ["Nemotron3DiarizationForAudioFrameClassification"]}, + model_index={}, + ) + ) + assert support is not None + assert support.default_task == "audio_to_timed_labels" + + +def test_other_speech_models_are_not_claimed(): + # Sortformer's sibling checkpoints and the streaming ASR encoder share the + # NeMo lineage, not this head, chunking and speaker cache. + for model_type in ("nemotron_asr_streaming", "nemotron3_5_transcribe", "parakeet", "wav2vec2"): + assert describe(ModelMetadata(config={"model_type": model_type}, model_index={})) is None diff --git a/website/plugins/model-support-inventory/index.js b/website/plugins/model-support-inventory/index.js index 5c8071f213..d6095def0a 100644 --- a/website/plugins/model-support-inventory/index.js +++ b/website/plugins/model-support-inventory/index.js @@ -105,6 +105,7 @@ const TASKS = { speech_translation: ['Speech translation', 'Audio', null, 'transcribe'], audio_language_identification: ['Audio language identification', 'Audio', 'audio-classification', null], audio_to_class_scores: ['Audio to class scores', 'Audio', 'audio-classification', 'classify'], + audio_to_timed_labels: ['Audio to timed labels', 'Audio', 'voice-activity-detection', null], spectrogram_to_frame_features: ['Spectrogram frame features', 'Audio', null, null], speech_to_speech_response: ['Speech-to-speech response', 'Audio', 'audio-to-audio', 'speak'], batch_speech_transcription: ['Batch speech transcription', 'Audio', 'automatic-speech-recognition', 'transcribe-batch'],