-
Notifications
You must be signed in to change notification settings - Fork 10
Canary streamatt #34
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
azziko
wants to merge
13
commits into
hlt-mt:main
Choose a base branch
from
azziko:canary-streamatt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Canary streamatt #34
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
15b6a00
Add canary streamatt
azziko 4279681
Add audio history type flag to the base streamatt
azziko 53afb67
Add stylistic fixes addressing the linter
azziko b9ec9ba
Add minor fixes
azziko 056ec4e
Fix linter issues
azziko 39f1380
Add minor fixes
azziko 3f9a6eb
Delete removing eos in the beginning
azziko 6b23ddf
Add unit test for audio trimming in update history
azziko 52803f4
Change the canary dependency version
azziko cbc895e
Update simulstream/server/speech_processors/canary_streamatt.py
azziko 59bf6f3
Update uts/speech_processors/test_streamatt.py
azziko 076ed37
Fix linter
azziko a1fea18
Add minor fixes
azziko File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| type: "simulstream.server.speech_processors.canary_streamatt.CanaryStreamAtt" | ||
| model_name: "nvidia/canary-1b-v2" | ||
| text_history: | ||
| type: "simulstream.server.speech_processors.base_streamatt.FixedWordsTextHistory" | ||
| history_words: 10 | ||
| speech_chunk_size: 0.960 # seconds | ||
| detokenizer_type: "canary" | ||
| cross_attn_layer: -2 | ||
| cutoff_frame_num: 8 | ||
| num_beams: 5 | ||
| audio_subsampling_factor: 8 | ||
| audio_history_max_duration: 160 # Maximum length for the audio buffer, in seconds | ||
| mel_hop_samples: 160 # Number of audio samples between adjacent mel frames | ||
|
mgaido91 marked this conversation as resolved.
|
||
| text_history_max_len: 128 | ||
| word_level_postprocess: True # Disable if character-level language | ||
| use_raw_audio_history: True | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -52,7 +52,7 @@ hf = [ | |
|
|
||
| canary = [ | ||
| "Cython", | ||
| "nemo_toolkit[asr]==2.4.0", | ||
| "nemo_toolkit[asr]==2.8.0", | ||
| ] | ||
|
|
||
| vad = [ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
158 changes: 158 additions & 0 deletions
158
simulstream/server/speech_processors/canary_streamatt.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| # Copyright 2025 FBK | ||
|
|
||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
|
|
||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License | ||
|
|
||
| import torch | ||
| import numpy as np | ||
|
|
||
| from types import SimpleNamespace | ||
| from typing import List, Tuple | ||
|
|
||
| import copy | ||
|
|
||
| from simulstream.server.speech_processors import SAMPLE_RATE | ||
| from simulstream.server.speech_processors.base_streamatt import BaseStreamAtt | ||
|
|
||
| from nemo.collections.asr.models import ASRModel | ||
| from nemo.collections.asr.parts.submodules.multitask_decoding import ( | ||
| MultiTaskDecodingConfig, | ||
| ) | ||
| from nemo.collections.asr.models.aed_multitask_models import ( | ||
| MultiTaskTranscriptionConfig, | ||
| ) | ||
|
|
||
|
|
||
| class CanaryStreamAtt(BaseStreamAtt): | ||
| """ | ||
| StreamAtt policy implementation for NVIDIA's Canary-v2 model. | ||
|
|
||
| Args: | ||
| config (SimpleNamespace): Configuration object. | ||
|
azziko marked this conversation as resolved.
|
||
| Supported attributes: | ||
| - **audio_history_max_duration (int)**: Maximum audio history in seconds. | ||
| Defaults to ``30``. | ||
| - **num_beams (int)**: Number of beams to use for beam search decoding. | ||
| Defaults to ``5``. | ||
| """ | ||
|
|
||
| def __init__(self, config: SimpleNamespace): | ||
| super().__init__(config) | ||
| self._audio_history_max_duration = getattr(self.config, "audio_history_max_duration", 30) | ||
|
|
||
| expected_mel_hop_samples = ( | ||
| self.model.cfg.preprocessor.window_stride * self.model.cfg.preprocessor.sample_rate | ||
| ) | ||
|
|
||
| assert self.mel_hop_samples == expected_mel_hop_samples, ( | ||
| f"mel_hop_samples is set to {self.mel_hop_samples} in the config, but the loaded " | ||
| f"model's preprocessor uses {expected_mel_hop_samples} samples per mel frame" | ||
| ) | ||
|
|
||
| # Build the transcription config, which is reused for every transcribe() call. | ||
| self.transcription_cfg = MultiTaskTranscriptionConfig( | ||
| batch_size=1, | ||
| return_hypotheses=True, | ||
| enable_chunking=False, | ||
| verbose=False, | ||
| ) | ||
|
|
||
| @property | ||
| def audio_max_len(self) -> int: | ||
| """Maximum audio history length in raw waveform samples.""" | ||
| return self._audio_history_max_duration * SAMPLE_RATE | ||
|
|
||
| def set_source_language(self, language: str) -> None: | ||
| self.src_lang = language | ||
|
|
||
| def set_target_language(self, language: str) -> None: | ||
| self.tgt_lang = language | ||
|
|
||
| @classmethod | ||
| def load_model(cls, config: SimpleNamespace): | ||
| if not hasattr(cls, "model") or cls.model is None: | ||
| cls.model = ASRModel.from_pretrained(model_name=config.model_name) | ||
|
|
||
| # Configure decoding strategy | ||
| multitask_decoding = MultiTaskDecodingConfig() | ||
| multitask_decoding.strategy = "beam" | ||
| multitask_decoding.return_xattn_scores = True | ||
| multitask_decoding.beam.beam_size = getattr(config, "num_beams", 5) | ||
| cls.model.change_decoding_strategy(multitask_decoding) | ||
|
|
||
| cls.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | ||
| assert cls.model.cfg.preprocessor.sample_rate == SAMPLE_RATE | ||
| cls.model.to(cls.device) | ||
|
|
||
| def _build_transcription_config(self): | ||
| """ | ||
| Return a ``MultiTaskTranscriptionConfig`` whose prompt encodes the current source/target | ||
| languages, task, PNC preference, and forced decoder prefix. | ||
| """ | ||
|
|
||
| default_turns = self.model.prompt.get_default_dialog_slots() | ||
| default_slots = copy.deepcopy(default_turns[0]["slots"]) | ||
| default_slots["source_lang"] = self.src_lang | ||
| default_slots["target_lang"] = self.tgt_lang | ||
|
|
||
| turns = [ | ||
| { | ||
| "role": "user", "slots": default_slots | ||
| }, | ||
| { | ||
| "role": "user_prefix", | ||
| "slots": { | ||
| "prefix": self.model.tokenizer.tokens_to_text(self.text_history) | ||
|
mgaido91 marked this conversation as resolved.
|
||
| }, | ||
| }, | ||
| ] | ||
|
|
||
| cfg_copy = copy.deepcopy(self.transcription_cfg) | ||
| cfg_copy.prompt = turns | ||
|
|
||
| return cfg_copy | ||
|
|
||
| def _preprocess(self, waveform: np.ndarray) -> np.ndarray: | ||
| """ | ||
| Append the incoming waveform chunk to the raw audio history and return it. | ||
|
|
||
| Returns: | ||
| np.ndarray: Accumulated raw audio history. | ||
| """ | ||
| waveform = waveform.astype(np.float32) | ||
| if self.audio_history is None: | ||
| self.audio_history = waveform | ||
| else: | ||
| self.audio_history = np.concatenate( | ||
| [self.audio_history, waveform]) | ||
|
|
||
| return self.audio_history | ||
|
|
||
| def _generate(self, speech: np.ndarray) -> Tuple[List[str], torch.Tensor]: | ||
| override_config = self._build_transcription_config() | ||
|
|
||
| with torch.inference_mode(): | ||
| output = self.model.transcribe(audio=speech, override_config=override_config) | ||
|
|
||
| hypothesis = output[0] | ||
|
|
||
| token_ids = hypothesis.y_sequence.detach().cpu().tolist() | ||
| tokens = self.model.tokenizer.ids_to_tokens(token_ids) | ||
|
|
||
| xatt_raw = hypothesis.xatt_scores[self.cross_attn_layer] | ||
| xatt = xatt_raw.mean(dim=0).cpu() # we average over heads | ||
| xatt = self.normalize_attn(xatt) | ||
|
|
||
| return tokens, xatt | ||
|
|
||
| def tokens_to_string(self, tokens: List[str]) -> str: | ||
| return self.model.tokenizer.tokens_to_text(tokens) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.