NVIDIA-NeMo/Speech · #16556
Make tarred noise/RIR augmentation and Lhotse noise mixing resume exactly
docs/source/dataloaders.rst67 + / 0 −
@@ -1544,6 +1544,73 @@ Other, more exotic configurations: * With ``seed="randomized"``, the base random seed is set to Python's global RNG seed. It might be different on each GPU training process. This setting is not recommended. +Randomness inside datasets+^^^^^^^^^^^^^^^^^^^^^^^^^^++Per-example randomness in a dataset's ``__getitem__`` (random crops, context slicing, text augmentation, ...)+must not use the global ``random`` / ``np.random`` generators: their state is not part of the+``StatefulDataLoader`` checkpoint, so a resumed run would read the same cuts as the uninterrupted run but+transform them differently. Datasets inherit+``nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin`` and draw from ``self.rng`` instead::++ class MyDataset(StatefulRandomMixin, torch.utils.data.Dataset):+ def __getitem__(self, cuts):+ offsets = [self.rng.uniform(0, cut.duration) for cut in cuts]+ ...++This is opt-in: the dataloader builder enables it when ``use_stateful_dataloader=True``. Otherwise ``self.rng`` is+the global ``random`` module and the dataset draws exactly the same numbers as before. When enabled, the generator+is seeded per dataloading process from the dataloader seed and the data-parallel rank (the builder's+``global_rank``, so ranks differ whatever the worker start method), and its state is saved and+restored with the dataloader state: by ``StatefulDataLoader`` itself for map-style datasets, and by NeMo's+``StatefulIterableDatasetWrapper`` for iterable-style datasets. A wrapper placed around the dataset must forward+``state_dict()`` / ``load_state_dict()``, or the state is not saved (``FallbackDataset`` does). Across epochs: with+``num_workers=0`` or persistent workers, the same generator continues its sequence, so a cut gets new random draws+when it is read again. With non-persistent workers, each epoch starts new workers whose generators are seeded+from that epoch's worker seeds, so the draws still differ between epochs but don't continue the previous+sequence. Exact resume is guaranteed within an epoch.++Not covered yet: these datasets still draw from the global ``random`` / ``np.random`` / ``torch`` generators, so+they don't resume exactly even with ``use_stateful_dataloader=True``: ``LhotseAudioNoiseDataset``+(``nemo/collections/asr/data/ssl_dataset.py``) and the speechlm2 duplex datasets+(``nemo/collections/speechlm2/data/duplex_stt_dataset.py`` and ``duplex_ear_tts_dataset.py``).++Randomness inside components a dataset calls must come from the same generator. For example, with checkpointed+randomness enabled the TTS datasets pass ``self.rng`` to their tokenizers' G2P modules (``set_g2p_rng`` in+``nemo.collections.tts.parts.utils.tts_dataset_utils``), so ``phoneme_probability`` decisions are restored on resume+as well. Otherwise a G2P module draws from its own unseeded generator, as before.++Audio augmentation with an ``AudioAugmentor`` (``nemo.collections.asr.parts.preprocessing.perturb``) uses the global+``random`` module by default. A dataset assigns its generator with ``augmentor.rng = self.rng`` before calling+``augmentor.perturb(...)``. That generator is then used by every perturbation in the pipeline, including nested+ones, so augmentation is restored on resume as well. ``LhotseSpeechToTextBpeEOUDataset`` does this. This holds+for perturbations that draw from ``self.rng``, as all built-in ones do. A custom perturbation added with+``register_perturbation`` must also draw from ``self.rng``; one that draws from the global ``random`` /+``np.random`` keeps doing so and is not restored on resume.+With an injected generator, noise and RIR perturbations that read tarred audio (``audio_tar_filepaths``) choose+a manifest entry with that generator and read its file by random access, from its own source's tars. On the first+draw the manifest is checked against the tar members, and an entry that is not in the tars raises an error. They use the+``.idx`` next to each tar; a local tar without one gets a cached temporary index, and a remote tar must have its+``.idx`` (build it with ``scripts/dataloading/build_indexes.py``). The sequential tar reader is not used, because+its position is not checkpointed. Random access needs uncompressed tars (a ``.tar.gz`` raises an error), and with+``shard_strategy: scatter`` each rank samples only from the entries in its own shards.++Noise mixing with ``noise_path`` (``CutSet.mix``) keeps the noise input as configured (repetition, blend weights,+``max_open_streams``). Indexed noise with a length is sampled by index. Indexed noise without a length (repeated or+blended tarred/Shar noise), which used to fail on the first batch with an "infinite iterator" error, is mixed as a+stream; this bug fix applies with or without ``use_stateful_dataloader``. With ``use_stateful_dataloader=True``, the+noise shards are shuffled with the data's ``shard_seed`` unless ``noise_path`` sets its own, so with an integer+``shard_seed`` the mixed audio is reproducible and identical after a resume. Without it, the noise keeps its own+default ``shard_seed`` (``"trng"``), as before. ``rir_path`` reverb draws from+a generator that is saved with the sampler state, and it is restored exactly as well.++Random transforms applied to the ``CutSet`` itself (``.map(...)`` in a data type parser) can't keep a checkpointed+generator. They can seed a generator from the cut ID instead, e.g. ``random.Random(f"{seed}:{cut.id}")``, so the+result is a pure function of the cut, and a cut then gets the same draw in every epoch. The+``lhotse_magpietts_data_as_continuation`` parser does this for ``add_extra_end_silence`` when+``extra_end_silence_seed`` is set; set it for exact resume. Without it, the silence is drawn from the global+``random`` module as before and is not restored on resume.+ CP/TP-safe batches with ``BroadcastingDataLoader`` --------------------------------------------------- nemo/collections/asr/data/audio_to_eou_label_lhotse.py25 + / 8 −
@@ -28,6 +28,7 @@ from nemo.collections.asr.parts.preprocessing.segment import AudioSegment from nemo.collections.asr.parts.utils.eou_utils import EOB_STRING, EOU_STRING # noqa: F401 (re-exported) from nemo.collections.common.data.lhotse.audio_loading import LhotseAudioLoadingDatasetMixin+from nemo.collections.common.data.lhotse.stateful_rng import StatefulRandomMixin from nemo.collections.common.tokenizers.aggregate_tokenizer import TokenizerWrapper from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType@@ -73,7 +74,7 @@ class RandomPaddingConfig: post_pad_duration: float = 3.0 # amount of right-padding when pad_distribution='constant' -class LhotseSpeechToTextBpeEOUDataset(LhotseAudioLoadingDatasetMixin, torch.utils.data.Dataset):+class LhotseSpeechToTextBpeEOUDataset(StatefulRandomMixin, LhotseAudioLoadingDatasetMixin, torch.utils.data.Dataset): """ This dataset processes the audio data and the corresponding text data to generate the ASR labels, along with EOU labels for each frame. The audios used in this dataset should only contain speech with@@ -137,6 +138,9 @@ class LhotseSpeechToTextBpeEOUDataset(LhotseAudioLoadingDatasetMixin, torch.util 5) concatenate the pre-padding, audio, and post-padding to get the padded audio signal 6) update the EOU labels accordingly + Random draws are restored on resume with ``use_stateful_dataloader=True`` (see the dataloading docs).+ The ``augmentor`` perturbations draw from the same generator (see ``AudioAugmentor.rng``), including those+ that read tarred audio (``audio_tar_filepaths``), which then read their files by random access. """ @property@@ -423,7 +427,7 @@ def _random_pad_audio(self, audio: torch.Tensor, audio_len: torch.Tensor, eou_ta padded_eou_targets: torch.Tensor of padded EOU labels, shape [T+padding] padded_eou_targets_len: torch.Tensor of padded EOU label length, shape [1] """- p = np.random.rand()+ p = self.rng.random() if self.checkpointed_rng_enabled else np.random.rand() if self.padding_cfg is None or p > self.padding_cfg.prob: # don't apply padding eou_targets = self._repeat_eou_labels(eou_targets)@@ -454,9 +458,16 @@ def _random_pad_audio(self, audio: torch.Tensor, audio_len: torch.Tensor, eou_ta post_padding_duration = None if self.padding_cfg.pad_distribution == 'uniform':- total_padding_duration = np.random.uniform(min_padding_duration, max_padding_duration)+ if self.checkpointed_rng_enabled:+ total_padding_duration = self.rng.uniform(min_padding_duration, max_padding_duration)+ else:+ total_padding_duration = np.random.uniform(min_padding_duration, max_padding_duration) elif self.padding_cfg.pad_distribution == 'normal':- total_padding_duration = np.random.normal(self.padding_cfg.normal_mean, self.padding_cfg.normal_std)+ mean, std = self.padding_cfg.normal_mean, self.padding_cfg.normal_std+ if self.checkpointed_rng_enabled:+ total_padding_duration = self.rng.gauss(mean, std)+ else:+ total_padding_duration = np.random.normal(mean, std) total_padding_duration = max(min_padding_duration, min(max_padding_duration, total_padding_duration)) elif self.padding_cfg.pad_distribution == 'constant': pass@@ -470,9 +481,12 @@ def _random_pad_audio(self, audio: torch.Tensor, audio_len: torch.Tensor, eou_ta pre_padding_duration = total_padding_duration / 2 post_padding_duration = total_padding_duration / 2 else:- post_padding_duration = np.random.uniform(- self.padding_cfg.min_post_pad_duration, total_padding_duration - self.padding_cfg.min_pre_pad_duration- )+ low = self.padding_cfg.min_post_pad_duration+ high = total_padding_duration - self.padding_cfg.min_pre_pad_duration+ if self.checkpointed_rng_enabled:+ post_padding_duration = self.rng.uniform(low, high)+ else:+ post_padding_duration = np.random.uniform(low, high) pre_padding_duration = total_padding_duration - post_padding_duration if self.padding_cfg.max_pad_duration is not None:@@ -517,7 +531,10 @@ def _maybe_augment_audio(self, audio: torch.Tensor, audio_len: torch.Tensor): offset=0, duration=audio_len.item() / self.sample_rate, )- # Apply augmentation+ # Apply augmentation with the dataset generator (checkpointed when enabled, else the global generators).+ # Assign only when it changed: the assignment walks the perturbations to reach nested ones.+ if self.augmentor.rng is not self.rng:+ self.augmentor.rng = self.rng self.augmentor.perturb(audio_segment) audio = torch.from_numpy(audio_segment.samples).float() audio_len = audio.size(0)nemo/collections/asr/data/audio_to_text.py1 + / 49 −
@@ -20,7 +20,6 @@ from collections.abc import Iterable as IterableABC from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union -import braceexpand import numpy as np import torch from torch.utils.data import ChainDataset@@ -29,6 +28,7 @@ from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType from nemo.collections.asr.parts.preprocessing.segment import available_formats as valid_sf_formats+from nemo.collections.asr.parts.utils.tarred_shards import expand_sharded_filepaths # noqa: F401 (re-export) from nemo.collections.common import tokenizers from nemo.collections.common.parts.preprocessing import collections, parsers from nemo.core.classes import Dataset, IterableDataset@@ -181,54 +181,6 @@ def process_text_by_sample(self, sample: collections.ASRAudioText.OUTPUT_TYPE) - return t, tl -def expand_sharded_filepaths(sharded_filepaths, shard_strategy: str, world_size: int, global_rank: int):- valid_shard_strategies = ['scatter', 'replicate']- if shard_strategy not in valid_shard_strategies:- raise ValueError(f"`shard_strategy` must be one of {valid_shard_strategies}")-- if isinstance(sharded_filepaths, str):- # Replace '(' and '[' with '{'- brace_keys_open = ['(', '[', '<', '_OP_']- for bkey in brace_keys_open:- if bkey in sharded_filepaths:- sharded_filepaths = sharded_filepaths.replace(bkey, "{")-- # Replace ')' and ']' with '}'- brace_keys_close = [')', ']', '>', '_CL_']- for bkey in brace_keys_close:- if bkey in sharded_filepaths:- sharded_filepaths = sharded_filepaths.replace(bkey, "}")-- if isinstance(sharded_filepaths, str):- # Brace expand, set escape=False for Windows compatibility- sharded_filepaths = list(braceexpand.braceexpand(sharded_filepaths, escape=False))-- # Check for distributed and partition shards accordingly- if world_size > 1:- if shard_strategy == 'scatter':- logging.info("All tarred dataset shards will be scattered evenly across all nodes.")-- if len(sharded_filepaths) % world_size != 0:- logging.warning(- f"Number of shards in tarred dataset ({len(sharded_filepaths)}) is not divisible "- f"by number of distributed workers ({world_size})."- )-- begin_idx = (len(sharded_filepaths) // world_size) * global_rank- end_idx = begin_idx + len(sharded_filepaths) // world_size- sharded_filepaths = sharded_filepaths[begin_idx:end_idx]- logging.info(- "Partitioning tarred dataset: process (%d) taking shards [%d, %d)", global_rank, begin_idx, end_idx- )-- elif shard_strategy == 'replicate':- logging.info("All tarred dataset shards will be replicated across all nodes.")- else:- raise ValueError(f"Invalid shard strategy ! Allowed values are : {valid_shard_strategies}")-- return sharded_filepaths-- def cache_datastore_manifests( manifest_filepaths: Union[str, List[str]], cache_audio: bool = False,nemo/collections/asr/data/audio_to_text_lhotse_prompt_index.py9 + / 4 −
@@ -18,7 +18,6 @@ The model creates the prompt tensor using the actual encoded length. """ -import random from typing import Dict, Optional, Tuple import torch@@ -28,13 +27,16 @@ from nemo.collections.asr.parts.utils.prompt_language_utils import AUTO_PROMPT_LANGUAGE, resolve_prompt_index from nemo.collections.common.data.lhotse.audio_loading import LhotseAudioLoadingDatasetMixin+from nemo.collections.common.data.lhotse.stateful_rng import StatefulRandomMixin from nemo.collections.common.tokenizers.aggregate_tokenizer import TokenizerWrapper from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType from nemo.utils import logging -class LhotseSpeechToTextBpeDatasetWithPromptIndex(LhotseAudioLoadingDatasetMixin, torch.utils.data.Dataset):+class LhotseSpeechToTextBpeDatasetWithPromptIndex(+ StatefulRandomMixin, LhotseAudioLoadingDatasetMixin, torch.utils.data.Dataset+): """ Simplified dataset class for speech-to-text with prompt support. @@ -48,6 +50,9 @@ class LhotseSpeechToTextBpeDatasetWithPromptIndex(LhotseAudioLoadingDatasetMixin transcripts: Token IDs [B, T] transcript_length: Token lengths [B] language_prompt_indices: Language ID indices [B] (NOT full tensors)++ In "unified" prompt mode the auto prompt is drawn at random.+ Random draws are restored on resume with ``use_stateful_dataloader=True`` (see the dataloading docs). """ @property@@ -136,12 +141,12 @@ def _get_prompt_index_for_cut(self, cut) -> int: elif mode == 'auto': return self.auto_index elif mode == 'unified':- if random.random() < self.unified_auto_ratio:+ if self.rng.random() < self.unified_auto_ratio: return self.auto_index return self._get_language_index(cut) else: logging.warning(f"Unknown prompt_mode '{mode}', falling back to unified")- if random.random() < self.unified_auto_ratio:+ if self.rng.random() < self.unified_auto_ratio: return self.auto_index return self._get_language_index(cut) nemo/collections/asr/data/audio_to_text_lhotse_speaker.py6 + / 3 −
@@ -13,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import random from typing import Dict, Optional, Tuple import torch.utils.data@@ -23,18 +22,22 @@ from nemo.collections.asr.data.audio_to_text_lhotse import TokenizerWrapper from nemo.collections.asr.parts.utils.asr_multispeaker_utils import speaker_to_target from nemo.collections.common.data.lhotse.audio_loading import LhotseAudioLoadingDatasetMixin+from nemo.collections.common.data.lhotse.stateful_rng import StatefulRandomMixin from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType -class LhotseSpeechToTextSpkBpeDataset(LhotseAudioLoadingDatasetMixin, torch.utils.data.Dataset):+class LhotseSpeechToTextSpkBpeDataset(StatefulRandomMixin, LhotseAudioLoadingDatasetMixin, torch.utils.data.Dataset): """ This dataset is based on BPE datasets from audio_to_text.py. It has the same functionality of LhotseSpeechToTextBpeDataset but also yield speaker target tensor. Unlike native NeMo datasets, Lhotse dataset defines only the mapping from a CutSet (meta-data) to a mini-batch with PyTorch tensors. Specifically, it performs tokenization, I/O, augmentation, and feature extraction (if any). Managing data, sampling, de-duplication across workers/nodes etc. is all handled by Lhotse samplers instead.++ The target speaker of each cut is drawn at random.+ Random draws are restored on resume with ``use_stateful_dataloader=True`` (see the dataloading docs). """ @property@@ -81,7 +84,7 @@ def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]: ) speaker_targets = speaker_targets.transpose(0, 1)[: len(texts)] - target_speaker_id = random.choice(range(len(texts)))+ target_speaker_id = self.rng.choice(range(len(texts))) non_target_speaker_ids = [i for i in range(len(texts)) if i != target_speaker_id] text = texts[target_speaker_id] speaker_target = speaker_targets[target_speaker_id]nemo/collections/asr/parts/preprocessing/perturb.py337 + / 35 −
@@ -34,12 +34,15 @@ # SOFTWARE. # This file contains code artifacts adapted from https://github.com/ryanleary/patter import copy+import hashlib import inspect import io import os import random import subprocess+import tempfile from tempfile import NamedTemporaryFile+from types import ModuleType from typing import List, Optional, Union import librosa@@ -48,6 +51,7 @@ from scipy import signal from nemo.collections.asr.parts.preprocessing.segment import AudioSegment+from nemo.collections.asr.parts.utils.tarred_shards import expand_sharded_filepaths from nemo.collections.common.parts.preprocessing import collections, parsers from nemo.core.classes import IterableDataset from nemo.utils import logging@@ -73,7 +77,17 @@ HAVE_NUMBA = False -def read_one_audiosegment(manifest, target_sr, tarred_audio=False, audio_dataset=None):+def read_one_audiosegment(+ manifest, target_sr, tarred_audio=False, audio_dataset=None, rng=random, tar_random_access=None+):+ if tarred_audio and rng is not random:+ # A generator was injected (e.g. a dataset's checkpointed generator): choose the file by index with it and+ # read it by random access, so that the choice is reproduced exactly after a resume. The sequential tar+ # iterator below has a position that is not checkpointed.+ if tar_random_access is None:+ raise ValueError("Tarred audio with an injected generator requires random access to the tar files.")+ # Only entries checked against the tars are drawn, so a missing file fails on the first draw.+ return tar_random_access.load(rng.sample(tar_random_access.entries(manifest), 1)[0], target_sr) if tarred_audio: if audio_dataset is None: raise TypeError("Expected augmentation dataset but got None")@@ -83,7 +97,7 @@ def read_one_audiosegment(manifest, target_sr, tarred_audio=False, audio_dataset duration = 0 if manifest_entry.duration is None else manifest_entry.duration else:- audio_record = random.sample(manifest.data, 1)[0]+ audio_record = rng.sample(manifest.data, 1)[0] audio_file = audio_record.audio_file offset = 0 if audio_record.offset is None else audio_record.offset duration = 0 if audio_record.duration is None else audio_record.duration@@ -92,6 +106,26 @@ def read_one_audiosegment(manifest, target_sr, tarred_audio=False, audio_dataset class Perturbation(object):+ @property+ def rng(self) -> Union[random.Random, ModuleType]:+ """+ Random generator used by :meth:`perturb`.++ Defaults to the global ``random`` module, as before. A dataset that owns a checkpointed generator+ (see :class:`~nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin`) assigns it here,+ usually through :attr:`AudioAugmentor.rng`, so that augmentation draws are restored on resume.+ Assigning a generator also assigns it to nested perturbations (e.g. the noise perturbers of+ :class:`RirAndNoisePerturbation`).+ """+ return self.__dict__.get("_injected_rng", random)++ @rng.setter+ def rng(self, value: Union[random.Random, ModuleType]) -> None:+ _store_injected_rng(self, value)+ for perturbation in _nested_perturbations(vars(self).values()):+ if perturbation is not self:+ perturbation.rng = value+ def max_augmentation_length(self, length): return length @@ -154,9 +188,9 @@ def max_augmentation_length(self, length): def perturb(self, data): # Select speed rate either from choice or random sample if self._num_rates < 0:- speed_rate = random.uniform(self._min_rate, self._max_rate)+ speed_rate = self.rng.uniform(self._min_rate, self._max_rate) else:- speed_rate = random.choice(self._rates)+ speed_rate = self.rng.choice(self._rates) # Skip perturbation in case of identity speed rate if speed_rate == 1.0:@@ -236,9 +270,9 @@ def max_augmentation_length(self, length): def perturb(self, data): # Select speed rate either from choice or random sample if self._num_rates < 0:- speed_rate = random.uniform(self._min_rate, self._max_rate)+ speed_rate = self.rng.uniform(self._min_rate, self._max_rate) else:- speed_rate = random.choice(self._rates)+ speed_rate = self.rng.choice(self._rates) # Skip perturbation in case of identity speed rate if speed_rate == 1.0:@@ -312,8 +346,8 @@ def __init__( self._value = value def perturb(self, data):- start_silence_len = random.uniform(self._min_start_silence_secs, self._max_start_silence_secs)- end_silence_len = random.uniform(self._min_end_silence_secs, self._max_end_silence_secs)+ start_silence_len = self.rng.uniform(self._min_start_silence_secs, self._max_start_silence_secs)+ end_silence_len = self.rng.uniform(self._min_end_silence_secs, self._max_end_silence_secs) start = np.full((int(start_silence_len * data.sample_rate),), self._value) end = np.full((int(end_silence_len * data.sample_rate),), self._value) @@ -336,7 +370,7 @@ def __init__(self, min_gain_dbfs=-10, max_gain_dbfs=10, rng=None): random.seed(rng) if rng else None def perturb(self, data):- gain = random.uniform(self._min_gain_dbfs, self._max_gain_dbfs)+ gain = self.rng.uniform(self._min_gain_dbfs, self._max_gain_dbfs) data._samples = data._samples * (10.0 ** (gain / 20.0)) @@ -369,10 +403,13 @@ def __init__( self._shift_impulse = shift_impulse self._data_iterator = None + self._tar_random_access = None+ if audio_tar_filepaths: self._tarred_audio = True self._audiodataset = AugmentationDataset(manifest_path, audio_tar_filepaths, shuffle_n) self._data_iterator = iter(self._audiodataset)+ self._tar_random_access = _TarredAudioRandomAccess(audio_tar_filepaths) self._rng = rng random.seed(self._rng) if rng else None@@ -383,6 +420,8 @@ def perturb(self, data): data.sample_rate, tarred_audio=self._tarred_audio, audio_dataset=self._data_iterator,+ rng=self.rng,+ tar_random_access=self._tar_random_access, ) # normalize if necessary@@ -438,7 +477,7 @@ def __init__(self, min_shift_ms=-5.0, max_shift_ms=5.0, rng=None): random.seed(rng) if rng else None def perturb(self, data):- shift_ms = random.uniform(self._min_shift_ms, self._max_shift_ms)+ shift_ms = self.rng.uniform(self._min_shift_ms, self._max_shift_ms) max_shift_ms = data.duration * 1000 if abs(shift_ms) > max_shift_ms: shift_ms = max(-max_shift_ms, min(shift_ms, max_shift_ms))@@ -486,10 +525,13 @@ def __init__( self._orig_sr = orig_sr self._data_iterator = None + self._tar_random_access = None+ if audio_tar_filepaths: self._tarred_audio = True self._audiodataset = AugmentationDataset(manifest_path, audio_tar_filepaths, shuffle_n) self._data_iterator = iter(self._audiodataset)+ self._tar_random_access = _TarredAudioRandomAccess(audio_tar_filepaths) random.seed(rng) if rng else None self._rng = rng@@ -504,7 +546,12 @@ def orig_sr(self): def get_one_noise_sample(self, target_sr): return read_one_audiosegment(- self._manifest, target_sr, tarred_audio=self._tarred_audio, audio_dataset=self._data_iterator+ self._manifest,+ target_sr,+ tarred_audio=self._tarred_audio,+ audio_dataset=self._data_iterator,+ rng=self.rng,+ tar_random_access=self._tar_random_access, ) def perturb(self, data, ref_mic=0):@@ -518,6 +565,8 @@ def perturb(self, data, ref_mic=0): data.sample_rate, tarred_audio=self._tarred_audio, audio_dataset=self._data_iterator,+ rng=self.rng,+ tar_random_access=self._tar_random_access, ) self.perturb_with_input_noise(data, noise, ref_mic=ref_mic) @@ -539,7 +588,7 @@ def perturb_with_input_noise(self, data, noise, data_rms=None, ref_mic=0): f" reference mic ID must be an integer in [0, {data.num_channels}), got {ref_mic} instead." ) - snr_db = random.uniform(self._min_snr_db, self._max_snr_db)+ snr_db = self.rng.uniform(self._min_snr_db, self._max_snr_db) if data.is_empty(): logging.warning(@@ -568,15 +617,15 @@ def perturb_with_input_noise(self, data, noise, data_rms=None, ref_mic=0): noise_gain_db = min(noise_gain_db, self._max_gain_db) # calculate noise segment to use- start_time = random.uniform(0.0, noise.duration - data.duration)+ start_time = self.rng.uniform(0.0, noise.duration - data.duration) if noise.duration > (start_time + data.duration): noise.subsegment(start_time=start_time, end_time=start_time + data.duration) # adjust gain for snr purposes and superimpose noise.gain_db(noise_gain_db) if noise._samples.shape[0] < data._samples.shape[0]:- noise_idx = random.randint(0, data._samples.shape[0] - noise._samples.shape[0])+ noise_idx = self.rng.randint(0, data._samples.shape[0] - noise._samples.shape[0]) data._samples[noise_idx : noise_idx + noise._samples.shape[0]] += noise._samples else:@@ -602,7 +651,7 @@ def perturb_with_foreground_noise(self, data, noise, data_rms=None, max_noise_du f" reference mic ID must be an integer in [0, {data.num_channels}), got {ref_mic} instead." ) - snr_db = random.uniform(self._min_snr_db, self._max_snr_db)+ snr_db = self.rng.uniform(self._min_snr_db, self._max_snr_db) if not data_rms: data_rms = data.rms_db @@ -612,11 +661,11 @@ def perturb_with_foreground_noise(self, data, noise, data_rms=None, max_noise_du noise_gain_db = data_rms - noise.rms_db - snr_db noise_gain_db = min(noise_gain_db, self._max_gain_db) - n_additions = random.randint(1, max_additions)+ n_additions = self.rng.randint(1, max_additions) for i in range(n_additions):- noise_dur = random.uniform(0.0, max_noise_dur)- start_time = random.uniform(0.0, noise.duration)+ noise_dur = self.rng.uniform(0.0, max_noise_dur)+ start_time = self.rng.uniform(0.0, noise.duration) start_sample = int(round(start_time * noise.sample_rate)) end_sample = int(round(min(noise.duration, (start_time + noise_dur)) * noise.sample_rate)) noise_samples = np.copy(noise._samples[start_sample:end_sample])@@ -626,7 +675,7 @@ def perturb_with_foreground_noise(self, data, noise, data_rms=None, max_noise_du if noise_samples.shape[0] > data._samples.shape[0]: noise_samples = noise_samples[0 : data._samples.shape[0]] - noise_idx = random.randint(0, data._samples.shape[0] - noise_samples.shape[0])+ noise_idx = self.rng.randint(0, data._samples.shape[0] - noise_samples.shape[0]) data._samples[noise_idx : noise_idx + noise_samples.shape[0]] += noise_samples @@ -673,6 +722,12 @@ def __init__( self._tarred_audio = False self._orig_sr = orig_sr self._data_iterator = None+ # (source index, manifest entry) for the entries of every tarred source that this rank reads; built+ # lazily on the first draw with an injected generator, see read_one_audiosegment().+ self._tar_entries = None+ self._tar_manifests = []+ self._tar_random_access = []+ self._tar_partitioned = shard_strategy == "scatter" and world_size > 1 random.seed(rng) if rng else None self._rng = rng@@ -683,6 +738,7 @@ def __init__( manifest_path = [manifest_path] if isinstance(audio_tar_filepaths, str): audio_tar_filepaths = [audio_tar_filepaths]+ datasets = [] for tarred_audio_filepath, manifest_filepath in zip(audio_tar_filepaths, manifest_path): dataset = AugmentationDataset(@@ -694,6 +750,16 @@ def __init__( shard_strategy=shard_strategy, ) datasets.append(dataset)+ # Each source keeps its own file-id namespace: its manifest entries are read from its own tars,+ # restricted to this rank's shards under the 'scatter' strategy.+ rank_tar_filepaths = expand_sharded_filepaths(+ tarred_audio_filepath,+ shard_strategy=shard_strategy,+ world_size=world_size,+ global_rank=global_rank,+ )+ self._tar_random_access.append(_TarredAudioRandomAccess(rank_tar_filepaths))+ self._tar_manifests.append(dataset._manifest) self._audiodataset = RandomizedChainDataset( datasets, rnd_seed=(rng if rng else random.randint(0, 30000)) + global_rank )@@ -714,6 +780,11 @@ def orig_sr(self): return self._orig_sr def read_one_audiosegment(self, target_sr):+ if self._tarred_audio and self.rng is not random:+ # See the module-level read_one_audiosegment(): random access keeps the choice resumable. Entries are+ # drawn uniformly over all sources' manifest entries and read from their own source's tars.+ source_idx, entry = self.rng.sample(self._rank_tar_entries(), 1)[0]+ return self._tar_random_access[source_idx].load(entry, target_sr) if self._tarred_audio: if self._data_iterator is None: raise TypeError("Expected valid iterator but got None")@@ -727,13 +798,28 @@ def read_one_audiosegment(self, target_sr): duration = 0 if manifest_entry.duration is None else manifest_entry.duration else:- audio_record = random.sample(self._manifest.data, 1)[0]+ audio_record = self.rng.sample(self._manifest.data, 1)[0] audio_file = audio_record.audio_file offset = 0 if audio_record.offset is None else audio_record.offset duration = 0 if audio_record.duration is None else audio_record.duration return AudioSegment.from_file(audio_file, target_sr=target_sr, offset=offset, duration=duration) + def _rank_tar_entries(self) -> list:+ """+ ``(source index, manifest entry)`` pairs that this rank can read: with the 'scatter' strategy, the entries+ stored in this rank's shards; otherwise every manifest entry, each of which must be in the source's tars.+ """+ if self._tar_entries is None:+ entries = []+ for source_idx, (manifest, access) in enumerate(zip(self._tar_manifests, self._tar_random_access)):+ present = access.entries(manifest, require_all=not self._tar_partitioned)+ entries.extend((source_idx, entry) for entry in present)+ if not entries:+ raise ValueError("None of the noise manifest entries are in this rank's tar shards.")+ self._tar_entries = entries+ return self._tar_entries+ def perturb(self, data, ref_mic=0): """ Args:@@ -823,9 +909,9 @@ def perturb_with_input_noise(self, data, noise, data_rms=None, ref_mic=0, norm_t ) if self._snr_samples:- snr_db = random.sample(self._snr_samples, 1)[0]+ snr_db = self.rng.sample(self._snr_samples, 1)[0] else:- snr_db = random.uniform(self._min_snr_db, self._max_snr_db)+ snr_db = self.rng.uniform(self._min_snr_db, self._max_snr_db) if data_rms is None: data_rms = data.rms_db[ref_mic] if isinstance(data.rms_db, (list, np.ndarray)) else data.rms_db @@ -863,8 +949,14 @@ def __init__(self, min_level=-90, max_level=-46, rng=None): np.random.seed(rng) if rng else None def perturb(self, data):- noise_level_db = np.random.randint(self.min_level, self.max_level, dtype='int32')- noise_signal = np.random.randn(data._samples.shape[0]) * (10.0 ** (noise_level_db / 20.0))+ if self.rng is random:+ noise_level_db = np.random.randint(self.min_level, self.max_level, dtype='int32')+ noise_signal = np.random.randn(data._samples.shape[0]) * (10.0 ** (noise_level_db / 20.0))+ else:+ # Draw from the injected generator; numpy is seeded from it so the noise is reproducible too.+ noise_level_db = self.rng.randrange(self.min_level, self.max_level)+ noise_rng = np.random.default_rng(self.rng.getrandbits(64))+ noise_signal = noise_rng.standard_normal(data._samples.shape[0]) * (10.0 ** (noise_level_db / 20.0)) data._samples += noise_signal @@ -970,14 +1062,14 @@ def __init__( self._apply_noise_rir = apply_noise_rir def perturb(self, data):- prob = random.uniform(0.0, 1.0)+ prob = self.rng.uniform(0.0, 1.0) if prob < self._rir_prob: self._rir_perturber.perturb(data) data_rms = data.rms_db - if self._fg_noise_perturbers is not None and random.uniform(0.0, 1.0) < self._noise_prob:+ if self._fg_noise_perturbers is not None and self.rng.uniform(0.0, 1.0) < self._noise_prob: orig_sr = data.orig_sr if orig_sr not in self._fg_noise_perturbers: orig_sr = max(self._fg_noise_perturbers.keys())@@ -989,7 +1081,7 @@ def perturb(self, data): data, noise, data_rms=data_rms, max_noise_dur=self._max_duration, max_additions=self._max_additions ) - if self._bg_noise_perturbers is not None and random.uniform(0.0, 1.0) < self._bg_noise_prob:+ if self._bg_noise_perturbers is not None and self.rng.uniform(0.0, 1.0) < self._bg_noise_prob: orig_sr = data.orig_sr if orig_sr not in self._bg_noise_perturbers: orig_sr = max(self._bg_noise_perturbers.keys())@@ -1030,19 +1122,19 @@ def perturb(self, data): orig_f = NamedTemporaryFile(suffix=".wav") sf.write(orig_f.name, norm_samples.transpose(), 16000) - codec_ind = random.randint(0, len(self._codecs) - 1)+ codec_ind = self.rng.randint(0, len(self._codecs) - 1) if self._codecs[codec_ind] == "amr-nb": transcoded_f = NamedTemporaryFile(suffix="_amr.wav") rates = list(range(0, 4))- rate = rates[random.randint(0, len(rates) - 1)]+ rate = rates[self.rng.randint(0, len(rates) - 1)] _ = subprocess.check_output( f"sox {orig_f.name} -V0 -C {rate} -t amr-nb - | sox -t amr-nb - -V0 -b 16 -r 16000 {transcoded_f.name}", shell=True, ) elif self._codecs[codec_ind] == "ogg": transcoded_f = NamedTemporaryFile(suffix="_ogg.wav") rates = list(range(-1, 8))- rate = rates[random.randint(0, len(rates) - 1)]+ rate = rates[self.rng.randint(0, len(rates) - 1)] _ = subprocess.check_output( f"sox {orig_f.name} -V0 -C {rate} -t ogg - | sox -t ogg - -V0 -b 16 -r 16000 {transcoded_f.name}", shell=True,@@ -1099,7 +1191,7 @@ def perturb(self, data: AudioSegment): pad_size = self._duration_sec * data.sample_rate - data.num_samples data.pad(pad_size=pad_size) else:- start_time = random.uniform(0.0, data.duration - self._duration_sec)+ start_time = self.rng.uniform(0.0, data.duration - self._duration_sec) end_time = start_time + self._duration_sec new_data = copy.deepcopy(data)@@ -1108,7 +1200,7 @@ def perturb(self, data: AudioSegment): rms_db = new_data.rms_db if new_data.num_channels == 1 else min(new_data.rms_db) trial = 0 while rms_db < self._min_rms_db and trial < self._max_trials:- start_time = random.uniform(0.0, data.duration - self._duration_sec)+ start_time = self.rng.uniform(0.0, data.duration - self._duration_sec) end_time = start_time + self._duration_sec new_data = copy.deepcopy(data) new_data.subsegment(start_time=start_time, end_time=end_time)@@ -1151,9 +1243,27 @@ def __init__(self, perturbations=None, rng=None): random.seed(rng) if rng else None self._pipeline = perturbations if perturbations is not None else [] + @property+ def rng(self) -> Union[random.Random, ModuleType]:+ """+ Random generator used to decide which perturbations to apply and by the perturbations themselves.++ Defaults to the global ``random`` module, as before. Assigning a generator (e.g. the checkpointed+ ``self.rng`` of a :class:`~nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin` dataset)+ assigns it to every perturbation in the pipeline, so all augmentation draws come from it and are restored+ on resume together with the dataset state.+ """+ return self.__dict__.get("_injected_rng", random)++ @rng.setter+ def rng(self, value: Union[random.Random, ModuleType]) -> None:+ _store_injected_rng(self, value)+ for perturbation in _nested_perturbations(p for _, p in self._pipeline):+ perturbation.rng = value+ def perturb(self, segment): for prob, p in self._pipeline:- if random.random() < prob:+ if self.rng.random() < prob: p.perturb(segment) return @@ -1242,6 +1352,9 @@ class CustomPerturbation(perturb.Perturbation): ... perturb.register_perturbation(name_of_perturbation, CustomPerturbation) ```+ A custom perturbation should draw its random numbers from ``self.rng`` (not from the global ``random`` /+ ``np.random``). A dataset can then assign a checkpointed generator to the augmentor, and the perturbation's+ draws are restored on resume together with the dataset state. Args: augmenter: AudioAugmentor object or dictionary of str -> kwargs (dict) which is parsed and used@@ -1301,6 +1414,115 @@ class CustomPerturbation(perturb.Perturbation): return augmenter +class _TarredAudioRandomAccess:+ """+ Random access to the audio files of tarred noise or RIR data (NeMo tarred format: one member per audio file),+ keyed by the manifest entry's file id.++ Perturbations use it instead of the sequential tar iterator when a generator is injected (see+ :attr:`Perturbation.rng`): the file is chosen by index with that generator, so the choice is reproduced exactly+ after resuming from the generator's saved state. Members are read with NeMo's indexed tar reader. A tar without+ a ``.idx`` file next to it is indexed once into a cached temporary file (local tars only; build indexes for+ remote tars with ``scripts/dataloading/build_indexes.py``).++ One instance serves one source: one manifest and its tar files. :meth:`entries` checks the manifest against+ the tar members once, so that an entry missing from the tars raises ``ValueError`` on first use rather than+ when it happens to be drawn. File ids must be unique within the tar files of one instance: every regular member+ of every indexed range is checked, and a duplicate member name or file id raises ``ValueError``. Compressed+ archives (e.g. ``.tar.gz``) can't be read by random access and raise ``ValueError``; use uncompressed tars for+ resumable augmentation. Readers are closed after each use, so the number of tar files is not limited by the+ open-file limit.++ Args:+ tar_filepaths: Tar file paths of one source, in any format accepted by ``AugmentationDataset``+ (brace-expandable string or list).+ """++ def __init__(self, tar_filepaths: Union[str, List[str]]):+ self._tar_filepaths = tar_filepaths+ self._locations = None+ self._entries = None++ @property+ def tar_filepaths(self) -> Union[str, List[str]]:+ return self._tar_filepaths++ def contains(self, manifest_entry) -> bool:+ """Whether the audio of ``manifest_entry`` is in these tar files."""+ return _file_id(manifest_entry.audio_file) in self._member_locations()++ def entries(self, manifest, require_all: bool = True) -> list:+ """+ The entries of ``manifest`` (this source's ``ASRAudioText``) whose audio is in these tar files, in manifest+ order. Computed on the first call and cached.++ Args:+ manifest: The source's manifest.+ require_all: Raise ``ValueError`` if any manifest entry is not in the tars. Set it to ``False`` when the+ tars are only this rank's share of the source (``shard_strategy: scatter``).+ """+ if self._entries is None:+ present = [entry for entry in manifest.data if self.contains(entry)]+ if require_all and len(present) != len(manifest.data):+ missing = [entry.audio_file for entry in manifest.data if not self.contains(entry)]+ raise ValueError(+ f"{len(missing)} manifest entries are not in the tar files {self._tar_filepaths} "+ f"(e.g. {missing[:3]}). With an injected generator every entry is read by random access from "+ "the tars, so the manifest and the tars must match."+ )+ self._entries = present+ return self._entries++ def load(self, manifest_entry, target_sr: int) -> AudioSegment:+ """Read the audio of ``manifest_entry`` (an ``ASRAudioText`` item), honouring its offset and duration."""+ file_id = _file_id(manifest_entry.audio_file)+ try:+ reader, member_idx = self._member_locations()[file_id]+ except KeyError as e:+ raise KeyError(+ f"Audio file '{manifest_entry.audio_file}' was not found in tar files {self._tar_filepaths}"+ ) from e+ try:+ _, audio_bytes = reader[member_idx]+ finally:+ reader.close()+ return AudioSegment.from_file(+ io.BytesIO(audio_bytes),+ target_sr=target_sr,+ offset=0 if manifest_entry.offset is None else manifest_entry.offset,+ duration=0 if manifest_entry.duration is None else manifest_entry.duration,+ )++ def _member_locations(self) -> dict:+ if self._locations is None:+ from nemo.collections.common.data.lhotse.indexed_adapters import IndexedTarMemberReader++ locations = {}+ for tar_path in self._expand_tar_filepaths():+ _reject_compressed_tar(tar_path)+ reader = _open_indexed_tar(IndexedTarMemberReader, tar_path)+ try:+ # An index entry may span several members (the index groups consecutive members with the same+ # stem), so every regular member in its range is checked, not only the first one.+ for member_idx in range(len(reader)):+ for name in reader.regular_member_names(member_idx):+ file_id = _file_id(name)+ if file_id in locations:+ raise ValueError(+ f"Tar member '{name}' repeats audio file id '{file_id}' ({tar_path}); "+ "random access by file id would be ambiguous."+ )+ locations[file_id] = (reader, member_idx)+ finally:+ reader.close()+ self._locations = locations+ return self._locations++ def _expand_tar_filepaths(self) -> List[str]:++ return expand_sharded_filepaths(self._tar_filepaths, shard_strategy="replicate", world_size=1, global_rank=0)++ class AugmentationDataset(IterableDataset): """ A class that loads tarred audio files and cycles over the files in the dataset.@@ -1328,8 +1550,6 @@ def __init__( world_size: int = 1, shard_strategy: str = "replicate", ):- # import here to avoid circular import error- from nemo.collections.asr.data.audio_to_text import expand_sharded_filepaths self._manifest = collections.ASRAudioText(manifest_path, parser=parsers.make_parser([]), index_by_file_id=True) @@ -1396,3 +1616,85 @@ def __iter__(self): yield audio_file, file_id, manifest_entry except StopIteration: audio_iter = iter(self.audio_dataset)+++def _nested_perturbations(values):+ """Yield the :class:`Perturbation` objects in ``values``, looking one level into dicts, lists and tuples."""+ for value in values:+ if isinstance(value, Perturbation):+ yield value+ elif isinstance(value, dict):+ yield from (v for v in value.values() if isinstance(v, Perturbation))+ elif isinstance(value, (list, tuple)):+ yield from (v for v in value if isinstance(v, Perturbation))+++def _open_indexed_tar(reader_cls, tar_path: str):+ """+ Open ``tar_path`` with an indexed tar reader, using the ``.idx`` next to it. A local tar without one gets a+ cached temporary index; a remote tar must have its index next to it (it is not scanned automatically).+ """+ idx_path = tar_path + ".idx"+ if not _is_remote_tar(tar_path):+ if not os.path.exists(idx_path):+ idx_path = _cached_local_tar_index(tar_path)+ return reader_cls(tar_path, idx_path=idx_path, auto_create_index=False)+ try:+ return reader_cls(tar_path, idx_path=idx_path, auto_create_index=False)+ except Exception as e:+ raise FileNotFoundError(+ f"Random access to remote tar {tar_path} requires an index at {idx_path}, which could not be read. "+ "Build it with scripts/dataloading/build_indexes.py."+ ) from e+++def _is_remote_tar(tar_path: str) -> bool:+ from nemo.collections.common.data.lhotse.indexed_adapters import _is_remote_path++ return _is_remote_path(tar_path)+++def _cached_local_tar_index(tar_path: str) -> str:+ """Create (once) and return a temporary ``.idx`` for a local tar that has no index next to it."""+ from nemo.collections.common.data.lhotse.indexed_adapters import create_tar_index++ stat = os.stat(tar_path)+ key = hashlib.sha1(f"{os.path.abspath(tar_path)}:{stat.st_size}:{stat.st_mtime_ns}".encode()).hexdigest()+ cache_dir = os.path.join(tempfile.gettempdir(), "nemo_perturb_tar_indexes")+ os.makedirs(cache_dir, exist_ok=True)+ idx_path = os.path.join(cache_dir, f"{key}.idx")+ if not os.path.exists(idx_path):+ # Write to a unique file first so that concurrent dataloader workers never read a partial index.+ tmp_path = f"{idx_path}.{os.getpid()}.tmp"+ create_tar_index(tar_path, tmp_path)+ os.replace(tmp_path, idx_path)+ return idx_path+++def _store_injected_rng(obj, value) -> None:+ """Store an injected generator; the global ``random`` module is stored as absent, which keeps ``obj`` picklable."""+ if value is random:+ obj.__dict__.pop("_injected_rng", None)+ else:+ obj.__dict__["_injected_rng"] = value+++def _file_id(path: str) -> str:+ return os.path.splitext(os.path.basename(path))[0]+++_COMPRESSED_TAR_SUFFIXES = (".gz", ".tgz", ".bz2", ".tbz2", ".xz", ".txz", ".zst", ".zstd")+_COMPRESSION_MAGIC = (b"\x1f\x8b", b"BZh", b"\xfd7zXZ\x00", b"\x28\xb5\x2f\xfd")+++def _reject_compressed_tar(tar_path: str) -> None:+ """Random access needs byte offsets into an uncompressed tar; compressed archives raise a clear error."""+ compressed = str(tar_path).lower().endswith(_COMPRESSED_TAR_SUFFIXES)+ if not compressed and not _is_remote_tar(tar_path) and os.path.exists(tar_path):+ with open(tar_path, "rb") as f:+ compressed = f.read(6).startswith(_COMPRESSION_MAGIC)+ if compressed:+ raise ValueError(+ f"{tar_path} is a compressed archive, which can't be read by random access. Tarred noise/RIR audio read "+ "with an injected (checkpointed) generator must be stored in uncompressed tar files."+ )nemo/collections/asr/parts/utils/tarred_shards.pyadded66 + / 0 −
@@ -0,0 +1,66 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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.+"""Sharded (tarred) dataset path expansion, kept free of dataset imports so that any module can use it."""+import braceexpand++from nemo.utils import logging+++def expand_sharded_filepaths(sharded_filepaths, shard_strategy: str, world_size: int, global_rank: int):+ valid_shard_strategies = ['scatter', 'replicate']+ if shard_strategy not in valid_shard_strategies:+ raise ValueError(f"`shard_strategy` must be one of {valid_shard_strategies}")++ if isinstance(sharded_filepaths, str):+ # Replace '(' and '[' with '{'+ brace_keys_open = ['(', '[', '<', '_OP_']+ for bkey in brace_keys_open:+ if bkey in sharded_filepaths:+ sharded_filepaths = sharded_filepaths.replace(bkey, "{")++ # Replace ')' and ']' with '}'+ brace_keys_close = [')', ']', '>', '_CL_']+ for bkey in brace_keys_close:+ if bkey in sharded_filepaths:+ sharded_filepaths = sharded_filepaths.replace(bkey, "}")++ if isinstance(sharded_filepaths, str):+ # Brace expand, set escape=False for Windows compatibility+ sharded_filepaths = list(braceexpand.braceexpand(sharded_filepaths, escape=False))++ # Check for distributed and partition shards accordingly+ if world_size > 1:+ if shard_strategy == 'scatter':+ logging.info("All tarred dataset shards will be scattered evenly across all nodes.")++ if len(sharded_filepaths) % world_size != 0:+ logging.warning(+ f"Number of shards in tarred dataset ({len(sharded_filepaths)}) is not divisible "+ f"by number of distributed workers ({world_size})."+ )++ begin_idx = (len(sharded_filepaths) // world_size) * global_rank+ end_idx = begin_idx + len(sharded_filepaths) // world_size+ sharded_filepaths = sharded_filepaths[begin_idx:end_idx]+ logging.info(+ "Partitioning tarred dataset: process (%d) taking shards [%d, %d)", global_rank, begin_idx, end_idx+ )++ elif shard_strategy == 'replicate':+ logging.info("All tarred dataset shards will be replicated across all nodes.")+ else:+ raise ValueError(f"Invalid shard strategy ! Allowed values are : {valid_shard_strategies}")++ return sharded_filepathsnemo/collections/common/data/fallback.py18 + / 0 −
@@ -14,6 +14,7 @@ # limitations under the License. import torch +from nemo.collections.common.data.lhotse.stateful_rng import _is_stateful from nemo.utils import logging @@ -29,12 +30,29 @@ class FallbackDataset(torch.utils.data.Dataset): >>> dataset = AudioToTextLhotseDataset(...) ... dataset = FallbackDataset(dataset)++ The wrapper is transparent to dataloader checkpointing: ``state_dict()`` / ``load_state_dict()`` save and+ restore the wrapped dataset's state (e.g. the generator of a+ :class:`~nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin` dataset) when it has one.+ The cached fallback batch is not saved: after a restore, a ``None`` batch before any successful read returns+ ``None``, as on a first read. """ def __init__(self, dataset): self.dataset = dataset self._fallback = None + def state_dict(self) -> dict:+ """The wrapped dataset's checkpoint state, if it has one."""+ if _is_stateful(self.dataset):+ return {"dataset": self.dataset.state_dict()}+ return {}++ def load_state_dict(self, state_dict: dict) -> None:+ """Restore the wrapped dataset's checkpoint state saved by :meth:`state_dict`."""+ if "dataset" in state_dict:+ self.dataset.load_state_dict(state_dict["dataset"])+ def __getitem__(self, item): ans = self.dataset[item] if ans is None:nemo/collections/common/data/lhotse/cutset.py23 + / 3 −
@@ -1184,6 +1184,11 @@ def read_lhotse_magpietts_data_as_s2s_duplex(config) -> Tuple[CutSet, bool]: config: Dictionary containing parser options: - add_extra_end_silence (bool): Whether to add extra silence at the end. - extra_end_silence_range (List[float]): Range of extra silence duration.+ - extra_end_silence_seed (int, optional): When set, the extra silence duration is drawn from an RNG+ seeded with ``(extra_end_silence_seed, cut.id)``, so it is a pure function of the cut and is+ reproduced exactly after resuming a ``StatefulDataLoader`` checkpoint (a given cut then gets the+ same extra silence in every epoch). Set it for exact resume. When omitted (default), the duration+ is drawn from the global ``random`` module as before, which is not restored on resume. - max_cer (float): Maximum allowed character error rate. - min_context_speaker_similarity (float): Minimum similarity score. - target_speaker (str, optional): Target speaker filter.@@ -1196,6 +1201,7 @@ def read_lhotse_magpietts_data_as_s2s_duplex(config) -> Tuple[CutSet, bool]: add_extra_end_sil = config.get("add_extra_end_silence", False) extra_end_silence_range = config.get("extra_end_silence_range", [0.5, 6.0])+ extra_end_silence_seed = config.get("extra_end_silence_seed") sample_rate = config.get("sample_rate", 22050) max_cer = config.get("max_cer", 0.03)@@ -1252,7 +1258,10 @@ def convert_cut_fn(cut: Cut) -> Cut: # Optionally add extra silence if add_extra_end_sil:- sil_duration = random.uniform(*extra_end_silence_range)+ silence_rng = (+ random if extra_end_silence_seed is None else random.Random(f"{extra_end_silence_seed}:{cut.id}")+ )+ sil_duration = silence_rng.uniform(*extra_end_silence_range) cut_target = cut_target.pad(duration=total_duration + sil_duration, direction="right") cut_source = cut_source.pad(duration=total_duration + sil_duration, direction="right") cut_source = cut_source.to_mono().move_to_memory(audio_format='wav')@@ -1952,7 +1961,10 @@ def mux( return cuts -def guess_parse_cutset(inp: Union[str, dict, omegaconf.DictConfig]) -> CutSet:+def guess_parse_cutset(+ inp: Union[str, dict, omegaconf.DictConfig],+ shard_seed: Union[int, str, None] = None,+) -> CutSet: """ Utility function that supports opening a CutSet from: * a string path to YAML input spec (see :func:`read_dataset_config` for details)@@ -1962,12 +1974,18 @@ def guess_parse_cutset(inp: Union[str, dict, omegaconf.DictConfig]) -> CutSet: :class:`nemo.collections.common.data.lhotse.dataloader.LhotseDataLoadingConfig` It's intended to be used in a generic context where we are not sure which way the user will specify the inputs.++ ``shard_seed``, when given, is used for shard shuffling unless ``inp`` sets its own ``shard_seed``+ (the default is ``"trng"``, which makes the shard order differ between runs). """ from nemo.collections.common.data.lhotse.dataloader import make_structured_with_schema_warnings if isinstance(inp, (dict, omegaconf.DictConfig)): try:- config = make_structured_with_schema_warnings(OmegaConf.from_dotlist([f"{k}={v}" for k, v in inp.items()]))+ dotlist = [f"{k}={v}" for k, v in inp.items()]+ if shard_seed is not None and "shard_seed" not in inp:+ dotlist.append(f"shard_seed={shard_seed}")+ config = make_structured_with_schema_warnings(OmegaConf.from_dotlist(dotlist)) cuts, _ = read_cutset_from_config(config) return cuts except Exception as e:@@ -1984,6 +2002,8 @@ def guess_parse_cutset(inp: Union[str, dict, omegaconf.DictConfig]) -> CutSet: else: # Assume anything else is a NeMo non-tarred manifest config = make_structured_with_schema_warnings(OmegaConf.from_dotlist([f"manifest_filepath={inp}"]))+ if shard_seed is not None:+ config.shard_seed = shard_seed cuts, _ = read_cutset_from_config(config) return cuts else:nemo/collections/common/data/lhotse/dataloader.py46 + / 6 −
@@ -31,7 +31,6 @@ CutConcatenate, DynamicBucketingSampler, DynamicCutSampler,- IterableDatasetWrapper, LowpassUsingResampling, ReverbWithImpulseResponse, RoundRobinSampler,@@ -40,7 +39,7 @@ ) from lhotse.dataset.dataloading import resolve_seed from lhotse.dataset.sampling.base import CutSampler, SamplingConstraint, TimeConstraint-from lhotse.lazy import IteratorNode, LazyFlattener+from lhotse.lazy import IteratorNode, LazyFlattener, supports_graph_restore from lhotse.utils import fix_random_seed from omegaconf import DictConfig, OmegaConf @@ -70,6 +69,10 @@ TokenPerTokenFilter, ValidationStatusFilter, )+from nemo.collections.common.data.lhotse.stateful_rng import (+ StatefulIterableDatasetWrapper,+ configure_dataset_checkpointed_rng,+) from nemo.collections.common.data.prompt_fn import apply_prompt_format_fn from nemo.collections.common.prompts import PromptFormatter from nemo.collections.common.tokenizers.aggregate_tokenizer import TokenizerWrapper@@ -628,6 +631,7 @@ def get_lhotse_dataloader_from_single_config( logging.info("We will be using a Lhotse DataLoader.") config = make_structured_with_schema_warnings(config) dataset = configure_dataset_audio_loading(dataset, config.fault_tolerant_audio_loading)+ dataset = configure_dataset_checkpointed_rng(dataset, config.use_stateful_dataloader, rank=global_rank) # First, resolve the random seed in case a string value was provided. config.seed = resolve_seed(config.seed)@@ -648,7 +652,7 @@ def get_lhotse_dataloader_from_single_config( # This together with infinite datasets removes the need to split data across nodes/workers. _maybe_init_main_process_for_iterable(config.num_workers, global_rank, world_size, config.seed) dloader_kwargs = dict(- dataset=IterableDatasetWrapper(dataset=dataset, sampler=sampler),+ dataset=StatefulIterableDatasetWrapper(dataset=dataset, sampler=sampler), worker_init_fn=make_worker_init_fn(rank=global_rank, world_size=world_size, seed=config.seed), persistent_workers=config.num_workers > 0, # helps Lhotse Shar maintain shuffling state )@@ -742,6 +746,7 @@ def gather_shared_opts(): shared_opts = gather_shared_opts() dataset = configure_dataset_audio_loading(dataset, shared_opts.fault_tolerant_audio_loading)+ dataset = configure_dataset_checkpointed_rng(dataset, shared_opts.use_stateful_dataloader, rank=global_rank) fix_random_seed(shared_opts.seed) configs = {@@ -801,7 +806,7 @@ def gather_shared_opts(): # This together with infinite datasets removes the need to split data across nodes/workers. _maybe_init_main_process_for_iterable(shared_opts.num_workers, global_rank, world_size, shared_opts.seed) dloader_kwargs = dict(- dataset=IterableDatasetWrapper(dataset=dataset, sampler=sampler),+ dataset=StatefulIterableDatasetWrapper(dataset=dataset, sampler=sampler), worker_init_fn=make_worker_init_fn(rank=global_rank, world_size=world_size, seed=shared_opts.seed), persistent_workers=shared_opts.num_workers > 0, # helps Lhotse Shar maintain shuffling state )@@ -926,9 +931,13 @@ def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=No # 2. Optional augmentations. # 2.a. Noise mixing. if config.noise_path is not None:- noise = guess_parse_cutset(config.noise_path)+ # With use_stateful_dataloader, the noise shards are shuffled with the data's shard_seed (unless noise_path+ # sets its own), so the noise order, and therefore the mixed audio, is reproducible and replayed exactly on+ # resume. Without it, the noise keeps its own default shard_seed, as before.+ noise_shard_seed = config.shard_seed if config.use_stateful_dataloader else None+ noise = guess_parse_cutset(config.noise_path, shard_seed=noise_shard_seed) # make sure the noise is resampled to the same sample rate as the audio cuts- noise = noise.resample(config.sample_rate)+ noise = _mixable_noise(noise.resample(config.sample_rate)) # preserve_id="left": a noisy cut keeps its source cut's ID. Otherwise Lhotse draws the ID from a # process-global UUID stream that isn't part of the dataloader state, so IDs (and any per-cut seed # derived from them) would differ between an uninterrupted run and a resumed one.@@ -1580,3 +1589,34 @@ def _find_fixed_order_sources(node, randomized: bool, int_seed_origin: Optional[ elif int_seed_origin is not None and not randomized: found.append(int_seed_origin) return found+++def _mixable_noise(noise: CutSet) -> CutSet:+ """+ Make a noise CutSet usable by ``CutSet.mix``.++ Lhotse's ``LazyCutMixer`` samples indexed, graph-restorable noise by index, which needs the noise length. Tarred+ and Shar noise is repeated indefinitely by default (and blends may be weighted or stream-bounded), so such a noise+ CutSet can have no length, and mixing then fails on the first batch with "... is an infinite iterator". Only+ that case is changed: the noise is mixed as a stream, which keeps the configured repetition, weights and+ ``max_open_streams``. Every other noise CutSet is returned unchanged, whatever ``use_stateful_dataloader`` is.+ """+ if not noise.is_lazy or not (+ getattr(noise.data, "is_indexed", False) and supports_graph_restore(noise.data, require_length=True)+ ):+ return noise+ try:+ len(noise.data)+ except TypeError:+ return CutSet(_StreamingNoise(noise.data))+ return noise+++class _StreamingNoise(IteratorNode):+ """Iterates over an (infinite) indexed CutSet graph without exposing its random access to ``LazyCutMixer``."""++ def __init__(self, source):+ self.source = source++ def __iter__(self):+ yield from self.sourcenemo/collections/common/data/lhotse/indexed_adapters.py33 + / 15 −
@@ -732,17 +732,27 @@ def _member_header(self, idx: int) -> tuple[str, int]: start = int(self.offsets[idx]) end = int(self.offsets[idx + 1]) self._ensure_open()+ return _read_tar_member_header(self._read_range, start, end, self.data_path) - def read_range(range_start: int, range_end: int) -> bytes:- self._fh.seek(range_start)- data = self._fh.read(range_end - range_start)- if len(data) != range_end - range_start:- raise EOFError(- f"Unexpected EOF reading tar header range [{range_start}, {range_end}) in {self.data_path}"- )- return data+ def regular_member_names(self, idx: int) -> list[str]:+ """Return the names of all regular members in the byte range of index entry ``idx``, in archive order.++ Reads tar headers only (no payloads). An entry written by :func:`create_tar_index` usually holds one+ member, but consecutive members with the same stem share one entry, so a range can hold several (and+ names may repeat). Callers that need unique names check for duplicates themselves.+ """+ idx = _resolve_idx(idx, self._len)+ self._ensure_open()+ return _regular_member_names_in_range(+ self._read_range, int(self.offsets[idx]), int(self.offsets[idx + 1]), self.data_path+ ) - return _read_tar_member_header(read_range, start, end, self.data_path)+ def _read_range(self, range_start: int, range_end: int) -> bytes:+ self._fh.seek(range_start)+ data = self._fh.read(range_end - range_start)+ if len(data) != range_end - range_start:+ raise EOFError(f"Unexpected EOF reading tar header range [{range_start}, {range_end}) in {self.data_path}")+ return data def _build_name_index(self, *, reject_duplicates: bool = False) -> dict[str, int]: """Walk the tar headers once to build a name → sample-index map.@@ -1194,14 +1204,24 @@ def read_range(range_start: int, range_end: int) -> bytes: def _regular_member_stems_in_range(read_range, start: int, end: int, source_path: str) -> list[str]:- """Return the basename stems of the regular members in the tar byte range ``[start, end)``.+ """Return the unique basename stems of the regular members in the tar byte range ``[start, end)``."""+ stems: list[str] = []+ for name in _regular_member_names_in_range(read_range, start, end, source_path):+ stem = Path(name).stem+ if stem not in stems:+ stems.append(stem)+ return stems+++def _regular_member_names_in_range(read_range, start: int, end: int, source_path: str) -> list[str]:+ """Return the names of all regular members in the tar byte range ``[start, end)``, in order (may repeat). Walks headers only (no payload reads). Non-regular entries such as directories are skipped, PAX and GNU long-name metadata name the following regular member, and the walk ends cleanly at the range end or at the end-of-archive marker. An entry whose header or payload extends past ``end`` raises ``ValueError`` because the range does not hold complete entries. """- stems: list[str] = []+ names: list[str] = [] pax_headers: dict[str, str] = {} long_name: str | None = None position = start@@ -1230,13 +1250,11 @@ def _regular_member_stems_in_range(read_range, start: int, end: int, source_path pass # Link target of the next entry; irrelevant for sample names. else: if info.type in (tarfile.REGTYPE, tarfile.AREGTYPE):- stem = Path(pax_headers.get("path") or long_name or info.name).stem- if stem not in stems:- stems.append(stem)+ names.append(pax_headers.get("path") or long_name or info.name) # Per-entry metadata applies only to the entry that follows it. pax_headers, long_name = {}, None position = next_position- return stems+ return names def _scan_wds_v2_tar(tar_path: str) -> tuple[list[int], int, int]:nemo/collections/common/data/lhotse/stateful_rng.pyadded181 + / 0 −
@@ -0,0 +1,181 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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.+"""+Checkpointable randomness for Lhotse datasets.++Per-example randomness in a dataset's ``__getitem__`` (random crops, context slicing, text augmentation, ...)+must be part of the dataloader state; otherwise a run resumed from a ``StatefulDataLoader`` checkpoint reads the+same cuts as the uninterrupted run but draws different random numbers for them. The global ``random`` and+``np.random`` generators are not checkpointed, so datasets use :class:`StatefulRandomMixin` instead.++Checkpointed randomness is opt-in: it is enabled when the dataset is used with ``use_stateful_dataloader=True``+(see :func:`configure_dataset_checkpointed_rng`). Otherwise ``self.rng`` is the global ``random`` module, so+existing configurations keep drawing exactly the same random numbers as before.++How the state reaches the checkpoint:++* Map-style dataloading (the sampler lives in the training process): ``torchdata``'s ``StatefulDataLoader`` calls+ ``dataset.state_dict()`` in every worker (or in the main process when ``num_workers=0``) and restores it with+ ``dataset.load_state_dict()`` before the worker resumes.+* Iterable-style dataloading: NeMo wraps the dataset in :class:`StatefulIterableDatasetWrapper`, which adds the+ wrapped dataset's state to the state of Lhotse's ``IterableDatasetWrapper`` (which only stores the sampler).+"""+import os+import random+from types import ModuleType+from typing import Any, Optional, Union++import torch+from lhotse.dataset import IterableDatasetWrapper+from lhotse.dataset.dataloading import get_rank+++class StatefulRandomMixin:+ """+ Mixin that gives a dataset a private :class:`random.Random` (``self.rng``) whose state is saved and restored+ by ``torchdata``'s ``StatefulDataLoader``.++ Until :meth:`enable_checkpointed_rng` is called, ``self.rng`` is the global ``random`` module (the legacy+ behaviour) and the saved state is empty. Once enabled, the generator is created lazily on first use in the+ process that uses it (a dataloader worker, or the training process when ``num_workers=0``) with+ :func:`process_seeded_rng`, i.e. from ``torch.initial_seed()``, which PyTorch and Lhotse's ``worker_init_fn``+ set per worker from the dataloader seed, combined with the data-parallel rank (the ``rank`` passed to+ :meth:`enable_checkpointed_rng`, which the dataloader builders set to their ``global_rank``). A generator created in another+ process (e.g. by a ``state_dict()`` call before the dataset was copied into dataloader workers) is replaced,+ so workers never share a sequence. The draws are deterministic given the dataloader seed and the position in+ the data, and are restored exactly on resume. ``load_state_dict`` restores the generator in place, so objects+ holding a reference to ``self.rng`` keep drawing from the restored sequence.++ Example::++ >>> class MyDataset(StatefulRandomMixin, torch.utils.data.Dataset):+ ... def __getitem__(self, cuts):+ ... offsets = [self.rng.uniform(0, c.duration) for c in cuts]+ """++ def enable_checkpointed_rng(self, rank: Optional[int] = None) -> None:+ """+ Switch ``self.rng`` from the global ``random`` module to a private, checkpointed generator.++ Args:+ rank: The data-parallel rank mixed into the generator seed, so that ranks draw different sequences.+ When ``None``, it is read from the environment or the default process group (``get_rank()``),+ which can be 0 on every rank in dataloader workers started with ``spawn``/``forkserver``.+ """+ self._checkpointed_rng_enabled = True+ self._checkpointed_rng_rank = rank++ @property+ def checkpointed_rng_enabled(self) -> bool:+ """Whether ``self.rng`` is a private, checkpointed generator (see :meth:`enable_checkpointed_rng`)."""+ return self.__dict__.get("_checkpointed_rng_enabled", False)++ @property+ def rng(self) -> Union[random.Random, ModuleType]:+ """The private generator of the current process when enabled, otherwise the global ``random`` module."""+ if not self.checkpointed_rng_enabled:+ return random+ pid = os.getpid()+ rng = self.__dict__.get("_stateful_rng")+ if rng is None or self.__dict__.get("_stateful_rng_pid") != pid:+ rng = process_seeded_rng(rank=self.__dict__.get("_checkpointed_rng_rank"))+ self._stateful_rng = rng+ self._stateful_rng_pid = pid+ return rng++ def state_dict(self) -> dict[str, Any]:+ """Return the generator state using only plain Python types (``None`` when not enabled)."""+ if not self.checkpointed_rng_enabled:+ return {"rng_state": None}+ version, internal_state, gauss_next = self.rng.getstate()+ return {"rng_state": {"version": version, "internal_state": list(internal_state), "gauss_next": gauss_next}}++ def load_state_dict(self, state_dict: dict[str, Any]) -> None:+ """Restore, in place, the generator state saved by :meth:`state_dict`."""+ state = state_dict["rng_state"]+ if state is None:+ return+ if not self.checkpointed_rng_enabled:+ raise RuntimeError(+ f"The checkpoint contains a random generator state for {type(self).__name__}, but checkpointed "+ "randomness is not enabled for it (it is enabled by use_stateful_dataloader=True)."+ )+ # self.rng returns the generator owned by this process (creating it if needed); restore it in place.+ self.rng.setstate((state["version"], tuple(state["internal_state"]), state["gauss_next"]))+++class StatefulIterableDatasetWrapper(IterableDatasetWrapper):+ """+ Lhotse's :class:`~lhotse.dataset.iterable_dataset.IterableDatasetWrapper` that also checkpoints the state of+ the wrapped dataset (e.g. the random generator of a :class:`StatefulRandomMixin` dataset).++ Lhotse's wrapper only saves the epoch and the sampler state, so without this the wrapped dataset's random+ draws after a resume would differ from the uninterrupted run.+ """++ def state_dict(self) -> dict:+ state = super().state_dict()+ if _is_stateful(self.dataset):+ state["dataset_state"] = self.dataset.state_dict()+ return state++ def load_state_dict(self, sd: dict) -> None:+ super().load_state_dict(sd)+ # Checkpoints written before the dataset state was saved don't have the key; the dataset then keeps+ # its freshly seeded state, which matches the behaviour those checkpoints were saved with.+ if "dataset_state" in sd:+ if not _is_stateful(self.dataset):+ raise RuntimeError(+ f"The dataloader checkpoint contains a dataset state, but the dataset "+ f"{type(self.dataset).__name__} does not implement load_state_dict()."+ )+ self.dataset.load_state_dict(sd["dataset_state"])+++def configure_dataset_checkpointed_rng(dataset: Any, enabled: bool, rank: Optional[int] = None) -> Any:+ """+ Enable checkpointed randomness on a :class:`StatefulRandomMixin` dataset when ``enabled``, seeding its+ generator with the data-parallel ``rank`` (see :meth:`StatefulRandomMixin.enable_checkpointed_rng`). Wrappers+ that keep the wrapped dataset in ``.dataset`` (e.g. ``FallbackDataset``) are looked through.+ """+ target = dataset+ while enabled and target is not None:+ if isinstance(target, StatefulRandomMixin):+ target.enable_checkpointed_rng(rank=rank)+ break+ target = getattr(target, "dataset", None)+ return dataset+++def process_seeded_rng(namespace: str = "", rank: Optional[int] = None) -> random.Random:+ """+ Create a :class:`random.Random` seeded for the current process.++ The seed combines ``namespace``, ``torch.initial_seed()`` (which PyTorch and Lhotse's ``worker_init_fn`` set+ per dataloader worker from the dataloader seed) and the data-parallel rank, so it is deterministic given the+ seeds and differs between workers and ranks. It never touches the global ``random`` state.++ Args:+ namespace: Prefix that separates generators of different components in the same process.+ rank: The data-parallel rank. Pass it when known: the fallback, ``get_rank()``, reads ``RANK`` or the+ default process group, which dataloader workers started with ``spawn``/``forkserver`` may not have.+ """+ if rank is None:+ rank = get_rank()+ return random.Random(f"{namespace}{torch.initial_seed()}:{rank}")+++def _is_stateful(obj: Any) -> bool:+ return callable(getattr(obj, "state_dict", None)) and callable(getattr(obj, "load_state_dict", None))nemo/collections/tts/data/audio_codec_dataset_lhotse.py8 + / 3 −
@@ -13,17 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. -import random from typing import Dict import numpy as np import torch from lhotse import CutSet +from nemo.collections.common.data.lhotse.stateful_rng import StatefulRandomMixin from nemo.utils import logging -class AudioCodecLhotseDataset(torch.utils.data.Dataset):+class AudioCodecLhotseDataset(StatefulRandomMixin, torch.utils.data.Dataset): """ A Lhotse-based dataset for audio codec model training. @@ -33,6 +33,11 @@ class AudioCodecLhotseDataset(torch.utils.data.Dataset): * Random truncation of each cut's `target_audio` to a fixed duration * Sanity checks on the audio + The random segment start is drawn from the dataset's generator ``self.rng``+ (see :class:`~nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin`).+ With ``use_stateful_dataloader=True`` it is checkpointed, so a resumed run reads the same segments+ as an uninterrupted one; otherwise it is the global ``random`` module.+ The operations below are handled directly by Lhotse according to the configuration applied in `AudioCodecModel._get_lhotse_dataloader()`: * Minimum duration filtering@@ -85,7 +90,7 @@ def _load_and_truncate_target_audio(self, cut) -> torch.Tensor: ) # Randomly select a segment of the audio- start = random.randint(0, num_samples - self.segment_samples)+ start = self.rng.randint(0, num_samples - self.segment_samples) segment = audio[start : start + self.segment_samples] return torch.from_numpy(np.ascontiguousarray(segment, dtype=np.float32)) nemo/collections/tts/data/text_to_speech_dataset_lhotse.py23 + / 9 −
@@ -13,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import random import re from typing import Dict, List, Union @@ -24,6 +23,7 @@ from omegaconf import DictConfig from transformers import AutoTokenizer, T5Tokenizer +from nemo.collections.common.data.lhotse.stateful_rng import StatefulRandomMixin from nemo.collections.common.tokenizers.text_to_speech.tts_tokenizers import ( AggregatedTTSTokenizer, IPABPETokenizer,@@ -37,6 +37,7 @@ has_phoneme_text_spans, normalize_volume, partially_phonemize_text,+ set_g2p_rng, stack_tensors, tokenize_text_with_phoneme_spans, )@@ -121,7 +122,7 @@ def check_speaker_format(item: str): return bool(re.match(pattern, item)) -class MagpieTTSLhotseDataset(torch.utils.data.Dataset):+class MagpieTTSLhotseDataset(StatefulRandomMixin, torch.utils.data.Dataset): """ A PyTorch Dataset for loading and processing Text-to-Speech data for MagpieTTS models using Lhotse CutSets, specifically designed for datasets@@ -138,6 +139,12 @@ class MagpieTTSLhotseDataset(torch.utils.data.Dataset): Tokenizers (for target text and optional context text) are initialized lazily within each dataloader worker process upon first access. + All random choices (context slicing, text context remapping, partial phonemization, tokenizer+ choice, G2P ``phoneme_probability``, ...) use the dataset's generator ``self.rng`` (see+ :class:`~nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin`). With+ ``use_stateful_dataloader=True`` it is a checkpointed generator, so a run resumed from a ``StatefulDataLoader``+ checkpoint produces the same batches as an uninterrupted run; otherwise it is the global ``random`` module.+ Args: sample_rate (int): Target sample rate for loading audio. Audio will be resampled if necessary.@@ -279,6 +286,10 @@ def __getitem__(self, cuts: CutSet) -> Dict[str, Union[torch.Tensor, List]]: # initialize the phoneme tokenizer once per dataset/worker when config is available. if self.phoneme_tokenizer is None and self.phoneme_tokenizer_config is not None: self.phoneme_tokenizer = safe_instantiate(self.phoneme_tokenizer_config)+ # With checkpointed randomness, G2P draws (e.g. phoneme_probability) come from the dataset generator.+ if self.checkpointed_rng_enabled:+ set_g2p_rng(self.text_tokenizer, self.rng)+ set_g2p_rng(self.phoneme_tokenizer, self.rng) # define list to store batched information dataset_name_list = []@@ -309,7 +320,7 @@ def __getitem__(self, cuts: CutSet) -> Dict[str, Union[torch.Tensor, List]]: def _sample_context_duration_with_available_limit(available_duration_sec: float) -> float: effective_duration_max = min(self.context_duration_max, available_duration_sec) effective_duration_max = max(self.context_duration_min, effective_duration_max)- return random.uniform(self.context_duration_min, effective_duration_max)+ return self.rng.uniform(self.context_duration_min, effective_duration_max) for cut in cuts: speaker = cut.supervisions[0].speaker@@ -366,7 +377,7 @@ def _sample_context_duration_with_available_limit(available_duration_sec: float) _context_duration_to_slice * self.sample_rate / self.codec_model_samples_per_frame ) if _num_frames_to_slice < context_audio_codes.shape[1]:- start_idx = random.randint(0, context_audio_codes.shape[1] - _num_frames_to_slice)+ start_idx = self.rng.randint(0, context_audio_codes.shape[1] - _num_frames_to_slice) context_audio_codes = context_audio_codes[:, start_idx : start_idx + _num_frames_to_slice] else: # Repeat the audio if it is shorter than the desired duration@@ -391,7 +402,7 @@ def _sample_context_duration_with_available_limit(available_duration_sec: float) _context_duration_to_slice, self.sample_rate ) if _num_samples_to_slice < len(context_audio_array):- start_idx = random.randint(0, len(context_audio_array) - _num_samples_to_slice)+ start_idx = self.rng.randint(0, len(context_audio_array) - _num_samples_to_slice) context_audio_array = context_audio_array[start_idx : start_idx + _num_samples_to_slice] else: # Repeat the audio if it is shorter than the desired duration@@ -440,7 +451,7 @@ def _sample_context_duration_with_available_limit(available_duration_sec: float) _context_duration_to_slice = _sample_context_duration_with_available_limit(_available_context_duration) _num_samples_to_slice = int(_context_duration_to_slice * 16_000) if _num_samples_to_slice < len(audio_array_16khz):- start_idx = random.randint(0, len(audio_array_16khz) - _num_samples_to_slice)+ start_idx = self.rng.randint(0, len(audio_array_16khz) - _num_samples_to_slice) audio_array_16khz = audio_array_16khz[start_idx : start_idx + _num_samples_to_slice] audio_16khz = torch.from_numpy(audio_array_16khz) audio_len_16khz = audio_16khz.shape[0]@@ -451,7 +462,7 @@ def _sample_context_duration_with_available_limit(available_duration_sec: float) if cut.supervisions[0].has_custom("context_text"): context_text = cut.supervisions[0].context_text if self.text_context_remapping is not None and context_text in self.text_context_remapping:- if self.dataset_type == 'train' and random.random() < self.text_context_remapping_prob:+ if self.dataset_type == 'train' and self.rng.random() < self.text_context_remapping_prob: # Only remap during training. Give the exact text context during inference. context_text = self.text_context_remapping[context_text] context_text_tokens = self.text_tokenizer.encode(@@ -492,6 +503,7 @@ def _sample_context_duration_with_available_limit(available_duration_sec: float) text=supervision.text, normalized_text=supervision.normalized_text if supervision.has_custom("normalized_text") else None, load_normalized_text_percent=self.load_normalized_text_percent,+ rng=self.rng, ) raw_text_list.append(text_str) text_for_tokens = text_str@@ -506,12 +518,13 @@ def _sample_context_duration_with_available_limit(available_duration_sec: float) bop_marker=self.phoneme_text_bop_marker, eop_marker=self.phoneme_text_eop_marker, )- and random.random() < self.partial_phoneme_text_prob+ and self.rng.random() < self.partial_phoneme_text_prob ): sampled_portion = _sample_probability_range( "partial_phoneme_portion", self.partial_phoneme_portion_min, self.partial_phoneme_portion_max,+ rng=self.rng, ) text_for_tokens = partially_phonemize_text( text=text_str,@@ -520,10 +533,11 @@ def _sample_context_duration_with_available_limit(available_duration_sec: float) full_ipa_text=(cut.supervisions[0].ipa if cut.supervisions[0].has_custom("ipa") else None), bop_marker=self.phoneme_text_bop_marker, eop_marker=self.phoneme_text_eop_marker,+ rng=self.rng, ) if cut.has_custom("tokenizer_names"): # Pick a random tokenizer from the list of tokenizers- tokenizer_name = random.choice(cut.tokenizer_names)+ tokenizer_name = self.rng.choice(cut.tokenizer_names) else: tokenizer_name = "english_phoneme" # Default to english phoneme tokenizer tokens = tokenize_text_with_phoneme_spans(nemo/collections/tts/data/text_to_speech_dataset_lhotse_multiturn.py55 + / 20 −
@@ -27,6 +27,7 @@ from lhotse.utils import ifnone from omegaconf import DictConfig +from nemo.collections.common.data.lhotse.stateful_rng import StatefulRandomMixin from nemo.collections.common.tokenizers.text_to_speech.tts_tokenizers import IPABPETokenizer from nemo.collections.speechlm2.parts.precision import fp32_precision from nemo.collections.tts.data.text_to_speech_dataset_lhotse import setup_tokenizers@@ -38,6 +39,7 @@ has_phoneme_text_spans, normalize_volume, partially_phonemize_text,+ set_g2p_rng, stack_tensors, tokenize_text_with_phoneme_spans, )@@ -79,7 +81,7 @@ def _get_supervision_ipa_text(supervision) -> str: return "" -class MagpieTTSLhotseMultiturnDataset(torch.utils.data.Dataset):+class MagpieTTSLhotseMultiturnDataset(StatefulRandomMixin, torch.utils.data.Dataset): """ A PyTorch Dataset for loading and processing Text-to-Speech data for MagpieTTS models using Lhotse CutSets, specifically designed for datasets@@ -96,6 +98,12 @@ class MagpieTTSLhotseMultiturnDataset(torch.utils.data.Dataset): Tokenizers (for target text and optional context text) are initialized lazily within each dataloader worker process upon first access. + All random choices (context slicing, challenging text replacement, context shuffling, partial+ phonemization, phoneme turn dropout, tokenizer choice, G2P ``phoneme_probability``, ...) use the dataset's+ generator ``self.rng`` (see :class:`~nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin`). With+ ``use_stateful_dataloader=True`` it is a checkpointed generator, so a run resumed from a ``StatefulDataLoader``+ checkpoint produces the same batches as an uninterrupted run; otherwise it is the global ``random`` module.+ Args: sample_rate (int): Target sample rate for loading audio. Audio will be resampled if necessary.@@ -310,12 +318,12 @@ def _prepare_cuts(self, cuts: CutSet) -> tuple[CutSet, list[str]]: batch_tokenizer_names = [] for cut in cuts: if cut.has_custom("tokenizer_names"):- batch_tokenizer_names.append(random.choice(cut.tokenizer_names))+ batch_tokenizer_names.append(self.rng.choice(cut.tokenizer_names)) else: batch_tokenizer_names.append("english_phoneme") challenging_text_prob = self.get_challenging_text_replacement_prob()- if self.dataset_type == 'train' and random.random() < challenging_text_prob:+ if self.dataset_type == 'train' and self.rng.random() < challenging_text_prob: candidates = [ (cut_idx, cut, supervision) for cut_idx, cut in enumerate(cuts)@@ -324,11 +332,11 @@ def _prepare_cuts(self, cuts: CutSet) -> tuple[CutSet, list[str]]: if supervision.speaker in self.output_roles ] if candidates:- cut_idx, cut, supervision = random.choice(candidates)+ cut_idx, cut, supervision = self.rng.choice(candidates) total_slots = compute_num_frames(cut.duration, self.frame_length, cut.sampling_rate) start_slot = compute_num_frames(supervision.start, self.frame_length, cut.sampling_rate) available_slots = total_slots - start_slot- for replacement_text in random.sample(self.challenging_texts, min(32, len(self.challenging_texts))):+ for replacement_text in self.rng.sample(self.challenging_texts, min(32, len(self.challenging_texts))): replacement_ids = tokenize_text_with_phoneme_spans( text_tokenizer=self.text_tokenizer, text_str=replacement_text,@@ -446,6 +454,7 @@ def _collate_text_channels(self, cuts: CutSet, batch_tokenizer_names: list[str]) ignore_phoneme_languages=self.ignore_phoneme_languages, apply_partial_phoneme_text=self.dataset_type == 'train', load_normalized_text_percent=self.load_normalized_text_percent,+ rng=self.rng, ) source_tokens, source_token_lens = collate_token_channel( cuts,@@ -459,6 +468,7 @@ def _collate_text_channels(self, cuts: CutSet, batch_tokenizer_names: list[str]) bos_id=self.bos_id, interruption_token_id=self.interruption_token_id, load_normalized_text_percent=self.load_normalized_text_percent,+ rng=self.rng, ) return {@@ -483,6 +493,7 @@ def _collate_phoneme_tokens(self, cuts: CutSet) -> Dict[str, Union[torch.Tensor, phoneme_turn_dropout_turn_prob=self.phoneme_turn_dropout_turn_prob, phoneme_turn_max_words_to_drop=self.phoneme_turn_max_words_to_drop, apply_turn_dropout=self.dataset_type == 'train',+ rng=self.rng, ) else: target_phoneme_tokens, target_phoneme_lens, phoneme_turn_dropout = None, None, None@@ -530,7 +541,7 @@ def _load_cached_codes(self, cut: Cut) -> tuple[Union[torch.Tensor, None], Union def _sample_context_duration_with_available_limit(self, available_duration_sec: float) -> float: effective_duration_max = min(self.context_duration_max, available_duration_sec) effective_duration_max = max(self.context_duration_min, effective_duration_max)- return random.uniform(self.context_duration_min, effective_duration_max)+ return self.rng.uniform(self.context_duration_min, effective_duration_max) def _load_context_codes(self, cut: Cut) -> torch.Tensor: context_audio_codes_array = cut.context_codes.load().astype(np.int32)@@ -542,7 +553,7 @@ def _load_context_codes(self, cut: Cut) -> torch.Tensor: _num_frames_to_slice = int(_context_duration_to_slice * self.sample_rate / self.codec_model_samples_per_frame) if _num_frames_to_slice < context_audio_codes.shape[1]:- start_idx = random.randint(0, context_audio_codes.shape[1] - _num_frames_to_slice)+ start_idx = self.rng.randint(0, context_audio_codes.shape[1] - _num_frames_to_slice) context_audio_codes = context_audio_codes[:, start_idx : start_idx + _num_frames_to_slice] else: _num_repeats = int(np.ceil(_num_frames_to_slice / context_audio_codes.shape[1]))@@ -561,7 +572,7 @@ def _load_context_audio(self, cut: Cut) -> torch.Tensor: _num_samples_to_slice = self.get_num_audio_samples_to_slice(_context_duration_to_slice, self.sample_rate) if _num_samples_to_slice < len(context_audio_array):- start_idx = random.randint(0, len(context_audio_array) - _num_samples_to_slice)+ start_idx = self.rng.randint(0, len(context_audio_array) - _num_samples_to_slice) context_audio_array = context_audio_array[start_idx : start_idx + _num_samples_to_slice] else: _num_repeats = int(np.ceil(_num_samples_to_slice / len(context_audio_array)))@@ -576,7 +587,7 @@ def _load_fallback_context( if self.load_cached_codes_if_available and cut.has_custom("target_codes"): if context_text is None and len(matching_supervisions) > 0:- sup = random.choice(matching_supervisions)+ sup = self.rng.choice(matching_supervisions) codes_array = cut.target_codes.load().astype(np.int32) start_frame = int(max(0, sup.start) * self.sample_rate / self.codec_model_samples_per_frame) num_frames = int(sup.duration * self.sample_rate / self.codec_model_samples_per_frame)@@ -587,7 +598,7 @@ def _load_fallback_context( return None, context_audio_codes if context_text is None and len(matching_supervisions) > 0:- sup = random.choice(matching_supervisions)+ sup = self.rng.choice(matching_supervisions) with fp32_precision(): turn_cut = cut.resample(self.sample_rate, recording_field="target_audio").truncate( offset=max(0, sup.start), duration=sup.duration@@ -623,12 +634,12 @@ def _load_audio_16khz(self, cut: Cut) -> torch.Tensor: ) _num_samples_to_slice = int(_context_duration_to_slice * 16_000) if _num_samples_to_slice < len(audio_array_16khz):- start_idx = random.randint(0, len(audio_array_16khz) - _num_samples_to_slice)+ start_idx = self.rng.randint(0, len(audio_array_16khz) - _num_samples_to_slice) audio_array_16khz = audio_array_16khz[start_idx : start_idx + _num_samples_to_slice] else: matching_supervisions = [s for s in cut.supervisions if s.speaker in self.output_roles] if len(matching_supervisions) > 0:- sup = random.choice(matching_supervisions)+ sup = self.rng.choice(matching_supervisions) turn_cut = cut.resample(16_000, recording_field="target_audio").truncate( offset=max(0, sup.start), duration=sup.duration )@@ -644,7 +655,7 @@ def _load_audio_16khz(self, cut: Cut) -> torch.Tensor: def _encode_context_text(self, context_text: Union[str, None], language: str) -> tuple[torch.Tensor, bool]: if context_text is not None: if self.text_context_remapping is not None and context_text in self.text_context_remapping:- if self.dataset_type == 'train' and random.random() < self.text_context_remapping_prob:+ if self.dataset_type == 'train' and self.rng.random() < self.text_context_remapping_prob: context_text = self.text_context_remapping[context_text] context_text_tokens = self.text_tokenizer.encode( context_text, tokenizer_name=self.text_conditioning_tokenizer_name@@ -803,7 +814,7 @@ def _maybe_shuffle_context_audio(self, features: Dict[str, List]) -> None: if ( self.dataset_type != 'train' or self.context_audio_shuffle_batch_prob <= 0.0- or random.random() >= self.context_audio_shuffle_batch_prob+ or self.rng.random() >= self.context_audio_shuffle_batch_prob ): return @@ -842,7 +853,7 @@ def _maybe_shuffle_context_audio(self, features: Dict[str, List]) -> None: ] if not candidates: candidates = [donor_idx for donor_idx in eligible_indices if donor_idx != target_idx]- donor_indices[target_idx] = random.choice(candidates)+ donor_indices[target_idx] = self.rng.choice(candidates) original_contexts = list(features[context_key]) original_context_lens = list(context_lens)@@ -976,6 +987,10 @@ def _build_batch_dict( def __getitem__(self, cuts: CutSet) -> Dict[str, Union[torch.Tensor, List]]: self._initialize_tokenizers()+ # With checkpointed randomness, G2P draws (e.g. phoneme_probability) come from the dataset generator.+ if self.checkpointed_rng_enabled:+ set_g2p_rng(self.text_tokenizer, self.rng)+ set_g2p_rng(self.phoneme_tokenizer, self.rng) cuts, batch_tokenizer_names = self._prepare_cuts(cuts) audio_data = self._collate_audio_channels(cuts)@@ -1009,8 +1024,15 @@ def collate_token_channel( ignore_phoneme_languages: list[str] = None, apply_partial_phoneme_text: bool = False, load_normalized_text_percent: float = 1.0,+ *,+ rng: random.Random | None = None, ) -> tuple[torch.Tensor, torch.Tensor]:- """Build and collate token channels aligned to the audio frame grid."""+ """Build and collate token channels aligned to the audio frame grid.++ ``rng`` is the random generator for normalized-text selection and partial phonemization+ (the global ``random`` module when omitted).+ """+ rng = random if rng is None else rng tokens = [] for i, c in enumerate(cuts):@@ -1038,6 +1060,7 @@ def collate_token_channel( ignore_phoneme_languages, apply_partial_phoneme_text, load_normalized_text_percent=load_normalized_text_percent,+ rng=rng, ) ) token_lens = torch.tensor([len(tt) for tt in tokens])@@ -1094,8 +1117,10 @@ def build_token_channel( ignore_phoneme_languages: list[str] = None, apply_partial_phoneme_text: bool = False, load_normalized_text_percent: float = 1.0,+ *,+ rng: random.Random | None = None, ) -> torch.Tensor:-+ rng = random if rng is None else rng total = compute_num_frames(cut.duration, frame_length, cut.sampling_rate) tokens = torch.ones(total, dtype=torch.long) * pad_id @@ -1105,6 +1130,7 @@ def build_token_channel( text=supervision.text, normalized_text=supervision.normalized_text if supervision.has_custom("normalized_text") else None, load_normalized_text_percent=load_normalized_text_percent,+ rng=rng, ) text_for_tokens = text language = cut.lang if cut.has_custom("lang") else supervision.language@@ -1120,12 +1146,13 @@ def build_token_channel( bop_marker=phoneme_text_bop_marker, eop_marker=phoneme_text_eop_marker, )- and random.random() < partial_phoneme_text_prob+ and rng.random() < partial_phoneme_text_prob ): sampled_portion = _sample_probability_range( "partial_phoneme_portion", partial_phoneme_portion_min, partial_phoneme_portion_max,+ rng=rng, ) text_for_tokens = partially_phonemize_text( text=text,@@ -1134,6 +1161,7 @@ def build_token_channel( full_ipa_text=_get_supervision_ipa_text(supervision), bop_marker=phoneme_text_bop_marker, eop_marker=phoneme_text_eop_marker,+ rng=rng, ) raw_ids = tokenize_text_with_phoneme_spans( text_tokenizer=tokenizer,@@ -1240,7 +1268,10 @@ def collate_phoneme_channel( phoneme_turn_dropout_turn_prob: float = 0.0, phoneme_turn_max_words_to_drop: int = 2, apply_turn_dropout: bool = False,+ *,+ rng: random.Random | None = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ rng = random if rng is None else rng tokens = [] dropout_flags = [] for i, c in enumerate(cuts):@@ -1257,6 +1288,7 @@ def collate_phoneme_channel( phoneme_turn_dropout_turn_prob=phoneme_turn_dropout_turn_prob, phoneme_turn_max_words_to_drop=phoneme_turn_max_words_to_drop, apply_turn_dropout=apply_turn_dropout,+ rng=rng, ) tokens.append(token) dropout_flags.append(dropout_applied)@@ -1277,7 +1309,10 @@ def build_phoneme_channel( phoneme_turn_dropout_turn_prob: float = 0.0, phoneme_turn_max_words_to_drop: int = 2, apply_turn_dropout: bool = False,+ *,+ rng: random.Random | None = None, ) -> tuple[torch.Tensor, bool]:+ rng = random if rng is None else rng language = ( cut.lang if cut.has_custom("lang")@@ -1291,12 +1326,12 @@ def build_phoneme_channel( apply_turn_dropout and phoneme_turn_dropout_batch_prob > 0.0 and phoneme_turn_dropout_turn_prob > 0.0- and random.random() < phoneme_turn_dropout_batch_prob+ and rng.random() < phoneme_turn_dropout_batch_prob ) for supervision in cut.supervisions: if supervision.speaker in roles:- if apply_dropout and random.random() < phoneme_turn_dropout_turn_prob:+ if apply_dropout and rng.random() < phoneme_turn_dropout_turn_prob: dropout_applied = True continue nemo/collections/tts/g2p/models/base.py26 + / 0 −
@@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import os+import random from abc import ABC, abstractmethod from typing import Optional @@ -37,6 +39,30 @@ def __init__( self.apply_to_oov_word = apply_to_oov_word self.mapping_file = mapping_file + @property+ def rng(self) -> random.Random:+ """+ Random generator for stochastic G2P choices (e.g. ``phoneme_probability``).++ By default this is an unseeded ``random.Random()`` per G2P instance and process, as before. A training+ dataset with checkpointed randomness (see+ :class:`~nemo.collections.common.data.lhotse.stateful_rng.StatefulRandomMixin`) assigns its generator+ here in its dataloading process, so G2P draws are restored on resume together with the dataset's own+ draws. For reproducible standalone use, assign a seeded generator, e.g.+ ``g2p.rng = process_seeded_rng("g2p:")``. A generator assigned or created in another process (e.g. before+ the G2P was copied into a dataloader worker) is replaced by a fresh unseeded one, so workers never share+ a sequence.+ """+ rng = self.__dict__.get("_rng")+ if rng is None or self.__dict__.get("_rng_pid") != os.getpid():+ self.rng = rng = random.Random()+ return rng++ @rng.setter+ def rng(self, value: random.Random) -> None:+ self._rng = value+ self._rng_pid = os.getpid()+ @abstractmethod def __call__(self, text: str) -> str: passnemo/collections/tts/g2p/models/en_us_arpabet.py1 + / 3 −
@@ -14,7 +14,6 @@ # limitations under the License. import pathlib-import random import re import time from typing import Optional@@ -85,7 +84,6 @@ def __init__( else heteronyms ) self.phoneme_probability = phoneme_probability- self._rng = random.Random() @staticmethod def _parse_as_cmu_dict(phoneme_dict_path=None, encoding='latin-1'):@@ -158,7 +156,7 @@ def parse_one_word(self, word: str): `status` will be `False` if word wasn't handled, `True` otherwise. """ - if self.phoneme_probability is not None and self._rng.random() > self.phoneme_probability:+ if self.phoneme_probability is not None and self.rng.random() > self.phoneme_probability: return word, True # punctuation or whitespace.nemo/collections/tts/g2p/models/i18n_ipa.py1 + / 3 −
@@ -14,7 +14,6 @@ # limitations under the License. import pathlib-import random import re from collections import defaultdict from typing import Callable, Dict, List, Optional, Set, Tuple, Union@@ -109,7 +108,6 @@ def __init__( self.grapheme_prefix = grapheme_prefix self.phoneme_probability = phoneme_probability self.locale = locale- self._rng = random.Random() if locale is not None: validate_locale(locale)@@ -390,7 +388,7 @@ def parse_one_word(self, word: str) -> Tuple[List[str], bool]: return list(word), True # Keep graphemes of a word with a probability.- if self.phoneme_probability is not None and self._rng.random() > self.phoneme_probability:+ if self.phoneme_probability is not None and self.rng.random() > self.phoneme_probability: return self._prepend_prefix_for_one_word(word), True # Heteronymsnemo/collections/tts/parts/utils/tts_dataset_utils.py59 + / 6 −
@@ -42,6 +42,7 @@ from nemo.collections.asr.parts.preprocessing.segment import AudioSegment from nemo.collections.audio.parts.utils.transforms import resample from nemo.collections.common.parts.utils import mask_sequence_tensor+from nemo.collections.tts.g2p.models.base import BaseG2p try: from nemo_text_processing.text_normalization.normalize import Normalizer@@ -121,22 +122,33 @@ def _validate_probability(name: str, value: float): raise ValueError(f"`{name}` must be in range [0.0, 1.0], received {value}") -def _select_text_for_tts_input(text: str, normalized_text: Optional[str], load_normalized_text_percent: float) -> str:- """Select the raw or normalized transcript used as TTS model input."""+def _select_text_for_tts_input(+ text: str,+ normalized_text: Optional[str],+ load_normalized_text_percent: float,+ rng: Optional[random.Random] = None,+) -> str:+ """Select the raw or normalized transcript used as TTS model input.++ ``rng`` is the caller's random generator; when omitted, the global ``random`` module is used.+ """ if normalized_text is None or load_normalized_text_percent == 0.0: return text- if load_normalized_text_percent == 1.0 or random.random() < load_normalized_text_percent:+ if load_normalized_text_percent == 1.0 or (rng or random).random() < load_normalized_text_percent: return normalized_text return text -def _sample_probability_range(name: str, min_value: float, max_value: float) -> float:+def _sample_probability_range(+ name: str, min_value: float, max_value: float, rng: Optional[random.Random] = None+) -> float: """Sample a probability uniformly from an inclusive configured range. Args: name: Base parameter name to include in validation errors. min_value: Lower bound of the probability range. max_value: Upper bound of the probability range.+ rng: Random generator to draw from. Defaults to the global ``random`` module. Returns: A uniformly sampled probability between ``min_value`` and ``max_value``.@@ -149,7 +161,7 @@ def _sample_probability_range(name: str, min_value: float, max_value: float) -> _validate_probability(f"{name}_max", max_value) if min_value > max_value: raise ValueError(f"`{name}_min` must be <= `{name}_max`, received {min_value} > {max_value}")- return random.uniform(min_value, max_value)+ return (rng or random).uniform(min_value, max_value) def has_phoneme_text_spans(text: str, bop_marker: str = "<bop>", eop_marker: str = "<eop>") -> bool:@@ -224,6 +236,7 @@ def partially_phonemize_text( full_ipa_text: Optional[str] = None, bop_marker: str = "<bop>", eop_marker: str = "<eop>",+ rng: Optional[random.Random] = None, ) -> str: """Replace a sampled portion of aligned words with marked IPA spans. @@ -241,6 +254,7 @@ def partially_phonemize_text( full_ipa_text: IPA transcription of the complete input text. bop_marker: Marker to place before each generated IPA span. eop_marker: Marker to place after each generated IPA span.+ rng: Random generator used to select the words. Defaults to the global ``random`` module. Returns: Text with sampled words replaced by marked IPA spans, or the original@@ -267,7 +281,7 @@ def partially_phonemize_text( ipa_ranges.append((ipa_start, ipa_end)) ipa_cursor = ipa_end - selected_indices = sorted(random.sample(range(len(ipa_alignment)), num_selected))+ selected_indices = sorted((rng or random).sample(range(len(ipa_alignment)), num_selected)) selected_runs = [] for index in selected_indices: if selected_runs and index == selected_runs[-1][1] + 1:@@ -1375,3 +1389,42 @@ def transcribe(self, audio_paths: List[Path], language: str, batch_size: int) -> transcriptions = self.processor.batch_decode(predicted_ids, skip_special_tokens=True) all_transcriptions.extend(transcriptions) return all_transcriptions+++def set_g2p_rng(tokenizer: Any, rng: random.Random) -> None:+ """+ Make every G2P module reachable from ``tokenizer`` draw its random choices (e.g. ``phoneme_probability``)+ from ``rng``.++ Datasets call this with their checkpointed generator so that G2P randomness is restored on resume together+ with the dataset's own draws. ``tokenizer`` may be a single TTS tokenizer with a ``g2p`` attribute, an+ ``AggregatedTTSTokenizer`` (its ``tokenizers`` are visited), or any other tokenizer (ignored).+ """+ if tokenizer is None:+ return+ sub_tokenizers = getattr(tokenizer, "tokenizers", None)+ if isinstance(sub_tokenizers, dict):+ sub_tokenizers = list(sub_tokenizers.values())+ if isinstance(sub_tokenizers, (list, tuple)):+ for sub_tokenizer in sub_tokenizers:+ set_g2p_rng(sub_tokenizer, rng)+ elif sub_tokenizers is not None:+ _warn_once_g2p_rng_skipped(tokenizer, f"its 'tokenizers' is a {type(sub_tokenizers).__name__}")+ g2p = getattr(tokenizer, "g2p", None)+ if isinstance(g2p, BaseG2p):+ g2p.rng = rng+ elif g2p is not None:+ _warn_once_g2p_rng_skipped(tokenizer, f"its g2p ({type(g2p).__name__}) is not a BaseG2p")+++_G2P_RNG_SKIP_WARNED = set()+++def _warn_once_g2p_rng_skipped(tokenizer: Any, reason: str) -> None:+ key = (type(tokenizer).__name__, reason)+ if key not in _G2P_RNG_SKIP_WARNED:+ _G2P_RNG_SKIP_WARNED.add(key)+ logging.warning(+ f"set_g2p_rng: skipped {type(tokenizer).__name__} because {reason}; its random G2P choices keep their own "+ "generator and are not restored on resume."+ )tests/collections/asr/conftest.py11 + / 0 −
@@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import random from dataclasses import dataclass from typing import Optional, Type @@ -427,3 +428,13 @@ def cache_aware_model_cfg(): }, } )+++@pytest.fixture+def restore_global_rng_state():+ """Restore the global ``random``, ``np.random`` and ``torch`` generators after a test that seeds them."""+ python_state, numpy_state, torch_state = random.getstate(), np.random.get_state(), torch.get_rng_state()+ yield+ random.setstate(python_state)+ np.random.set_state(numpy_state)+ torch.set_rng_state(torch_state)tests/collections/asr/test_asr_lhotse_dataset_rng_resume.pyadded143 + / 0 −
@@ -0,0 +1,143 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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.+"""+The ASR Lhotse datasets with random choices resume exactly through the configured stateful loader:+``use_stateful_dataloader=True`` enables their checkpointed generator, and a restored loader reproduces the+uninterrupted batches.+"""++import random+from unittest.mock import patch++import pytest+import torch+from lhotse import CutSet, SupervisionSegment+from lhotse.testing.dummies import DummyManifest+from omegaconf import OmegaConf++from nemo.collections.asr.data.audio_to_text_lhotse_prompt_index import LhotseSpeechToTextBpeDatasetWithPromptIndex+from nemo.collections.asr.data.audio_to_text_lhotse_speaker import LhotseSpeechToTextSpkBpeDataset+from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config+from nemo.collections.common.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer, create_spt_model+from tests.collections.asr.test_asr_lhotse_eou_dataset import make_eou_dataset++pytestmark = pytest.mark.unit++PROMPT_DICTIONARY = {'en-US': 0, 'de-DE': 3, 'auto': 6}+++@pytest.fixture(scope="module")+def tokenizer(tmp_path_factory) -> SentencePieceTokenizer:+ tmpdir = tmp_path_factory.mktemp("rng_resume_tokens")+ text_path = tmpdir / "text.txt"+ text_path.write_text("\n".join(map(chr, range(ord('a'), ord('z')))))+ model_path, _ = create_spt_model(+ text_path, vocab_size=32, sample_size=-1, do_lower_case=False, output_dir=str(tmpdir)+ )+ return SentencePieceTokenizer(model_path)+++def _cuts(kind: str) -> CutSet:+ """Eight one-second cuts with in-memory audio; speaker cuts have two distinguishable speakers."""+ cuts = DummyManifest(CutSet, begin_id=0, end_id=8, with_data=True)+ for cut in cuts:+ if kind == "speaker":+ cut.supervisions = [+ SupervisionSegment(+ id=f"{cut.id}-0", recording_id=cut.recording_id, start=0, duration=0.5, text="first", speaker="0"+ ),+ SupervisionSegment(+ id=f"{cut.id}-1",+ recording_id=cut.recording_id,+ start=0.5,+ duration=0.5,+ text="second",+ speaker="1",+ ),+ ]+ else:+ cut.supervisions[0].language = "de-DE"+ return cuts+++def _dataset(kind: str, tokenizer, pad_distribution: str = "uniform"):+ if kind == "eou":+ return make_eou_dataset(pad_distribution, tokenizer=tokenizer)+ if kind == "speaker":+ return LhotseSpeechToTextSpkBpeDataset(cfg={}, tokenizer=tokenizer)+ cfg = {"prompt_dictionary": PROMPT_DICTIONARY, "num_prompts": 8, "default_prompt_mode": "unified"}+ return LhotseSpeechToTextBpeDatasetWithPromptIndex(tokenizer=tokenizer, cfg=cfg)+++def _loader(kind, tokenizer, mode, pad_distribution="uniform"):+ config = OmegaConf.create(+ {+ "batch_size": 2,+ "shuffle": True,+ "seed": 0,+ "shard_seed": 0,+ "num_workers": 0,+ "use_stateful_dataloader": True,+ "force_map_dataset": mode == "map",+ "force_iterable_dataset": mode == "iterable",+ }+ )+ dataset = _dataset(kind, tokenizer, pad_distribution) # checkpointed randomness is not enabled by hand+ with patch(+ "nemo.collections.common.data.lhotse.dataloader.read_cutset_from_config", return_value=(_cuts(kind), False)+ ):+ return get_lhotse_dataloader_from_config(config, global_rank=0, world_size=1, dataset=dataset)+++def _summarize(kind, batch):+ if kind == "eou":+ tensors = [batch.audio_signal, batch.audio_lengths, batch.eou_targets, batch.eou_target_lengths]+ else:+ tensors = list(batch)+ return [t.tolist() for t in tensors]+++def _random_part(kind, summary):+ """The part of a batch that the dataset draws at random."""+ # EOU: padded audio lengths; speaker: target-speaker masks; prompt: language prompt indices.+ return summary[1] if kind == "eou" else summary[4]+++@pytest.mark.usefixtures("restore_global_rng_state")+@pytest.mark.parametrize("mode", ["map", "iterable"])+@pytest.mark.parametrize(+ "kind,pad_distribution", [("eou", "uniform"), ("eou", "normal"), ("speaker", None), ("prompt", None)]+)+def test_stateful_loader_resumes_random_draws(tokenizer, kind, pad_distribution, mode):+ uninterrupted_loader = _loader(kind, tokenizer, mode, pad_distribution)+ uninterrupted = [_summarize(kind, batch) for batch in uninterrupted_loader]+ loader = _loader(kind, tokenizer, mode, pad_distribution)+ it = iter(loader)+ _ = next(it)+ _ = next(it)+ state = loader.state_dict()++ # A resumed process starts with different global RNG states; the fresh dataset is not reseeded.+ random.seed(1234)+ torch.manual_seed(1234)+ resumed_loader = _loader(kind, tokenizer, mode, pad_distribution)+ resumed_loader.load_state_dict(state)+ resumed = [_summarize(kind, batch) for batch in resumed_loader]++ assert len(uninterrupted) == 4+ assert resumed == uninterrupted[2:]+ # The loader enabled checkpointed randomness, and the draws vary between batches.+ random_parts = [_random_part(kind, summary) for summary in uninterrupted]+ assert len({str(part) for part in random_parts}) > 1tests/collections/asr/test_asr_lhotse_eou_dataset.pyadded155 + / 0 −
@@ -0,0 +1,155 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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 random++import numpy as np+import pytest+import torch+from omegaconf import OmegaConf++from nemo.collections.asr.data.audio_to_eou_label_lhotse import LhotseSpeechToTextBpeEOUDataset++pytestmark = pytest.mark.unit++SAMPLE_RATE = 16000+++def make_eou_dataset(pad_distribution: str, tokenizer=None) -> LhotseSpeechToTextBpeEOUDataset:+ """An EOU dataset with ``random_padding`` (shared with ``test_asr_lhotse_dataset_rng_resume.py``)."""+ cfg = OmegaConf.create(+ {+ "check_tokenizer": False,+ "sample_rate": SAMPLE_RATE,+ "random_padding": {+ "prob": 0.9,+ "max_total_duration": 6.0,+ "min_post_pad_duration": 0.5,+ "pad_distribution": pad_distribution,+ },+ }+ )+ return LhotseSpeechToTextBpeEOUDataset(cfg=cfg, tokenizer=tokenizer)+++def _dataset(pad_distribution: str, checkpointed_rng: bool = True) -> LhotseSpeechToTextBpeEOUDataset:+ dataset = make_eou_dataset(pad_distribution)+ if checkpointed_rng:+ dataset.enable_checkpointed_rng()+ return dataset+++def _pad(dataset: LhotseSpeechToTextBpeEOUDataset):+ audio = torch.ones(SAMPLE_RATE)+ eou_targets = torch.zeros(13, dtype=torch.long)+ eou_targets[-1] = 1+ padded_audio, padded_audio_len, padded_eou_targets = dataset._random_pad_audio(+ audio, torch.tensor(SAMPLE_RATE), eou_targets+ )+ return padded_audio, int(padded_audio_len), padded_eou_targets+++@pytest.mark.usefixtures("restore_global_rng_state")+@pytest.mark.parametrize("pad_distribution", ["uniform", "normal"])+def test_restored_rng_state_reproduces_random_padding(pad_distribution):+ dataset = _dataset(pad_distribution)+ dataset.rng.seed(0) # a fixed sequence that pads to several different lengths+ state = dataset.state_dict()+ expected = [_pad(dataset) for _ in range(8)]++ # A resumed process does not share the global RNG state of the original one.+ np.random.seed(1234)+ restored = _dataset(pad_distribution)+ restored.load_state_dict(state)++ for padded_audio, padded_audio_len, padded_eou_targets in expected:+ actual_audio, actual_len, actual_eou_targets = _pad(restored)+ assert actual_len == padded_audio_len+ torch.testing.assert_close(actual_audio, padded_audio)+ torch.testing.assert_close(actual_eou_targets, padded_eou_targets)+ # The padding is drawn at random, so it differs between reads of the same audio.+ assert len({padded_audio_len for _, padded_audio_len, _ in expected}) > 1+++@pytest.mark.usefixtures("restore_global_rng_state")+@pytest.mark.parametrize("pad_distribution", ["uniform", "normal"])+def test_random_padding_uses_numpy_rng_unless_checkpointed_rng_is_enabled(pad_distribution):+ # Legacy behaviour: without use_stateful_dataloader the padding follows the global ``np.random``.+ dataset = _dataset(pad_distribution, checkpointed_rng=False)+ np.random.seed(0)+ first = [_pad(dataset)[1] for _ in range(8)]+ np.random.seed(0)+ second = [_pad(dataset)[1] for _ in range(8)]++ assert first == second+ assert len(set(first)) > 1+++def _dataset_with_augmentor(checkpointed_rng: bool = True) -> LhotseSpeechToTextBpeEOUDataset:+ cfg = OmegaConf.create(+ {+ "check_tokenizer": False,+ "sample_rate": SAMPLE_RATE,+ "augmentor": {+ "gain": {"prob": 0.5, "min_gain_dbfs": -10, "max_gain_dbfs": 10},+ "white_noise": {"prob": 1.0, "min_level": -60, "max_level": -40},+ },+ }+ )+ dataset = LhotseSpeechToTextBpeEOUDataset(cfg=cfg, tokenizer=None)+ if checkpointed_rng:+ dataset.enable_checkpointed_rng()+ return dataset+++def _augment(dataset: LhotseSpeechToTextBpeEOUDataset):+ audio = torch.sin(torch.arange(SAMPLE_RATE, dtype=torch.float32) / 10.0)+ augmented, augmented_len = dataset._maybe_augment_audio(audio, torch.tensor(SAMPLE_RATE))+ return augmented, int(augmented_len)+++@pytest.mark.usefixtures("restore_global_rng_state")+def test_restored_rng_state_reproduces_augmentor_perturbations():+ dataset = _dataset_with_augmentor()+ dataset.rng.seed(0) # a fixed sequence in which the gain perturbation is applied to some reads only+ state = dataset.state_dict()+ expected = [_augment(dataset) for _ in range(4)]++ # A resumed process does not share the global RNG states of the original one.+ random.seed(1234)+ np.random.seed(1234)+ restored = _dataset_with_augmentor()+ restored.load_state_dict(state)++ for expected_audio, expected_len in expected:+ actual_audio, actual_len = _augment(restored)+ assert actual_len == expected_len+ torch.testing.assert_close(actual_audio, expected_audio)+ # The perturbations are random, so the output differs between reads of the same audio.+ assert len({audio.numpy().tobytes() for audio, _ in expected}) == len(expected)+++@pytest.mark.usefixtures("restore_global_rng_state")+def test_augmentor_uses_global_rngs_unless_checkpointed_rng_is_enabled():+ # Legacy behaviour: without use_stateful_dataloader the perturbations follow the global generators.+ dataset = _dataset_with_augmentor(checkpointed_rng=False)+ random.seed(0)+ np.random.seed(0)+ first = _augment(dataset)[0]+ random.seed(0)+ np.random.seed(0)+ second = _augment(dataset)[0]++ torch.testing.assert_close(first, second)tests/collections/asr/test_asr_lhotse_speaker_dataset.py48 + / 0 −
@@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import random+ import pytest import torch from lhotse import CutSet, SupervisionSegment@@ -87,3 +89,49 @@ def test_lhotse_asr_speaker_dataset(tokenizer): assert bg_spk_targets[1].long().sum().item() in [6, 7] assert (spk_targets[1] + bg_spk_targets[1]).long().tolist() == [1] * 13+++def _two_speaker_cuts():+ cuts = DummyManifest(CutSet, begin_id=0, end_id=4, with_data=True)+ for cut in cuts:+ cut.supervisions = [+ SupervisionSegment(+ id=f"{cut.id}-sup0", recording_id=cut.recording_id, start=0, duration=0.5, text="first", speaker="0"+ ),+ SupervisionSegment(+ id=f"{cut.id}-sup1", recording_id=cut.recording_id, start=0.5, duration=0.5, text="second", speaker="1"+ ),+ ]+ return cuts+++def test_lhotse_asr_speaker_dataset_restored_rng_state_reproduces_target_speakers(tokenizer):+ cuts = _two_speaker_cuts()+ dataset = LhotseSpeechToTextSpkBpeDataset(cfg={}, tokenizer=tokenizer)+ dataset.enable_checkpointed_rng()+ dataset.rng.seed(0) # a fixed sequence that picks different target speakers+ state = dataset.state_dict()+ expected = [dataset[cuts] for _ in range(4)]++ restored = LhotseSpeechToTextSpkBpeDataset(cfg={}, tokenizer=tokenizer)+ restored.enable_checkpointed_rng()+ restored.load_state_dict(state)++ for expected_batch in expected:+ for actual, exp in zip(restored[cuts], expected_batch):+ torch.testing.assert_close(actual, exp)+ # The target speaker is drawn at random, so the targets differ between reads of the same cuts.+ assert len({tuple(batch[4].flatten().tolist()) for batch in expected}) > 1+++@pytest.mark.usefixtures("restore_global_rng_state")+def test_lhotse_asr_speaker_dataset_uses_global_rng_unless_checkpointed_rng_is_enabled(tokenizer):+ # Legacy behaviour: without use_stateful_dataloader the target speaker follows the global ``random``.+ cuts = _two_speaker_cuts()+ dataset = LhotseSpeechToTextSpkBpeDataset(cfg={}, tokenizer=tokenizer)+ random.seed(0)+ first = dataset[cuts][4]+ random.seed(0)+ second = dataset[cuts][4]++ torch.testing.assert_close(first, second)tests/collections/asr/test_asr_rnnt_prompt_language.py35 + / 0 −
@@ -20,6 +20,7 @@ """ import os+import random from functools import partial from types import SimpleNamespace @@ -649,6 +650,40 @@ def test_plain_model_forward_signature_has_no_prompt(self): ) +class TestPromptIndexDatasetRNG:+ """The unified-mode auto prompt draw must be restored with the dataloader state."""++ @pytest.mark.unit+ def test_restored_rng_state_reproduces_unified_prompt_draws(self):+ dataset = make_prompt_dataset(default_prompt_mode='unified')+ dataset.enable_checkpointed_rng()+ dataset.rng.seed(0) # a fixed sequence that picks both prompts+ cut = make_cut('de-DE')+ state = dataset.state_dict()+ expected = [dataset._get_prompt_index_for_cut(cut) for _ in range(32)]++ restored = make_prompt_dataset(default_prompt_mode='unified')+ restored.enable_checkpointed_rng()+ restored.load_state_dict(state)++ assert [restored._get_prompt_index_for_cut(cut) for _ in range(32)] == expected+ assert set(expected) == {PROMPT_DICTIONARY['de-DE'], PROMPT_DICTIONARY['auto']}++ @pytest.mark.unit+ @pytest.mark.usefixtures("restore_global_rng_state")+ def test_unified_prompt_uses_global_rng_unless_checkpointed_rng_is_enabled(self):+ # Legacy behaviour: without use_stateful_dataloader the choice follows the global ``random``.+ dataset = make_prompt_dataset(default_prompt_mode='unified')+ cut = make_cut('de-DE')+ random.seed(0)+ first = [dataset._get_prompt_index_for_cut(cut) for _ in range(16)]+ random.seed(0)+ second = [dataset._get_prompt_index_for_cut(cut) for _ in range(16)]++ assert first == second+ assert len(set(first)) > 1++ @pytest.mark.unit def test_chunked_transcription_keeps_each_manifest_language(prompt_model, tmp_path): import jsontests/collections/asr/test_perturb_rng.pyadded243 + / 0 −
@@ -0,0 +1,243 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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 json+import pickle+import random++import numpy as np+import pytest+import soundfile as sf+import torch++from nemo.collections.asr.parts.preprocessing.perturb import (+ GainPerturbation,+ Perturbation,+ RirAndNoisePerturbation,+ ShiftPerturbation,+ SilencePerturbation,+ WhiteNoisePerturbation,+ process_augmentations,+)+from nemo.collections.asr.parts.preprocessing.segment import AudioSegment++pytestmark = pytest.mark.unit++SAMPLE_RATE = 16000+AUGMENTOR_CFG = {+ "gain": {"prob": 0.5, "min_gain_dbfs": -10, "max_gain_dbfs": 10},+ "shift": {"prob": 0.5, "min_shift_ms": -50.0, "max_shift_ms": 50.0},+ "silence": {"prob": 0.5, "min_start_silence_secs": 0.0, "max_start_silence_secs": 0.2},+ "white_noise": {"prob": 1.0, "min_level": -60, "max_level": -40},+}+++@pytest.fixture(scope="module")+def manifests(tmp_path_factory):+ """Two-file noise and RIR manifests (distinct files, so the sampled entry changes the output)."""+ root = tmp_path_factory.mktemp("perturb_rng")+ rng = np.random.default_rng(0)+ paths = {}+ for kind, duration in [("noise", 2.0), ("rir", 0.1)]:+ lines = []+ for i in range(2):+ path = root / f"{kind}_{i}.wav"+ samples = rng.standard_normal(int(duration * SAMPLE_RATE)).astype(np.float32) * (0.1 + 0.4 * i)+ if kind == "rir":+ samples *= np.exp(-np.arange(samples.size) / (20.0 + 100.0 * i)).astype(np.float32)+ sf.write(path, samples, SAMPLE_RATE)+ lines.append(json.dumps({"audio_filepath": str(path), "duration": duration, "text": ""}))+ paths[kind] = root / f"{kind}_manifest.json"+ paths[kind].write_text("\n".join(lines) + "\n")+ return paths+++def _manifest_augmentor_cfg(manifests):+ """AUGMENTOR_CFG plus manifest-sampled noise and impulse perturbations."""+ return {+ **AUGMENTOR_CFG,+ "noise": {"prob": 1.0, "manifest_path": str(manifests["noise"]), "min_snr_db": 0, "max_snr_db": 20},+ "impulse": {"prob": 0.5, "manifest_path": str(manifests["rir"])},+ }+++def _segment():+ samples = np.sin(np.arange(SAMPLE_RATE, dtype=np.float32) / 10.0).astype(np.float32)+ return AudioSegment(samples=samples, sample_rate=SAMPLE_RATE)+++def _augment(augmentor, times: int = 6):+ outputs = []+ for _ in range(times):+ segment = _segment()+ augmentor.perturb(segment)+ outputs.append(segment.samples.copy())+ return outputs+++def _assert_same(actual, expected):+ assert len(actual) == len(expected)+ for a, e in zip(actual, expected):+ np.testing.assert_array_equal(a, e)+++@pytest.mark.usefixtures("restore_global_rng_state")+def test_injected_rng_drives_all_augmentation_draws():+ augmentor = process_augmentations(AUGMENTOR_CFG)+ augmentor.rng = random.Random(0)+ random.seed(1)+ np.random.seed(1)+ expected = _augment(augmentor)++ other = process_augmentations(AUGMENTOR_CFG)+ other.rng = random.Random(0)+ random.seed(2) # the global generators play no part once a generator is injected+ np.random.seed(2)++ _assert_same(_augment(other), expected)+ # The draws vary between calls (different lengths from silence/shift, different noise).+ assert len({out.tobytes() for out in expected}) == len(expected)+++@pytest.mark.usefixtures("restore_global_rng_state")+def test_injected_rng_drives_manifest_sampling(manifests):+ cfg = _manifest_augmentor_cfg(manifests)+ augmentor = process_augmentations(cfg)+ augmentor.rng = random.Random(0)+ random.seed(1)+ np.random.seed(1)+ expected = _augment(augmentor, times=8)++ other = process_augmentations(cfg)+ other.rng = random.Random(0)+ random.seed(2) # the noise/RIR entries and offsets are drawn from the injected generator only+ np.random.seed(2)++ _assert_same(_augment(other, times=8), expected)+ assert len({out.tobytes() for out in expected}) == len(expected)+++def test_restoring_injected_rng_state_reproduces_augmentation():+ augmentor = process_augmentations(AUGMENTOR_CFG)+ rng = random.Random(0)+ augmentor.rng = rng+ _augment(augmentor, times=2)+ state = rng.getstate()+ expected = _augment(augmentor)++ restored = random.Random()+ restored.setstate(state)+ augmentor.rng = restored++ _assert_same(_augment(augmentor), expected)+++def test_injected_rng_reaches_every_perturbation():+ augmentor = process_augmentations(AUGMENTOR_CFG)+ rng = random.Random(0)+ augmentor.rng = rng++ assert augmentor.rng is rng+ assert all(p.rng is rng for _, p in augmentor._pipeline)+++def test_injected_rng_reaches_nested_perturbations():+ class Composite(Perturbation):+ def __init__(self):+ self._by_sample_rate = {SAMPLE_RATE: GainPerturbation()}+ self._chain = [ShiftPerturbation(), SilencePerturbation()]+ self._single = WhiteNoisePerturbation()++ def perturb(self, data):+ pass++ composite = Composite()+ rng = random.Random(0)+ composite.rng = rng++ nested = [composite._by_sample_rate[SAMPLE_RATE], *composite._chain, composite._single]+ assert all(p.rng is rng for p in nested)+++def test_injected_rng_reaches_rir_and_noise_perturbers(manifests):+ perturbation = RirAndNoisePerturbation(+ rir_manifest_path=str(manifests["rir"]),+ noise_manifest_paths=[str(manifests["noise"])],+ min_snr_db=[0],+ max_snr_db=[20],+ noise_tar_filepaths=[None],+ bg_noise_manifest_paths=[str(manifests["noise"])],+ bg_min_snr_db=[10],+ bg_max_snr_db=[30],+ bg_noise_tar_filepaths=[None],+ )+ rng = random.Random(0)+ perturbation.rng = rng++ nested = [+ perturbation._rir_perturber,+ *perturbation._fg_noise_perturbers.values(),+ *perturbation._bg_noise_perturbers.values(),+ ]+ assert all(p.rng is rng for p in nested)++ state = rng.getstate()+ expected = _augment(perturbation, times=4)+ rng.setstate(state)+ _assert_same(_augment(perturbation, times=4), expected)+ assert len({out.tobytes() for out in expected}) == len(expected)+++def test_default_rng_is_the_global_random_module():+ # Backward compatibility: without an injected generator, perturbations use the global RNG as before.+ assert GainPerturbation().rng is random+ assert process_augmentations(AUGMENTOR_CFG).rng is random+++@pytest.mark.parametrize("assignment", ["default", "global", "private", "private_then_global"])+def test_augmentor_stays_picklable(assignment):+ # Dataloader workers started with spawn receive a pickled dataset (and its augmentor).+ augmentor = process_augmentations(AUGMENTOR_CFG)+ if assignment in ("private", "private_then_global"):+ augmentor.rng = random.Random(0)+ if assignment in ("global", "private_then_global"):+ augmentor.rng = random++ copy = pickle.loads(pickle.dumps(augmentor))++ expect_private = assignment == "private"+ for obj in [copy, *(p for _, p in copy._pipeline)]:+ assert (obj.rng is not random) == expect_private+ if expect_private:+ assert all(p.rng is copy.rng for _, p in copy._pipeline)+ _assert_same(_augment(copy), _augment(augmentor))+++def test_eou_dataset_with_augmentor_stays_picklable_after_a_legacy_read():+ from omegaconf import OmegaConf++ from nemo.collections.asr.data.audio_to_eou_label_lhotse import LhotseSpeechToTextBpeEOUDataset++ dataset = LhotseSpeechToTextBpeEOUDataset(+ cfg=OmegaConf.create({"check_tokenizer": False, "sample_rate": SAMPLE_RATE, "augmentor": AUGMENTOR_CFG}),+ tokenizer=None,+ )+ audio = np.sin(np.arange(SAMPLE_RATE, dtype=np.float32) / 10.0)+ # A diagnostic read in the parent with checkpointing disabled assigns the legacy generator.+ dataset._maybe_augment_audio(torch.from_numpy(audio), torch.tensor(SAMPLE_RATE))++ copy = pickle.loads(pickle.dumps(dataset))++ assert copy.augmentor.rng is randomtests/collections/asr/test_perturb_tarred_rng.pyadded378 + / 0 −
@@ -0,0 +1,378 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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 gzip+import json+import os+import random+import tarfile+from types import SimpleNamespace++import numpy as np+import pytest+import soundfile as sf+import torch++from nemo.collections.asr.parts.preprocessing import perturb+from nemo.collections.asr.parts.preprocessing.perturb import (+ ImpulsePerturbation,+ NoisePerturbation,+ NoisePerturbationWithNormalization,+)+from nemo.collections.asr.parts.preprocessing.segment import AudioSegment+from nemo.collections.common.data.lhotse.indexed_adapters import create_tar_index++pytestmark = pytest.mark.unit++SAMPLE_RATE = 16000+NUM_FILES = 8+++@pytest.fixture(params=[True, False], ids=["with_idx", "without_idx"])+def tarred_audio(tmp_path, request):+ """Eight distinct 1.2 s audio files in two NeMo-style tars, with or without .idx files.++ NoisePerturbationWithNormalization requires noise of at least 1 s.+ """+ manifest_path = tmp_path / "manifest.json"+ tar_paths = [tmp_path / f"audio_{i}.tar" for i in range(2)]+ tars = [tarfile.open(path, "w") for path in tar_paths]+ with manifest_path.open("w") as manifest:+ for i in range(NUM_FILES):+ t = np.arange(int(1.2 * SAMPLE_RATE)) / SAMPLE_RATE+ samples = 0.1 * np.sin(2 * np.pi * (200 + 150 * i) * t) * np.exp(-t * (i + 1))+ wav_path = tmp_path / f"audio_{i}.wav"+ sf.write(wav_path, samples.astype(np.float32), SAMPLE_RATE)+ tars[i % 2].add(wav_path, arcname=wav_path.name)+ manifest.write(json.dumps({"audio_filepath": wav_path.name, "duration": 1.2, "text": ""}) + "\n")+ for tar in tars:+ tar.close()+ if request.param:+ for path in tar_paths:+ create_tar_index(str(path), str(path) + ".idx")+ return str(manifest_path), [str(path) for path in tar_paths]+++def _make(kind, manifest_path, tar_paths):+ if kind == "noise":+ return NoisePerturbation(manifest_path, min_snr_db=10, max_snr_db=10, audio_tar_filepaths=tar_paths)+ if kind == "impulse":+ return ImpulsePerturbation(manifest_path, audio_tar_filepaths=tar_paths, shuffle_n=4)+ return NoisePerturbationWithNormalization(+ manifest_path, min_snr_db=10, max_snr_db=10, audio_tar_filepaths=[tar_paths], shuffle_n=4+ )+++def _apply(perturbation, times):+ outputs = []+ for _ in range(times):+ t = np.arange(SAMPLE_RATE) / SAMPLE_RATE+ segment = AudioSegment(samples=(0.3 * np.sin(2 * np.pi * 440 * t)).astype(np.float32), sample_rate=SAMPLE_RATE)+ perturbation.perturb(segment)+ outputs.append(segment.samples.copy())+ return outputs+++@pytest.mark.parametrize("kind", ["noise", "impulse", "noise_with_normalization"])+def test_tarred_audio_choice_is_restored_from_injected_rng(tarred_audio, kind):+ manifest_path, tar_paths = tarred_audio+ perturbation = _make(kind, manifest_path, tar_paths)+ rng = random.Random(0)+ perturbation.rng = rng+ _apply(perturbation, 2)+ state = rng.getstate()+ expected = _apply(perturbation, 4)++ # A resumed run builds a fresh perturbation (with a fresh tar iterator) and restores the generator state.+ resumed = _make(kind, manifest_path, tar_paths)+ restored_rng = random.Random()+ restored_rng.setstate(state)+ resumed.rng = restored_rng+ actual = _apply(resumed, 4)++ for a, e in zip(actual, expected):+ np.testing.assert_array_equal(a, e)+ # Different noise/RIR files are picked over the calls.+ assert len({out.tobytes() for out in expected}) > 1+++@pytest.mark.parametrize("kind", ["noise", "impulse", "noise_with_normalization"])+def test_tarred_audio_without_injected_rng_keeps_sequential_reading(tarred_audio, kind, monkeypatch):+ manifest_path, tar_paths = tarred_audio+ perturbation = _make(kind, manifest_path, tar_paths)++ def fail(*args, **kwargs):+ raise AssertionError("random access must only be used with an injected generator")++ monkeypatch.setattr(perturb._TarredAudioRandomAccess, "load", fail)++ assert len(_apply(perturbation, 3)) == 3+++def _write_tar(tar_path, members):+ """Write a tar with ``(arcname, samples)`` members, in order (names may repeat)."""+ with tarfile.open(tar_path, "w") as tar:+ for i, (arcname, samples) in enumerate(members):+ wav_path = tar_path.parent / f"{tar_path.stem}_{i}.wav"+ sf.write(wav_path, samples.astype(np.float32), SAMPLE_RATE)+ tar.add(wav_path, arcname=arcname)+++def _tone(frequency, seconds=1.2):+ t = np.arange(int(seconds * SAMPLE_RATE)) / SAMPLE_RATE+ return 0.1 * np.sin(2 * np.pi * frequency * t)+++def _manifest(path, entries):+ path.write_text("".join(json.dumps({"text": "", **entry}) + "\n" for entry in entries))+ return str(path)+++def _entry(audio_file, offset=None, duration=1.2):+ return SimpleNamespace(audio_file=audio_file, offset=offset, duration=duration)+++def test_noise_sources_keep_their_own_file_names(tmp_path):+ # Two sources each contain a different "noise.wav"; each entry must be read from its own source's tar.+ source_dirs = [tmp_path / "a", tmp_path / "b"]+ manifests, tars = [], []+ for source_dir, frequency in zip(source_dirs, [300, 900]):+ source_dir.mkdir()+ _write_tar(source_dir / "noise.tar", [("noise.wav", _tone(frequency))])+ manifests.append(_manifest(source_dir / "manifest.json", [{"audio_filepath": "noise.wav", "duration": 1.2}]))+ tars.append(str(source_dir / "noise.tar"))++ def make():+ return NoisePerturbationWithNormalization(manifests, audio_tar_filepaths=tars, shuffle_n=1)++ perturbation = make()+ rng = random.Random(0)+ perturbation.rng = rng+ state = rng.getstate()+ noises = [perturbation.read_one_audiosegment(SAMPLE_RATE).samples for _ in range(16)]++ expected = {frequency: _tone(frequency).astype(np.float32) for frequency in [300, 900]}+ matched = [+ next(f for f, ref in expected.items() if np.allclose(noise, ref, atol=1e-4)) for noise in noises+ ] # raises StopIteration if a noise matches neither source+ assert set(matched) == {300, 900}++ resumed = make()+ restored_rng = random.Random()+ restored_rng.setstate(state)+ resumed.rng = restored_rng+ for noise in noises:+ np.testing.assert_array_equal(resumed.read_one_audiosegment(SAMPLE_RATE).samples, noise)+++@pytest.mark.parametrize("kind", ["noise", "impulse", "noise_with_normalization"])+def test_manifest_entry_missing_from_tars_fails_on_first_draw(tmp_path, kind):+ # A 10-member tar and an 11-entry manifest: the extra entry must be reported on the first draw, not when it+ # happens to be drawn (possibly hours into training).+ tar_path = tmp_path / "noise.tar"+ _write_tar(tar_path, [(f"n{i}.wav", _tone(200 + 50 * i)) for i in range(10)])+ manifest = _manifest(+ tmp_path / "manifest.json", [{"audio_filepath": f"n{i}.wav", "duration": 1.2} for i in range(11)]+ )+ perturbation = _make(kind, manifest, [str(tar_path)])+ perturbation.rng = random.Random(0)++ with pytest.raises(ValueError, match="n10.wav"):+ _apply(perturbation, 1)+++def test_duplicate_tar_member_names_are_rejected(tmp_path):+ tar_path = tmp_path / "noise.tar"+ _write_tar(tar_path, [("noise.wav", _tone(300)), ("other.wav", _tone(500)), ("noise.wav", _tone(700))])++ with pytest.raises(ValueError, match="noise.wav"):+ perturb._TarredAudioRandomAccess(str(tar_path)).load(_entry("noise.wav"), SAMPLE_RATE)+++def test_manifest_offsets_into_one_member_load_their_slices(tmp_path):+ tar_path = tmp_path / "noise.tar"+ samples = np.concatenate([_tone(300, 1.0), _tone(900, 1.0)])+ _write_tar(tar_path, [("noise.wav", samples)])+ access = perturb._TarredAudioRandomAccess(str(tar_path))++ first = access.load(_entry("noise.wav", offset=0.0, duration=1.0), SAMPLE_RATE).samples+ second = access.load(_entry("noise.wav", offset=1.0, duration=1.0), SAMPLE_RATE).samples++ np.testing.assert_allclose(first, _tone(300, 1.0), atol=1e-4)+ np.testing.assert_allclose(second, _tone(900, 1.0), atol=1e-4)+++def test_remote_tar_uses_its_existing_index(tarred_audio, monkeypatch):+ manifest_path, tar_paths = tarred_audio+ for path in tar_paths:+ if not os.path.exists(path + ".idx"):+ create_tar_index(path, path + ".idx")+ # Treat the local tar as remote: its index must exist next to it and is never created.+ monkeypatch.setattr(perturb, "_is_remote_tar", lambda path: True)++ access = perturb._TarredAudioRandomAccess(tar_paths)+ loaded = access.load(_entry("audio_3.wav"), SAMPLE_RATE).samples++ assert loaded.shape == (int(1.2 * SAMPLE_RATE),)+++def test_remote_tar_without_index_raises_actionable_error(tmp_path, monkeypatch):+ tar_path = tmp_path / "noise.tar"+ _write_tar(tar_path, [("noise.wav", _tone(300))])+ # Treat the local tar as remote: its index must exist next to it and is never created.+ monkeypatch.setattr(perturb, "_is_remote_tar", lambda path: True)++ with pytest.raises(FileNotFoundError, match="build_indexes.py"):+ perturb._TarredAudioRandomAccess(str(tar_path)).load(_entry("noise.wav"), SAMPLE_RATE)+++def test_random_access_does_not_keep_tar_files_open(tmp_path):+ # Readers are closed after each use, so reading from many shards does not accumulate open files+ # (otherwise a corpus with more shards than the open-file limit fails).+ num_shards = 32+ for i in range(num_shards):+ _write_tar(tmp_path / f"noise_{i}.tar", [(f"noise_{i}.wav", _tone(200 + i, 0.1))])+ access = perturb._TarredAudioRandomAccess([str(tmp_path / f"noise_{i}.tar") for i in range(num_shards)])+ fd_dir = "/proc/self/fd" if os.path.isdir("/proc/self/fd") else "/dev/fd"+ num_open_before = len(os.listdir(fd_dir))++ rng = random.Random(0)+ for _ in range(2 * num_shards):+ i = rng.randrange(num_shards)+ access.load(_entry(f"noise_{i}.wav", duration=0.1), SAMPLE_RATE)++ assert len(os.listdir(fd_dir)) <= num_open_before + 2+++@pytest.mark.parametrize("with_index", [False, True], ids=["without_idx", "with_idx"])+def test_adjacent_duplicate_tar_members_are_rejected(tmp_path, with_index):+ # The index groups consecutive members with the same stem into one entry; both members must still be checked.+ tar_path = tmp_path / "noise.tar"+ _write_tar(tar_path, [("noise.wav", _tone(300)), ("noise.wav", _tone(900))])+ if with_index:+ create_tar_index(str(tar_path), str(tar_path) + ".idx")++ with pytest.raises(ValueError, match="noise.wav"):+ perturb._TarredAudioRandomAccess(str(tar_path)).load(_entry("noise.wav"), SAMPLE_RATE)+++def test_compressed_tar_with_injected_rng_raises(tmp_path):+ tar_path = tmp_path / "noise.tar"+ _write_tar(tar_path, [("noise.wav", _tone(300))])+ gz_path = tmp_path / "noise.tar.gz"+ with open(tar_path, "rb") as src, gzip.open(gz_path, "wb") as dst:+ dst.write(src.read())+ manifest = _manifest(tmp_path / "manifest.json", [{"audio_filepath": "noise.wav", "duration": 1.2}])+ perturbation = NoisePerturbation(manifest, min_snr_db=10, max_snr_db=10, audio_tar_filepaths=str(gz_path))+ perturbation.rng = random.Random(0)++ with pytest.raises(ValueError, match="compressed archive"):+ _apply(perturbation, 1)+++@pytest.mark.parametrize("strategy", ["scatter", "replicate"])+def test_noise_with_normalization_respects_the_shard_partition(tmp_path, strategy, monkeypatch):+ # Two shards with distinct tones; under 'scatter' rank r must read only shard r.+ tones = {0: 300, 1: 900}+ tar_paths = []+ for shard, frequency in tones.items():+ tar_path = tmp_path / f"noise_{shard}.tar"+ _write_tar(tar_path, [(f"noise_{shard}.wav", _tone(frequency))])+ tar_paths.append(str(tar_path))+ manifest = _manifest(+ tmp_path / "manifest.json", [{"audio_filepath": f"noise_{shard}.wav", "duration": 1.2} for shard in tones]+ )+ opened = []+ original = perturb._open_indexed_tar+ monkeypatch.setattr(+ perturb, "_open_indexed_tar", lambda cls, path: opened.append(os.path.basename(path)) or original(cls, path)+ )++ def make(rank):+ return NoisePerturbationWithNormalization(+ [manifest],+ audio_tar_filepaths=[tar_paths],+ shuffle_n=1,+ global_rank=rank,+ world_size=2,+ shard_strategy=strategy,+ )++ for rank in [0, 1]:+ opened.clear()+ perturbation = make(rank)+ rng = random.Random(0)+ perturbation.rng = rng+ state = rng.getstate()+ noises = [perturbation.read_one_audiosegment(SAMPLE_RATE).samples for _ in range(12)]+ frequencies = {+ next(f for f in tones.values() if np.allclose(noise, _tone(f).astype(np.float32), atol=1e-4))+ for noise in noises+ }+ if strategy == "scatter":+ assert frequencies == {tones[rank]}+ assert set(opened) == {f"noise_{rank}.tar"}+ else:+ assert frequencies == set(tones.values())++ resumed = make(rank)+ restored = random.Random()+ restored.setstate(state)+ resumed.rng = restored+ for noise in noises:+ np.testing.assert_array_equal(resumed.read_one_audiosegment(SAMPLE_RATE).samples, noise)+++@pytest.mark.parametrize("checkpointed_rng", [False, True])+def test_eou_augmentor_with_compressed_tarred_noise(tmp_path, checkpointed_rng):+ # Existing (non-stateful) configurations with .tar.gz noise keep working through the sequential reader; with+ # checkpointed randomness enabled (use_stateful_dataloader=True) random access needs an uncompressed tar.+ from omegaconf import OmegaConf++ from nemo.collections.asr.data.audio_to_eou_label_lhotse import LhotseSpeechToTextBpeEOUDataset++ tar_path = tmp_path / "noise.tar"+ _write_tar(tar_path, [("noise_0.wav", _tone(300)), ("noise_1.wav", _tone(900))])+ gz_path = tmp_path / "noise.tar.gz"+ with open(tar_path, "rb") as src, gzip.open(gz_path, "wb") as dst:+ dst.write(src.read())+ manifest = _manifest(+ tmp_path / "manifest.json", [{"audio_filepath": f"noise_{i}.wav", "duration": 1.2} for i in range(2)]+ )+ cfg = {+ "check_tokenizer": False,+ "sample_rate": SAMPLE_RATE,+ "augmentor": {+ "noise": {+ "prob": 1.0,+ "manifest_path": manifest,+ "audio_tar_filepaths": str(gz_path),+ "min_snr_db": 10,+ "max_snr_db": 10,+ }+ },+ }+ dataset = LhotseSpeechToTextBpeEOUDataset(cfg=OmegaConf.create(cfg), tokenizer=None)+ if checkpointed_rng:+ dataset.enable_checkpointed_rng()+ audio = torch.from_numpy(_tone(440, 1.0).astype(np.float32))++ if checkpointed_rng:+ with pytest.raises(ValueError, match="compressed archive"):+ dataset._maybe_augment_audio(audio, torch.tensor(SAMPLE_RATE))+ else:+ augmented, augmented_len = dataset._maybe_augment_audio(audio, torch.tensor(SAMPLE_RATE))+ assert int(augmented_len) == SAMPLE_RATE+ assert not torch.equal(augmented, audio)tests/collections/common/test_lhotse_augmentation_resume.pyadded179 + / 0 −
@@ -0,0 +1,179 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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.+"""Noise mixing and RIR reverb must give bit-identical audio after a mid-stream StatefulDataLoader resume."""++import copy+import hashlib++import numpy as np+import pytest+import soundfile as sf+from lhotse import CutSet, Recording, RecordingSet+from lhotse.dataset.iterable_dataset import IdentityDataset+from omegaconf import OmegaConf++from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config++pytestmark = pytest.mark.unit+++def _wav_cuts(root, prefix, count, rng, duration=1.0):+ cuts = []+ for i in range(count):+ path = root / f"{prefix}_{i}.wav"+ sf.write(path, (0.1 * rng.standard_normal(int(16000 * duration))).astype(np.float32), 16000)+ cuts.append(Recording.from_file(path, recording_id=f"{prefix}_{i}").to_cut())+ return CutSet.from_cuts(cuts)+++@pytest.fixture(scope="module")+def data_dir(tmp_path_factory):+ """Speech and noise as Shar (tarred audio; noise also in an indexed variant), plus a RecordingSet of RIRs."""+ root = tmp_path_factory.mktemp("aug_resume")+ rng = np.random.default_rng(0)+ for name, count, shard_size in [("speech", 24, 8), ("noise", 12, 4), ("noise_a", 8, 4), ("noise_b", 8, 4)]:+ (root / name).mkdir()+ _wav_cuts(root, name, count, rng).to_shar(root / name, fields={"recording": "wav"}, shard_size=shard_size)+ (root / "noise_indexed").mkdir()+ _wav_cuts(root, "noise_indexed", 12, rng).to_shar(+ root / "noise_indexed", fields={"recording": "wav"}, shard_size=4, compress_jsonl=False, create_index=True+ )+ rir_recordings = []+ for i in range(4):+ path = root / f"rir_{i}.wav"+ sf.write(path, (rng.standard_normal(1600) * np.exp(-np.arange(1600) / 200.0)).astype(np.float32), 16000)+ rir_recordings.append(Recording.from_file(path))+ RecordingSet.from_recordings(rir_recordings).to_file(root / "rirs.jsonl")+ return root+++def _noise_path(data_dir, aug):+ if aug == "noise_blend":+ # A weighted blend of two equally sized sources.+ return {"shar_path": [[str(data_dir / "noise_a"), 90], [str(data_dir / "noise_b"), 10]]}+ if aug == "noise_bounded":+ # A blend read with at most one open stream at a time.+ return {"shar_path": [str(data_dir / "noise_a"), str(data_dir / "noise_b")], "max_open_streams": 1}+ return {"shar_path": str(data_dir / aug)}+++def _loader(data_dir, mode, num_workers, aug):+ """aug: "noise*" (noise mixing from Shar, see _noise_path) or "rir" (reverb with RIR recordings)."""+ cfg = {+ "shar_path": str(data_dir / "speech"),+ "batch_size": 2,+ "shuffle": True,+ # The speech source repeats indefinitely; a small shuffle buffer avoids mixing 10k cuts before batch 1.+ "shuffle_buffer_size": 32,+ "num_workers": num_workers,+ "seed": 1,+ "shard_seed": 1,+ "use_stateful_dataloader": True,+ "force_map_dataset": mode == "map",+ "force_iterable_dataset": mode == "iterable",+ "sample_rate": 16000,+ }+ if aug.startswith("noise"):+ cfg.update(noise_path=_noise_path(data_dir, aug), noise_mix_prob=1.0)+ else:+ cfg.update(rir_enabled=True, rir_prob=1.0, rir_path=str(data_dir / "rirs.jsonl"))+ return get_lhotse_dataloader_from_config(+ OmegaConf.create(cfg), global_rank=0, world_size=1, dataset=IdentityDataset()+ )+++def _take(data_dir, mode, num_workers, aug, num_batches, state=None):+ dloader = _loader(data_dir, mode, num_workers, aug)+ if state is not None:+ dloader.load_state_dict(state)+ it = iter(dloader)+ hashes = []+ for _ in range(num_batches):+ batch = next(it)+ hashes.append([hashlib.md5(np.ascontiguousarray(c.load_audio()).tobytes()).hexdigest() for c in batch])+ return hashes, copy.deepcopy(dloader.state_dict())+++@pytest.mark.parametrize(+ "aug,num_workers",+ [+ ("noise", 0),+ ("noise_indexed", 0),+ ("noise_blend", 0),+ ("noise_bounded", 0),+ ("rir", 0),+ ],+)+@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_augmented_audio_is_bit_identical_after_resume(data_dir, mode, num_workers, aug):+ uninterrupted, _ = _take(data_dir, mode, num_workers, aug, num_batches=6)+ _, state = _take(data_dir, mode, num_workers, aug, num_batches=2)+ resumed, _ = _take(data_dir, mode, num_workers, aug, num_batches=4, state=state)++ assert resumed == uninterrupted[2:]+++@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_weighted_noise_blend_keeps_its_source_weights(data_dir, mode):+ it = iter(_loader(data_dir, mode, 0, "noise_blend"))+ sources = []+ for _ in range(30):+ for cut in next(it):+ noise_track = cut.tracks[1]+ sources.append(noise_track.cut.recording_id.split("_")[1])++ share_a = sources.count("a") / len(sources)+ # 90:10 weights; an unweighted (or finite, exhausting) blend of equal sources would give about 0.5.+ assert share_a > 0.75+++@pytest.mark.parametrize("use_stateful_dataloader", [False, True])+def test_noise_shard_seed_follows_the_stateful_flag(data_dir, monkeypatch, use_stateful_dataloader):+ from nemo.collections.common.data.lhotse import dataloader++ calls = []++ def fake_guess_parse_cutset(inp, shard_seed=None):+ calls.append(shard_seed)+ return _wav_cuts(data_dir, "flag_noise", 2, np.random.default_rng(0), duration=0.5)++ monkeypatch.setattr(dataloader, "guess_parse_cutset", fake_guess_parse_cutset)+ cfg = {+ "shar_path": str(data_dir / "speech"),+ "batch_size": 2,+ "seed": 1,+ "shard_seed": 1234,+ "use_stateful_dataloader": use_stateful_dataloader,+ "noise_path": "unused",+ "sample_rate": 16000,+ }+ get_lhotse_dataloader_from_config(OmegaConf.create(cfg), global_rank=0, world_size=1, dataset=IdentityDataset())++ # Without the flag the noise keeps its own default shard_seed, as before.+ assert calls == [1234 if use_stateful_dataloader else None]+++def test_mixable_noise_only_changes_noise_that_cannot_be_mixed(data_dir):+ from nemo.collections.common.data.lhotse.dataloader import _mixable_noise, _StreamingNoise++ eager = _wav_cuts(data_dir, "eager_noise", 2, np.random.default_rng(0), duration=0.5)+ streamed = CutSet.from_shar(in_dir=data_dir / "noise")+ indexed_finite = CutSet.from_shar(in_dir=data_dir / "noise_indexed", indexed=True)+ indexed_infinite = indexed_finite.repeat()++ for noise in [eager, streamed, indexed_finite]:+ assert _mixable_noise(noise) is noise+ # Indexed noise without a length used to fail on the first mixed batch ("... is an infinite iterator").+ assert isinstance(_mixable_noise(indexed_infinite).data, _StreamingNoise)tests/collections/common/test_lhotse_dataloading_duplex.py68 + / 0 −
@@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import random from itertools import islice from pathlib import Path @@ -25,6 +26,7 @@ from omegaconf import OmegaConf from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config+from nemo.collections.common.data.lhotse.cutset import read_cutset_from_config class Identity(torch.utils.data.Dataset):@@ -355,3 +357,69 @@ def test_data_input_cfg_reverse_role_multi_config_with_workers(regular_duplex_s2 sups = sorted(cut.supervisions, key=lambda s: s.start) assert sups[0].speaker == "swapped_agent" assert sups[1].speaker == "swapped_user"+++def _extra_silence_config(shar_path, extra_end_silence_seed=None, add_extra_end_silence=True):+ item = {+ "type": "lhotse_magpietts_data_as_continuation",+ "shar_path": str(shar_path),+ "sample_rate": 22050,+ "add_extra_end_silence": add_extra_end_silence,+ "extra_end_silence_range": [0.5, 3.0],+ }+ if extra_end_silence_seed is not None:+ item["extra_end_silence_seed"] = extra_end_silence_seed+ return OmegaConf.create(+ {+ "input_cfg": [item],+ "sample_rate": 22050,+ "force_finite": True,+ "shuffle": False,+ "seed": 0,+ "shard_seed": 0,+ }+ )+++def _read_cuts(config):+ # Cut IDs of padded cuts are random, so compare in (unshuffled) input order.+ cuts, _ = read_cutset_from_config(config)+ return list(cuts)+++def test_magpietts_extra_end_silence_with_seed_is_a_function_of_the_cut(cutset_shar_magpietts_path):+ config = _extra_silence_config(cutset_shar_magpietts_path, extra_end_silence_seed=0)++ # A resumed run re-creates the cuts in a process whose global RNG state differs from the original run.+ random.seed(0)+ first = [cut.duration for cut in _read_cuts(config)]+ random.seed(1)+ second = [cut.duration for cut in _read_cuts(config)]++ assert len(first) == 5+ assert first == second+ # The extra silence is drawn per cut, not shared by all cuts.+ assert len(set(first)) > 1+++def test_magpietts_extra_end_silence_without_seed_uses_the_global_rng(cutset_shar_magpietts_path, monkeypatch):+ draws = iter([0.5, 1.5] * 5)+ monkeypatch.setattr(random, "uniform", lambda a, b: next(draws))+ config = _extra_silence_config(cutset_shar_magpietts_path)++ cuts = _read_cuts(config)++ # The source cuts are 2 s long; each read draws the next global value.+ assert [cut.duration for cut in cuts] == [2.5, 3.5, 2.5, 3.5, 2.5]+ for cut in cuts:+ user_sup, agent_sup = cut.supervisions+ silence = cut.duration - 2.0+ assert user_sup.duration == pytest.approx(0.08 + silence)+ assert agent_sup.duration == pytest.approx(2.0 - 0.08 + silence + 1.0)+++def test_magpietts_without_extra_end_silence_keeps_durations(cutset_shar_magpietts_path):+ cuts = _read_cuts(_extra_silence_config(cutset_shar_magpietts_path, add_extra_end_silence=False))++ assert [cut.duration for cut in cuts] == [2.0] * 5+ assert all(cut.supervisions[0].duration == pytest.approx(0.08) for cut in cuts)tests/collections/common/test_lhotse_nemo_tar_index.py17 + / 0 −
@@ -354,6 +354,23 @@ def test_validate_tar_member_index_layout_accepts_nemo_index(tmp_path, entries, assert build_indexes._is_indexed(build_indexes.IndexJob(str(tar_path), build_indexes.NEMO_TAR)) +@pytest.mark.unit+@pytest.mark.parametrize("tar_format", [tarfile.PAX_FORMAT, tarfile.GNU_FORMAT], ids=["pax", "gnu"])+def test_indexed_tar_member_reader_lists_every_regular_member_of_an_entry(tmp_path, tar_format):+ long_name = "d/" + "x" * 150 + ".wav"+ entries = [("noise.wav", b"0"), ("noise.wav", b"1"), ("empty/", None), (long_name, b"2")]+ tar_path = _write_tar(tmp_path / "audio_0.tar", entries, tar_format=tar_format)+ idx_path = tmp_path / "audio_0.tar.idx"+ create_tar_index(tar_path, idx_path)+ reader = IndexedTarMemberReader(tar_path, idx_path, auto_create_index=False)++ # Consecutive members with the same stem share one index entry; each of them is listed (names may repeat).+ names = [reader.regular_member_names(i) for i in range(len(reader))]+ reader.close()++ assert names == [["noise.wav", "noise.wav"], [long_name]]++ @pytest.mark.unit def test_build_indexes_keeps_valid_nemo_tar_index_with_directory_entries(tmp_path): tar_path = _write_tar(tmp_path / "audio_0.tar", [("utt0.wav", b"0"), ("empty/", None), ("utt1.wav", b"1")])tests/collections/common/test_lhotse_stateful_rng.pyadded333 + / 0 −
@@ -0,0 +1,333 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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 pickle+import random+from collections import defaultdict++import pytest+import torch+from lhotse import CutSet+from lhotse.dataset import SimpleCutSampler+from lhotse.testing.dummies import DummyManifest+from omegaconf import OmegaConf++from nemo.collections.common.data.fallback import FallbackDataset+from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config, stateful_rng+from nemo.collections.common.data.lhotse.stateful_rng import StatefulIterableDatasetWrapper, StatefulRandomMixin++pytestmark = pytest.mark.unit+++class _RandomDrawDataset(StatefulRandomMixin, torch.utils.data.Dataset):+ """Returns one random draw per cut (like a random crop offset), with the id of the producing worker."""++ def __getitem__(self, cuts: CutSet) -> list[tuple[str, int, float]]:+ worker_info = torch.utils.data.get_worker_info()+ worker_id = -1 if worker_info is None else worker_info.id+ return [(cut.id, worker_id, self.rng.random()) for cut in cuts]+++class _StatelessDataset(torch.utils.data.Dataset):+ def __getitem__(self, cuts: CutSet) -> list[str]:+ return [cut.id for cut in cuts]+++def _enabled() -> _RandomDrawDataset:+ dataset = _RandomDrawDataset()+ dataset.enable_checkpointed_rng()+ return dataset+++def test_rng_is_the_global_module_unless_enabled():+ dataset = _RandomDrawDataset()++ assert not dataset.checkpointed_rng_enabled+ assert dataset.rng is random+ assert dataset.state_dict() == {"rng_state": None}+ dataset.load_state_dict({"rng_state": None}) # a no-op+ assert dataset.rng is random+++def test_disabled_rng_rejects_saved_generator_state():+ state = _enabled().state_dict()++ with pytest.raises(RuntimeError, match="not enabled"):+ _RandomDrawDataset().load_state_dict(state)+++def test_rng_state_dict_round_trip():+ dataset = _enabled()+ dataset.rng.random()+ state = dataset.state_dict()+ expected = [dataset.rng.random() for _ in range(5)]++ restored = _enabled()+ restored.load_state_dict(pickle.loads(pickle.dumps(state)))++ assert [restored.rng.random() for _ in range(5)] == expected+++def test_rng_state_round_trip_keeps_cached_gaussian():+ dataset = _enabled()+ dataset.rng.gauss(0.0, 1.0) # an odd number of gauss() calls leaves the second value cached+ state = dataset.state_dict()+ expected = [dataset.rng.gauss(0.0, 1.0) for _ in range(3)]++ restored = _enabled()+ restored.load_state_dict(state)++ assert state["rng_state"]["gauss_next"] is not None+ assert [restored.rng.gauss(0.0, 1.0) for _ in range(3)] == expected+++def test_load_state_dict_restores_in_place():+ dataset = _enabled()+ holder = dataset.rng # e.g. a G2P module holding a reference to the dataset generator+ state = dataset.state_dict()+ expected = [dataset.rng.random() for _ in range(3)]++ dataset.load_state_dict(state)++ assert dataset.rng is holder+ assert [holder.random() for _ in range(3)] == expected+++def test_rng_state_dict_uses_plain_types():+ state = _enabled().state_dict()["rng_state"]+ assert isinstance(state["version"], int)+ assert isinstance(state["internal_state"], list)+ assert all(isinstance(x, int) for x in state["internal_state"])+++def test_rng_is_seeded_from_torch_initial_seed():+ torch.manual_seed(1)+ first = _enabled().rng.random()+ torch.manual_seed(1)+ same = _enabled().rng.random()+ torch.manual_seed(2)+ other = _enabled().rng.random()++ assert first == same+ assert first != other+++def test_rng_ignores_global_random_state():+ torch.manual_seed(1)+ random.seed(1)+ first = _enabled().rng.random()+ torch.manual_seed(1)+ random.seed(2)+ assert _enabled().rng.random() == first+++def test_rng_inherited_from_another_process_is_reseeded(monkeypatch):+ dataset = _enabled()+ parent_rng = dataset.rng+ monkeypatch.setattr(stateful_rng.os, "getpid", lambda: -1)++ assert dataset.rng is not parent_rng+++def test_iterable_wrapper_checkpoints_dataset_state():+ cuts = DummyManifest(CutSet, begin_id=0, end_id=10)+ wrapper = StatefulIterableDatasetWrapper(_enabled(), SimpleCutSampler(cuts, max_cuts=2))+ it = iter(wrapper)+ next(it)+ state = wrapper.state_dict()+ expected = list(it)++ restored = StatefulIterableDatasetWrapper(_enabled(), SimpleCutSampler(cuts, max_cuts=2))+ restored.load_state_dict(state)++ assert "dataset_state" in state+ assert list(iter(restored)) == expected+++def test_iterable_wrapper_accepts_checkpoint_without_dataset_state():+ cuts = DummyManifest(CutSet, begin_id=0, end_id=4)+ wrapper = StatefulIterableDatasetWrapper(_enabled(), SimpleCutSampler(cuts, max_cuts=2))+ state = wrapper.state_dict()+ del state["dataset_state"]++ wrapper.load_state_dict(state)++ assert len(list(iter(wrapper))) == 2+++def test_iterable_wrapper_raises_on_dataset_state_for_stateless_dataset():+ cuts = DummyManifest(CutSet, begin_id=0, end_id=4)+ state = StatefulIterableDatasetWrapper(_enabled(), SimpleCutSampler(cuts, max_cuts=2)).state_dict()+ wrapper = StatefulIterableDatasetWrapper(_StatelessDataset(), SimpleCutSampler(cuts, max_cuts=2))++ with pytest.raises(RuntimeError, match="does not implement load_state_dict"):+ wrapper.load_state_dict(state)+++@pytest.fixture(scope="module")+def cuts_path(tmp_path_factory):+ path = tmp_path_factory.mktemp("stateful_rng") / "cuts.jsonl.gz"+ DummyManifest(CutSet, begin_id=0, end_id=20).to_file(path)+ return path+++def _make_dataloader(+ cuts_path, mode: str, num_workers: int = 0, use_stateful_dataloader: bool = True, fallback: bool = False+):+ config = OmegaConf.create(+ {+ "cuts_path": str(cuts_path),+ "batch_size": 2,+ "shuffle": True,+ "use_bucketing": False,+ "num_workers": num_workers,+ "seed": 0,+ # On the iterable path every worker runs its own sampler over the (non-indexed) cuts, so the shuffle+ # needs a per-worker seed; an integer seed would give each worker the same stream.+ "shard_seed": "randomized" if mode == "iterable" else 0,+ "use_stateful_dataloader": use_stateful_dataloader,+ "force_map_dataset": mode == "map",+ "force_iterable_dataset": mode == "iterable",+ }+ )+ # Seed first so the generator initialized below doesn't depend on the ambient torch seed.+ torch.manual_seed(config.seed)+ dataset = _RandomDrawDataset()+ # Initialize the generator in the parent process, as a state_dict() or a diagnostic read before the loader+ # starts would. Dataloader workers must still each get their own stream.+ dataset.enable_checkpointed_rng()+ dataset.state_dict()+ if fallback:+ dataset = FallbackDataset(dataset)+ return get_lhotse_dataloader_from_config(config, global_rank=0, world_size=1, dataset=dataset)+++def _take(cuts_path, mode: str, num_batches: int, state=None, num_workers: int = 0, fallback: bool = False):+ dloader = _make_dataloader(cuts_path, mode, num_workers, fallback=fallback)+ if state is not None:+ dloader.load_state_dict(state)+ it = iter(dloader)+ batches = [next(it) for _ in range(num_batches)]+ return batches, dloader.state_dict()+++def test_builder_enables_checkpointed_rng_only_for_stateful_loader(cuts_path):+ assert _make_dataloader(cuts_path, "map").dataset.checkpointed_rng_enabled+ plain = _RandomDrawDataset()+ config = OmegaConf.create({"cuts_path": str(cuts_path), "batch_size": 2, "force_map_dataset": True})+ get_lhotse_dataloader_from_config(config, global_rank=0, world_size=1, dataset=plain)+ assert not plain.checkpointed_rng_enabled+++@pytest.mark.parametrize("num_workers", [0, 2])+@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_resumed_dataloader_reproduces_random_draws(cuts_path, mode, num_workers):+ uninterrupted, _ = _take(cuts_path, mode, num_batches=8, num_workers=num_workers)+ _, state = _take(cuts_path, mode, num_batches=3, num_workers=num_workers)+ resumed, _ = _take(cuts_path, mode, num_batches=5, state=state, num_workers=num_workers)++ assert resumed == uninterrupted[3:]+++@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_dataloader_workers_draw_independent_streams(cuts_path, mode):+ batches, _ = _take(cuts_path, mode, num_batches=4, num_workers=2)+ first_draws = {}+ for batch in batches:+ for _, worker_id, value in batch:+ first_draws.setdefault(worker_id, value)++ assert set(first_draws) == {0, 1}+ assert first_draws[0] != first_draws[1]+++@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_random_draws_differ_across_epochs(cuts_path, mode):+ dloader = _make_dataloader(cuts_path, mode)+ draws = defaultdict(list)+ for epoch in range(2):+ for batch in dloader:+ for cut_id, _, value in batch:+ draws[cut_id].append(value)++ assert len(draws) == 20+ assert all(len(values) == 2 and values[0] != values[1] for values in draws.values())+++@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_fallback_dataset_forwards_the_wrapped_dataset_state(cuts_path, mode):+ # FallbackDataset (EasyMagpie multiturn, speechlm2 datamodule) must not hide the wrapped dataset's generator.+ uninterrupted, _ = _take(cuts_path, mode, num_batches=8, fallback=True)+ _, state = _take(cuts_path, mode, num_batches=3, fallback=True)+ resumed, _ = _take(cuts_path, mode, num_batches=5, state=state, fallback=True)++ assert "rng_state" in str(state)+ assert resumed == uninterrupted[3:]+++@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_builder_seeds_the_generator_with_the_given_rank(cuts_path, mode, monkeypatch):+ # Dataloader workers started with spawn/forkserver may see neither RANK nor the process group, so+ # get_rank() returns 0 on every rank; the builder's global_rank must separate the ranks regardless.+ monkeypatch.setenv("RANK", "0")+ config = OmegaConf.create(+ {+ "cuts_path": str(cuts_path),+ "batch_size": 2,+ "shard_seed": "randomized",+ "use_stateful_dataloader": True,+ "force_map_dataset": mode == "map",+ "force_iterable_dataset": mode == "iterable",+ }+ )+ draws = {}+ for rank in [0, 1, 1]:+ dataset = _RandomDrawDataset()+ get_lhotse_dataloader_from_config(config, global_rank=rank, world_size=2, dataset=dataset)+ torch.manual_seed(0) # the same torch seed in the drawing process, as in equally seeded workers+ sequence = [dataset.rng.random() for _ in range(3)]+ assert draws.setdefault(rank, sequence) == sequence # deterministic for a given rank++ assert draws[0] != draws[1]+++def test_explicit_rank_overrides_the_environment(monkeypatch):+ monkeypatch.setenv("RANK", "0")+ torch.manual_seed(0)+ from_env = stateful_rng.process_seeded_rng().random()+ torch.manual_seed(0)+ rank_0 = stateful_rng.process_seeded_rng(rank=0).random()+ torch.manual_seed(0)+ rank_1 = stateful_rng.process_seeded_rng(rank=1).random()++ assert from_env == rank_0+ assert rank_1 != rank_0+++def test_builder_enables_checkpointed_rng_through_fallback_dataset(cuts_path):+ inner = _RandomDrawDataset()+ config = OmegaConf.create(+ {"cuts_path": str(cuts_path), "batch_size": 2, "force_map_dataset": True, "use_stateful_dataloader": True}+ )+ get_lhotse_dataloader_from_config(config, global_rank=0, world_size=1, dataset=FallbackDataset(inner))++ assert inner.checkpointed_rng_enabled+++def test_fallback_dataset_with_stateless_dataset_has_empty_state():+ wrapper = FallbackDataset(_StatelessDataset())++ assert wrapper.state_dict() == {}+ wrapper.load_state_dict({})tests/collections/tts/data/test_audio_codec_dataset_lhotse.py69 + / 4 −
@@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import random from pathlib import Path import lhotse@@ -21,6 +22,8 @@ import soundfile as sf import torch from lhotse import CutSet+from lhotse.dataset import SimpleCutSampler+from torchdata.stateful_dataloader import StatefulDataLoader from nemo.collections.tts.data.audio_codec_dataset_lhotse import AudioCodecLhotseDataset @@ -85,6 +88,12 @@ def cutset(tmp_path) -> CutSet: return CutSet.from_cuts(cuts) +def _checkpointed_dataset() -> AudioCodecLhotseDataset:+ dataset = AudioCodecLhotseDataset(sample_rate=TARGET_SAMPLE_RATE, segment_duration=0.25)+ dataset.enable_checkpointed_rng()+ return dataset++ @pytest.fixture() def dataset() -> AudioCodecLhotseDataset: return AudioCodecLhotseDataset(@@ -153,10 +162,7 @@ def test_getitem_extracts_subset_of_longer_audio(self, tmp_path, dataset, monkey # Pin the random start so we can compare against the exact source slice. fixed_start = 7000- monkeypatch.setattr(- "nemo.collections.tts.data.audio_codec_dataset_lhotse.random.randint",- lambda low, high: fixed_start,- )+ monkeypatch.setattr(dataset.rng, "randint", lambda low, high: fixed_start) batch = dataset[cuts] segment = batch["audio"][0].numpy()@@ -167,3 +173,62 @@ def test_getitem_extracts_subset_of_longer_audio(self, tmp_path, dataset, monkey # dataset currently applies no augmentation. Once we add augmentation it makes # sense to remove this assertion. assert np.allclose(segment, full[fixed_start : fixed_start + segment_samples])++ @pytest.mark.unit+ def test_crops_use_the_global_rng_unless_checkpointed_rng_is_enabled(self, cutset):+ # Legacy behaviour: without use_stateful_dataloader the crop follows the global ``random`` module.+ dataset = AudioCodecLhotseDataset(sample_rate=TARGET_SAMPLE_RATE, segment_duration=0.25)+ random.seed(0)+ first = dataset[cutset]["audio"]+ random.seed(0)+ second = dataset[cutset]["audio"]++ assert not dataset.checkpointed_rng_enabled+ torch.testing.assert_close(first, second)++ @pytest.mark.unit+ def test_restored_rng_state_reproduces_segments(self, cutset):+ dataset = _checkpointed_dataset()+ dataset.rng.seed(0)+ _ = dataset[cutset]+ state = dataset.state_dict()+ expected = dataset[cutset]["audio"]++ restored = _checkpointed_dataset()+ restored.load_state_dict(state)++ torch.testing.assert_close(restored[cutset]["audio"], expected)++ @pytest.mark.unit+ def test_segments_differ_when_cuts_are_read_again(self, cutset):+ dataset = _checkpointed_dataset()+ dataset.rng.seed(0)+ first = dataset[cutset]["audio"]+ second = dataset[cutset]["audio"]++ assert not torch.equal(first, second)++ @pytest.mark.unit+ def test_stateful_dataloader_resume_reproduces_segments(self, cutset):+ def make_loader():+ dataset = _checkpointed_dataset()+ sampler = SimpleCutSampler(cutset, max_cuts=1, shuffle=True, seed=0)+ return StatefulDataLoader(dataset, sampler=sampler, batch_size=None, num_workers=0)++ torch.manual_seed(0)+ uninterrupted = [batch["audio"] for batch in make_loader()]++ torch.manual_seed(0)+ loader = make_loader()+ it = iter(loader)+ next(it)+ state = loader.state_dict()++ torch.manual_seed(1) # the resumed process does not share the global RNG state+ loader = make_loader()+ loader.load_state_dict(state)+ resumed = [batch["audio"] for batch in loader]++ assert len(resumed) == len(uninterrupted) - 1+ for actual, expected in zip(resumed, uninterrupted[1:]):+ torch.testing.assert_close(actual, expected)tests/collections/tts/data/test_magpietts_dataset_lhotse.py357 + / 1 −
@@ -14,6 +14,7 @@ # limitations under the License. import json+import os import random from io import BytesIO @@ -27,9 +28,15 @@ from lhotse.testing.dummies import dummy_cut, dummy_recording from omegaconf import OmegaConf +from nemo.collections.common.tokenizers.text_to_speech.tts_tokenizers import AggregatedTTSTokenizer, IPATokenizer from nemo.collections.tts.data.text_to_speech_dataset import MagpieTTSDataset from nemo.collections.tts.data.text_to_speech_dataset_lhotse import MagpieTTSLhotseDataset-from nemo.collections.tts.data.text_to_speech_dataset_lhotse_multiturn import MagpieTTSLhotseMultiturnDataset+from nemo.collections.tts.data.text_to_speech_dataset_lhotse_multiturn import (+ MagpieTTSLhotseMultiturnDataset,+ collate_phoneme_channel,+ collate_token_channel,+)+from nemo.collections.tts.g2p.models.i18n_ipa import IpaG2p pytestmark = pytest.mark.unit@@ -553,3 +560,352 @@ def test_multiturn_fallback_uses_target_turn_audio_when_cached_codes_are_unavail ) assert context_audio_codes is None torch.testing.assert_close(context_audio, torch.from_numpy(expected))+++def _dataset_with_fake_tokenizers(dataset_class):+ kwargs = _dataset_kwargs()+ kwargs.update(+ {+ "use_text_conditioning_tokenizer": False,+ "context_duration_min": 0.1,+ "context_duration_max": 0.6,+ }+ )+ if dataset_class is MagpieTTSLhotseMultiturnDataset:+ kwargs.update(+ {+ "codec_model_input_sample_rate": CODEC_MODEL_INPUT_SAMPLE_RATE,+ "frame_stacking_factor": FRAME_STACKING_FACTOR,+ "source_sample_rate": SAMPLE_RATE,+ "input_roles": ["user"],+ "output_roles": ["assistant"],+ "add_text_bos": False,+ }+ )+ dataset = dataset_class(**kwargs)+ dataset.enable_checkpointed_rng()+ dataset.text_tokenizer = _FakeTextTokenizer()+ dataset.bos_id = len(dataset.text_tokenizer.tokens)+ dataset.eos_id = dataset.bos_id + 1+ dataset.cfg_unk_token_id = dataset.bos_id + 2+ dataset.interruption_token_id = dataset.bos_id + 3+ dataset.pad_id = dataset.text_tokenizer.pad+ return dataset+++def _cutset_with_long_context(dataset_class):+ cuts = _multiturn_cutset() if dataset_class is MagpieTTSLhotseMultiturnDataset else _single_turn_cutset()+ cut = next(iter(cuts))+ # 40 codec frames (0.8 s) of context, so that context slicing has to pick a random duration and offset.+ cut.context_codes = _memory_temporal_array(_cached_codes(num_frames=40))+ return cuts+++def _assert_batches_equal(actual, expected):+ assert actual.keys() == expected.keys()+ for key, value in expected.items():+ if isinstance(value, torch.Tensor):+ torch.testing.assert_close(actual[key], value, msg=key)+ else:+ assert actual[key] == value, key+++@pytest.mark.parametrize("dataset_class", [MagpieTTSLhotseDataset, MagpieTTSLhotseMultiturnDataset])+class TestMagpieTTSLhotseDatasetRNG:+ def test_restored_rng_state_reproduces_batches(self, dataset_class):+ cuts = _cutset_with_long_context(dataset_class)+ dataset = _dataset_with_fake_tokenizers(dataset_class)+ dataset.rng.seed(0)+ _ = dataset[cuts]+ state = dataset.state_dict()+ expected = [dataset[cuts] for _ in range(3)]++ # A resumed process does not share the global RNG state of the original one.+ random.seed(1234)+ np.random.seed(1234)+ restored = _dataset_with_fake_tokenizers(dataset_class)+ restored.load_state_dict(state)++ for expected_batch in expected:+ _assert_batches_equal(restored[cuts], expected_batch)++ def test_context_slice_differs_when_cut_is_read_again(self, dataset_class):+ cuts = _cutset_with_long_context(dataset_class)+ dataset = _dataset_with_fake_tokenizers(dataset_class)+ dataset.rng.seed(0)++ contexts = [tuple(dataset[cuts]["context_audio_codes"].flatten().tolist()) for _ in range(5)]++ assert len(set(contexts)) > 1++ def test_global_rng_is_used_unless_checkpointed_rng_is_enabled(self, dataset_class):+ # Legacy behaviour: without use_stateful_dataloader the draws follow the global ``random`` module.+ cuts = _cutset_with_long_context(dataset_class)+ dataset = _dataset_with_fake_tokenizers(dataset_class)+ dataset._checkpointed_rng_enabled = False++ random.seed(0)+ first = dataset[cuts]["context_audio_codes"]+ random.seed(0)+ second = dataset[cuts]["context_audio_codes"]++ assert dataset.rng is random+ torch.testing.assert_close(first, second)+++def _normalized_multiturn_cutset():+ cuts = _multiturn_cutset()+ for supervision in next(iter(cuts)).supervisions:+ supervision.custom = {**(supervision.custom or {}), "normalized_text": f"normalized {supervision.text}"}+ return cuts+++def _collate_tokens(**kwargs):+ tokens, lens = collate_token_channel(+ _normalized_multiturn_cutset(),+ _FakeTextTokenizer(),+ 0.04,+ roles={"assistant"},+ pad_id=0,+ eos_id=1,+ bos_id=2,+ interruption_token_id=3,+ load_normalized_text_percent=0.5,+ **kwargs,+ )+ return tokens.tolist(), lens.tolist()+++def _collate_phonemes(**kwargs):+ tokens, lens, dropout = collate_phoneme_channel(+ _multiturn_cutset(),+ _FakeIPATokenizer(),+ 0.04,+ roles={"assistant"},+ ignore_phoneme_languages=[],+ phoneme_turn_dropout_batch_prob=0.5,+ phoneme_turn_dropout_turn_prob=0.5,+ apply_turn_dropout=True,+ **kwargs,+ )+ return tokens.tolist(), lens.tolist(), dropout.tolist()+++@pytest.mark.parametrize("collate", [_collate_tokens, _collate_phonemes])+def test_multiturn_channel_helpers_default_to_the_global_rng(collate):+ random.seed(0)+ without_rng = [collate() for _ in range(8)]+ random.seed(0)+ with_global_module = [collate(rng=random) for _ in range(8)]++ assert without_rng == with_global_module+++@pytest.mark.parametrize("collate", [_collate_tokens, _collate_phonemes])+def test_multiturn_channel_helpers_draw_from_injected_rng(collate):+ random.seed(0)+ first = [collate(rng=random.Random(5)) for _ in range(8)]+ random.seed(1)+ second = [collate(rng=random.Random(5)) for _ in range(8)]+ many = [collate(rng=random.Random(seed)) for seed in range(16)]++ assert first == second+ # The draws matter: different generators give different channels.+ assert len({str(out) for out in many}) > 1+++G2P_PHONEME_DICT_PATH = os.path.join(+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "g2p", "phoneme_dict", "test_dict_en.txt"+)+G2P_TEXT = " ".join(["hello world nvidia jones airport"] * 4)+++def _g2p_tokenizer():+ """A real IPA tokenizer whose G2P keeps each word as graphemes with probability 0.5."""+ g2p = IpaG2p(+ G2P_PHONEME_DICT_PATH,+ locale="en-US",+ use_chars=True,+ phoneme_probability=0.5,+ apply_to_oov_word=lambda x: x,+ )+ return AggregatedTTSTokenizer([IPATokenizer(g2p=g2p, locale="en-US")], ["english_phoneme"])+++def _single_turn_dataset_with_g2p():+ dataset = _dataset_with_fake_tokenizers(MagpieTTSLhotseDataset)+ dataset.text_tokenizer = _g2p_tokenizer()+ dataset.bos_id = len(dataset.text_tokenizer.tokens)+ dataset.eos_id = dataset.bos_id + 1+ dataset.pad_id = dataset.text_tokenizer.pad+ return dataset+++def _g2p_cutset(dataset_class=MagpieTTSLhotseDataset):+ cuts = _cutset_with_long_context(dataset_class)+ cut = next(iter(cuts))+ cut.tokenizer_names = ["english_phoneme"]+ # The multiturn token channel is frame-aligned, so its turns only fit a short text.+ text = G2P_TEXT if dataset_class is MagpieTTSLhotseDataset else "hello jones"+ for supervision in cut.supervisions:+ supervision.text = text+ supervision.custom = {k: v for k, v in (supervision.custom or {}).items() if k not in ("ipa", "ipa_alignment")}+ supervision.normalized_text = text+ return cuts+++def _multiturn_dataset_with_g2p():+ dataset = _dataset_with_fake_tokenizers(MagpieTTSLhotseMultiturnDataset)+ dataset.text_tokenizer = _g2p_tokenizer()+ dataset.bos_id = len(dataset.text_tokenizer.tokens)+ dataset.eos_id = dataset.bos_id + 1+ dataset.cfg_unk_token_id = dataset.bos_id + 2+ dataset.interruption_token_id = dataset.bos_id + 3+ dataset.pad_id = dataset.text_tokenizer.pad+ return dataset+++_G2P_DATASETS = {+ MagpieTTSLhotseDataset: _single_turn_dataset_with_g2p,+ MagpieTTSLhotseMultiturnDataset: _multiturn_dataset_with_g2p,+}+++@pytest.mark.parametrize("dataset_class", [MagpieTTSLhotseDataset, MagpieTTSLhotseMultiturnDataset])+class TestMagpieTTSDatasetG2pRNG:+ def test_lhotse_dataset_restores_g2p_draws(self, dataset_class):+ cuts = _g2p_cutset(dataset_class)+ make_dataset = _G2P_DATASETS[dataset_class]+ dataset = make_dataset()+ dataset.rng.seed(0) # a fixed sequence that picks both pronunciations+ _ = dataset[cuts]+ state = dataset.state_dict()+ expected = [dataset[cuts]["text"] for _ in range(3)]++ # A resumed process starts with different global and torch RNG states.+ random.seed(1234)+ torch.manual_seed(1234)+ restored = make_dataset()+ restored.load_state_dict(state)++ for expected_text in expected:+ torch.testing.assert_close(restored[cuts]["text"], expected_text)+ # phoneme_probability=0.5 makes the tokens vary between reads.+ assert len({tuple(text.flatten().tolist()) for text in expected}) > 1++ def test_g2p_keeps_its_own_generator_unless_checkpointed_rng_is_enabled(self, dataset_class):+ cuts = _g2p_cutset(dataset_class)+ dataset = _G2P_DATASETS[dataset_class]()+ dataset._checkpointed_rng_enabled = False+ g2p = dataset.text_tokenizer.tokenizers["english_phoneme"].g2p+ own_rng = g2p.rng++ _ = dataset[cuts]++ assert g2p.rng is own_rng+++def _g2p_tokenizer_config():+ """Config for a lazily constructed real IPA tokenizer whose G2P keeps words as graphemes with probability 0.5."""+ return OmegaConf.create(+ {+ "english_phoneme": {+ "_target_": "nemo.collections.common.tokenizers.text_to_speech.tts_tokenizers.IPATokenizer",+ "locale": "en-US",+ "g2p": {+ "_target_": "nemo.collections.tts.g2p.models.i18n_ipa.IpaG2p",+ "phoneme_dict": G2P_PHONEME_DICT_PATH,+ "locale": "en-US",+ "use_chars": True,+ "phoneme_probability": 0.5,+ },+ }+ }+ )+++def _g2p_loader_cuts(dataset_class, num_cuts=6):+ from lhotse.utils import fastcopy++ template = next(iter(_g2p_cutset(dataset_class)))+ return CutSet.from_cuts(fastcopy(template, id=f"g2p-{i}") for i in range(num_cuts))+++def _g2p_loader(dataset_class, mode):+ from unittest.mock import patch++ from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config++ kwargs = _dataset_kwargs()+ kwargs.update(+ {+ "use_text_conditioning_tokenizer": False,+ "context_duration_min": 0.1,+ "context_duration_max": 0.6,+ "tokenizer_config": _g2p_tokenizer_config(),+ }+ )+ if dataset_class is MagpieTTSLhotseMultiturnDataset:+ kwargs.update(+ {+ "codec_model_input_sample_rate": CODEC_MODEL_INPUT_SAMPLE_RATE,+ "frame_stacking_factor": FRAME_STACKING_FACTOR,+ "source_sample_rate": SAMPLE_RATE,+ "input_roles": ["user"],+ "output_roles": ["assistant"],+ "add_text_bos": False,+ }+ )+ config = OmegaConf.create(+ {+ "batch_size": 2,+ "shuffle": True,+ "seed": 0,+ "shard_seed": 0,+ "num_workers": 0,+ "use_stateful_dataloader": True,+ "force_map_dataset": mode == "map",+ "force_iterable_dataset": mode == "iterable",+ }+ )+ # Note: the tokenizer is not set here; the dataset builds it lazily on its first read.+ with patch(+ "nemo.collections.common.data.lhotse.dataloader.read_cutset_from_config",+ return_value=(_g2p_loader_cuts(dataset_class), False),+ ):+ return get_lhotse_dataloader_from_config(config, global_rank=0, world_size=1, dataset=dataset_class(**kwargs))+++def _summarize_g2p_batch(batch):+ return (batch["text"].tolist(), batch["text_lens"].tolist(), batch["context_audio_codes"].tolist())+++@pytest.mark.parametrize("restore_into", ["fresh_loader", "initialized_loader"])+@pytest.mark.parametrize("mode", ["map", "iterable"])+@pytest.mark.parametrize("dataset_class", [MagpieTTSLhotseDataset, MagpieTTSLhotseMultiturnDataset])+def test_stateful_loader_restores_lazily_built_g2p_draws(dataset_class, mode, restore_into):+ torch.manual_seed(0)+ uninterrupted = [_summarize_g2p_batch(batch) for batch in _g2p_loader(dataset_class, mode)]+ loader = _g2p_loader(dataset_class, mode)+ it = iter(loader)+ _ = next(it)+ state = loader.state_dict()++ # A resumed process starts with different global and torch RNG states.+ random.seed(1234)+ torch.manual_seed(1234)+ if restore_into == "fresh_loader":+ # The checkpoint is restored before the dataset has built its tokenizer.+ resumed_loader = _g2p_loader(dataset_class, mode)+ else:+ # The checkpoint is restored into a loader whose dataset already built (and bound) its tokenizer.+ resumed_loader = _g2p_loader(dataset_class, mode)+ _ = next(iter(resumed_loader))+ resumed_loader.load_state_dict(state)+ resumed = [_summarize_g2p_batch(batch) for batch in resumed_loader]++ assert len(uninterrupted) == 3+ assert resumed == uninterrupted[1:]+ # phoneme_probability=0.5 chooses different pronunciations for the identical texts.+ texts = {tuple(row) for text, _, _ in uninterrupted for row in text}+ assert len(texts) > 1tests/collections/tts/g2p/test_g2p_rng.pyadded156 + / 0 −
@@ -0,0 +1,156 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# 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 os+import random+from types import SimpleNamespace++import pytest+import torch++from nemo.collections.common.data.lhotse.stateful_rng import process_seeded_rng+from nemo.collections.common.tokenizers.text_to_speech.tts_tokenizers import AggregatedTTSTokenizer, IPATokenizer+from nemo.collections.tts.g2p.models import base as g2p_base+from nemo.collections.tts.g2p.models.en_us_arpabet import EnglishG2p+from nemo.collections.tts.g2p.models.i18n_ipa import IpaG2p+from nemo.collections.tts.parts.utils.tts_dataset_utils import set_g2p_rng++pytestmark = pytest.mark.unit++PHONEME_DICT_PATH_EN = os.path.join(os.path.dirname(os.path.abspath(__file__)), "phoneme_dict", "test_dict_en.txt")+TEXT = " ".join(["hello world nvidia jones airport"] * 8)+++def _ipa_g2p():+ return IpaG2p(+ PHONEME_DICT_PATH_EN, locale="en-US", use_chars=True, phoneme_probability=0.5, apply_to_oov_word=lambda x: x+ )+++def _arpabet_g2p():+ phoneme_dict = {+ "hello": [["HH", "AH0", "L", "OW1"]],+ "world": [["W", "ER1", "L", "D"]],+ "nvidia": [["EH0", "N", "V", "IH1", "D", "IY0", "AH0"]],+ "jones": [["JH", "OW1", "N", "Z"]],+ "airport": [["EH1", "R", "P", "AO2", "R", "T"]],+ }+ return EnglishG2p(phoneme_dict=phoneme_dict, phoneme_probability=0.5, apply_to_oov_word=lambda x: x)+++@pytest.fixture(params=[_ipa_g2p, _arpabet_g2p], ids=["IpaG2p", "EnglishG2p"])+def make_g2p(request):+ return request.param+++def _phonemize(g2p, times: int = 3):+ return [tuple(map(str, g2p(TEXT))) for _ in range(times)]+++def test_default_rng_is_an_unseeded_private_generator(make_g2p, monkeypatch):+ # Legacy behaviour: each G2P draws from its own unseeded random.Random().+ created = []++ class _RecordingRandom(random.Random):+ def __init__(self, *args):+ created.append(args)+ super().__init__(*args)++ monkeypatch.setattr(g2p_base.random, "Random", _RecordingRandom)+ g2p = make_g2p()+ _phonemize(g2p)++ assert created == [()]+ assert isinstance(g2p.rng, _RecordingRandom)+++def test_explicitly_seeded_rng_is_reproducible(make_g2p):+ torch.manual_seed(0)+ random.seed(0)+ first_g2p = make_g2p()+ first_g2p.rng = process_seeded_rng("g2p:")+ first = _phonemize(first_g2p)+ torch.manual_seed(0)+ random.seed(1) # the global RNG plays no part+ second_g2p = make_g2p()+ second_g2p.rng = process_seeded_rng("g2p:")+ second = _phonemize(second_g2p)++ assert first == second+ # phoneme_probability=0.5 keeps some words as graphemes, so the output varies between calls.+ assert len(set(first)) > 1+++def test_injected_rng_drives_phoneme_probability(make_g2p):+ g2p = make_g2p()+ g2p.rng = random.Random(1)+ expected = _phonemize(g2p)++ torch.manual_seed(123) # the default per-process seed plays no part either+ other = make_g2p()+ other.rng = random.Random(1)++ assert _phonemize(other) == expected+++def test_rng_from_another_process_is_replaced(make_g2p, monkeypatch):+ g2p = make_g2p()+ injected = random.Random(1)+ g2p.rng = injected+ assert g2p.rng is injected++ monkeypatch.setattr(g2p_base.os, "getpid", lambda: -1)++ assert g2p.rng is not injected+++def test_set_g2p_rng_reaches_aggregated_tokenizers():+ g2p = _ipa_g2p()+ tokenizer = AggregatedTTSTokenizer([IPATokenizer(g2p=g2p, locale="en-US")], ["english_phoneme"])+ rng = random.Random(0)++ set_g2p_rng(tokenizer, rng)+ set_g2p_rng(None, rng) # tokenizers that are not configured are skipped++ assert g2p.rng is rng+++def test_set_g2p_rng_reaches_tokenizers_in_a_list():+ g2p = _ipa_g2p()+ container = SimpleNamespace(tokenizers=[IPATokenizer(g2p=g2p, locale="en-US")])+ rng = random.Random(0)++ set_g2p_rng(container, rng)++ assert g2p.rng is rng+++def test_set_g2p_rng_warns_once_about_skipped_g2p(monkeypatch):+ from nemo.collections.tts.parts.utils import tts_dataset_utils++ warnings = []+ monkeypatch.setattr(tts_dataset_utils.logging, "warning", lambda msg, *args: warnings.append(msg))+ monkeypatch.setattr(tts_dataset_utils, "_G2P_RNG_SKIP_WARNED", set())++ class _CustomG2p:+ def __call__(self, text):+ return list(text)++ tokenizer = SimpleNamespace(g2p=_CustomG2p())+ set_g2p_rng(tokenizer, random.Random(0))+ set_g2p_rng(tokenizer, random.Random(0))++ assert len(warnings) == 1+ assert "_CustomG2p" in warnings[0]tests/collections/tts/models/test_easy_magpietts.py75 + / 0 −
@@ -665,3 +665,78 @@ def test_multiturn_lhotse_dataloader_omits_alignment_prior(): assert batch['agent_mask'].sum().item() > 0 # Ensure the alignment prior is not present assert 'align_prior_matrix' not in batch+++@pytest.mark.parametrize("mode", ["map", "iterable"])+def test_multiturn_lhotse_dataloader_resumes_random_context_slices(mode):+ """The multiturn loader must expose the dataset RNG to StatefulDataLoader so resumed batches match exactly."""+ from lhotse import CutSet+ from lhotse.utils import fastcopy++ from tests.collections.tts.data.test_magpietts_dataset_lhotse import _cached_codes, _memory_temporal_array++ with torch.device('cpu'):+ cfg = tiny_easy_magpie_cfg(+ {'use_bpe_char_tokenizer': False, 'load_cached_codes_if_available': True, 'use_multiturn_dataset': True}+ )+ cfg.text_tokenizers = {+ 'english_char': {+ '_target_': 'nemo.collections.common.tokenizers.text_to_speech.tts_tokenizers.EnglishCharsTokenizer'+ }+ }+ cfg.text_conditioning_tokenizer_name = 'english_char'+ cfg.context_duration_min = 0.1+ cfg.context_duration_max = 0.6+ model = _make_easy_magpie_model(cfg)++ template = next(iter(_multiturn_cutset()))+ cuts = []+ for i in range(6):+ cut = fastcopy(template, id=f"multiturn-{i}")+ cut.tokenizer_names = ['english_char']+ # 40 codec frames of distinguishable context, so each read slices a random duration and offset.+ cut.context_codes = _memory_temporal_array(_cached_codes(num_frames=40, offset=i))+ cuts.append(cut)+ cuts = CutSet.from_cuts(cuts)+ dataset_cfg = OmegaConf.create(+ {+ 'use_lhotse': True,+ 'volume_norm': False,+ 'dataset': {+ 'batch_size': 2,+ 'shuffle': True,+ 'seed': 0,+ 'shard_seed': 0,+ 'num_workers': 0,+ 'use_stateful_dataloader': True,+ 'force_map_dataset': mode == 'map',+ 'force_iterable_dataset': mode == 'iterable',+ },+ }+ )++ def make_loader():+ with patch(+ 'nemo.collections.common.data.lhotse.dataloader.read_cutset_from_config', return_value=(cuts, False)+ ):+ model.setup_training_data(dataset_cfg)+ return model.train_dataloader()++ def summarize(batch):+ return (+ list(batch['sample_id']),+ batch['context_audio_codes'].tolist(),+ batch['context_audio_codes_lens'].tolist(),+ )++ uninterrupted = [summarize(batch) for batch in make_loader()]+ loader = make_loader()+ it = iter(loader)+ next(it)+ state = loader.state_dict()+ loader = make_loader()+ loader.load_state_dict(state)+ resumed = [summarize(batch) for batch in loader]++ assert len(uninterrupted) == 3+ assert resumed == uninterrupted[1:]tests/collections/tts/parts/utils/test_tts_dataset_utils.py23 + / 18 −
@@ -13,7 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +import random from pathlib import Path+from types import SimpleNamespace import librosa import numpy as np@@ -68,24 +70,22 @@ class TestTTSDatasetUtils: ) @pytest.mark.run_only_on('CPU') @pytest.mark.unit- def test_select_text_for_tts_input(self, monkeypatch, load_normalized_text_percent, random_value, expected_text):+ def test_select_text_for_tts_input(self, load_normalized_text_percent, random_value, expected_text): if random_value is None:- monkeypatch.setattr(- tts_dataset_utils.random,- "random",- lambda: pytest.fail("Endpoint probabilities should not sample the random number generator"),+ rng = SimpleNamespace(+ random=lambda: pytest.fail("Endpoint probabilities should not sample the random number generator") ) else:- monkeypatch.setattr(tts_dataset_utils.random, "random", lambda: random_value)+ rng = SimpleNamespace(random=lambda: random_value) - text = _select_text_for_tts_input("raw", "normalized", load_normalized_text_percent)+ text = _select_text_for_tts_input("raw", "normalized", load_normalized_text_percent, rng=rng) assert text == expected_text @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_select_text_for_tts_input_falls_back_when_normalized_text_is_missing(self):- assert _select_text_for_tts_input("raw", None, 1.0) == "raw"+ assert _select_text_for_tts_input("raw", None, 1.0, rng=random.Random(0)) == "raw" @pytest.mark.run_only_on('CPU') @pytest.mark.unit@@ -525,14 +525,15 @@ def test_partially_phonemize_text_uses_full_ipa_for_full_portion(self): ipa_alignment=[[0, 2, "hi", "ab"], [3, 6, "how", "c"]], partial_phoneme_portion=1.0, full_ipa_text="ab c",+ rng=random.Random(0), ) assert text == "<bop>ab c<eop>" @pytest.mark.run_only_on('CPU') @pytest.mark.unit- def test_partially_phonemize_text_samples_exact_portion(self, monkeypatch):- monkeypatch.setattr(tts_dataset_utils.random, "sample", lambda population, count: [0, 2])+ def test_partially_phonemize_text_samples_exact_portion(self):+ rng = SimpleNamespace(sample=lambda population, count: [0, 2]) text = partially_phonemize_text( text="one two three four",@@ -544,14 +545,15 @@ def test_partially_phonemize_text_samples_exact_portion(self, monkeypatch): ], partial_phoneme_portion=0.5, full_ipa_text="a b c d",+ rng=rng, ) assert text == "<bop>a<eop> two <bop>c<eop> four" @pytest.mark.run_only_on('CPU') @pytest.mark.unit- def test_partially_phonemize_text_merges_adjacent_words(self, monkeypatch):- monkeypatch.setattr(tts_dataset_utils.random, "sample", lambda population, count: [1, 2])+ def test_partially_phonemize_text_merges_adjacent_words(self):+ rng = SimpleNamespace(sample=lambda population, count: [1, 2]) text = partially_phonemize_text( text="one two three four",@@ -563,6 +565,7 @@ def test_partially_phonemize_text_merges_adjacent_words(self, monkeypatch): ], partial_phoneme_portion=0.5, full_ipa_text="a b c d",+ rng=rng, ) assert text == "one <bop>b c<eop> four"@@ -577,15 +580,16 @@ def test_partially_phonemize_text_skips_unmatched_full_ipa(self): ipa_alignment=[[0, 3, "one", "a"], [4, 7, "two", "b"], [8, 13, "three", "c"]], partial_phoneme_portion=0.5, full_ipa_text="unmatched",+ rng=random.Random(0), ) assert phonemized_text == text @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_partially_phonemize_text_without_alignment_is_noop(self):- assert partially_phonemize_text("hello", None, 1.0) == "hello"- assert partially_phonemize_text("hello", [], 1.0) == "hello"+ assert partially_phonemize_text("hello", None, 1.0, rng=random.Random(0)) == "hello"+ assert partially_phonemize_text("hello", [], 1.0, rng=random.Random(0)) == "hello" @pytest.mark.run_only_on('CPU') @pytest.mark.unit@@ -595,6 +599,7 @@ def test_full_ipa_span_tokens_match_phoneme_channel_tokens(self): ipa_alignment=[[0, 5, "hello", "ab"], [6, 11, "world", "c"]], partial_phoneme_portion=1.0, full_ipa_text="ab c",+ rng=random.Random(0), ) phoneme_tokenizer = _FakePhonemeTokenizer() tokens = tokenize_text_with_phoneme_spans(@@ -610,16 +615,16 @@ def test_full_ipa_span_tokens_match_phoneme_channel_tokens(self): @pytest.mark.run_only_on('CPU') @pytest.mark.unit- def test_samples_phoneme_portion_range(self, monkeypatch):+ def test_samples_phoneme_portion_range(self): sampled_ranges = [] def fake_uniform(min_value, max_value): sampled_ranges.append((min_value, max_value)) return 0.5 - monkeypatch.setattr(tts_dataset_utils.random, "uniform", fake_uniform)-- probability = _sample_probability_range("partial_phoneme_portion", 0.25, 0.75)+ probability = _sample_probability_range(+ "partial_phoneme_portion", 0.25, 0.75, rng=SimpleNamespace(uniform=fake_uniform)+ ) assert sampled_ranges == [(0.25, 0.75)] assert probability == 0.5