o
    %ݫi~                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlZddl	Z	ddl
mZ ddlmZmZmZmZ ddlmZ dd	lmZ eeZG d
d deZG dd deZG dd deZG dd deZG dd deZG dd deZdS )zPyTorch compatible samplers.

These determine the order of iteration through a dataset.

Authors:
  * Aku Rouhe 2020
  * Samuele Cornell 2020
  * Ralf Leibold 2020
  * Artem Ploujnikov 2021
  * Andreas Nautsch 2021, 2023
  * Adel Moumen 2023
    )Counter)
itemgetter)ListN)lognorm)DistributedSamplerRandomSamplerSamplerWeightedRandomSampler)DynamicItemDataset)
get_loggerc                       s6   e Zd ZdZd
 fdd	Zdd Z fdd	Z  ZS )ReproducibleRandomSamplera	  A modification of RandomSampler which always returns the same values.

    Also look at `torch.utils.data.RandomSampler`. This has mostly
    the same behaviour and arguments, except for adding 'seed' and 'epoch' and
    not supporting 'generator'.

    Note
    ----
    Call `set_epoch` before every epoch. Otherwise, the sampler will produce the
    same sequence of indices every epoch.

    Arguments
    ---------
    data_source : Dataset
        The data source to sample indices for.
    seed : int
        The base seed to use for the random number generator. It is recommended
        to use a value which has a good mix of 0 and 1 bits.
    epoch : int
        The epoch to start at.
    **kwargs : dict
        Arguments to pass to parent class.

    Example
    -------
    >>> import torch
    >>> from speechbrain.utils.checkpoints import Checkpointer
    >>> from speechbrain.dataio.dataloader import SaveableDataLoader
    >>> # An example "dataset"
    >>> dataset = torch.arange(10).unsqueeze(1)
    >>> # Create the random sampler:
    >>> sampler = ReproducibleRandomSampler(dataset)
    >>> dataloader = SaveableDataLoader(dataset, sampler = sampler,
    ...     num_workers = 3)
    >>> # Setup the checkpointer.
    >>> # Note that the sampler doesn't need to be saved itself.
    >>> tmpdir = getfixture('tmpdir')
    >>> checkpointer = Checkpointer(tmpdir, {"dataloader": dataloader})
    >>> # Iterate:
    >>> subset = []
    >>> for i, data_point in enumerate(dataloader):
    ...     # Say you save a checkpoint on the fourth batch:
    ...     if i == 3:
    ...         _ = checkpointer.save_checkpoint(end_of_epoch = False)
    ...     # So let's save the numbers you would get if you continue
    ...     if i >= 4:
    ...         subset.append(data_point.item())
    >>> # What if instead you had to restart the experiment?
    >>> new_sampler = ReproducibleRandomSampler(dataset)
    >>> new_dataloader = SaveableDataLoader(dataset, sampler = new_sampler,
    ...        num_workers = 3)
    >>> new_checkpointer = Checkpointer(tmpdir, {"dataloader": new_dataloader})
    >>> _ = new_checkpointer.recover_if_possible()
    >>> # You'll get the same random order again:
    >>> new_subset = [data_point.item() for data_point in new_dataloader]
    >>> assert subset == new_subset

    &l!r   c                    sF   d|v r
d}t |t j|fi | t|| _|| _t | _d S N	generatorzECannot give a separate generator when using ReproducibleRandomSampler	
ValueErrorsuper__init__intseedepochtorch	Generatorr   )selfdata_sourcer   r   kwargsMSG	__class__ N/home/ubuntu/.local/lib/python3.10/site-packages/speechbrain/dataio/sampler.pyr   ^   s   
z"ReproducibleRandomSampler.__init__c                 C   
   || _ dS z
        You can also just access self.epoch, but we maintain this interface
        to mirror torch.utils.data.distributed.DistributedSampler
        Nr   r   r   r   r   r    	set_epochj      
z#ReproducibleRandomSampler.set_epochc                       | j | j| j  t  S Nr   manual_seedr   r   r   __iter__r   r   r   r    r+   q      
z"ReproducibleRandomSampler.__iter__)r   r   __name__
__module____qualname____doc__r   r%   r+   __classcell__r   r   r   r    r   "   s
    ;r   c                       s:   e Zd ZdZ		d
 fdd	Zdd Z fdd	Z  ZS )!ReproducibleWeightedRandomSamplera;  A reproducible modification of WeightedRandomSampler.

    Also look at `torch.utils.data.WeightedRandomSampler`. This has the
    the same behaviour and arguments, except for adding 'seed' and 'epoch' and
    not supporting 'generator'.

    Note
    ----
    Call `set_epoch` before every epoch. Otherwise, the sampler will produce the
    same sequence of indices every epoch.

    Arguments
    ---------
    weights : sequence of float
        Weights for each index. Doesn't need to sum to one.
    num_samples : int
        Number of samples to draw
    replacement : bool
        To draw with replacement or not (within an epoch of num_samples).
    seed : int
        The base seed to use for the random number generator. It is recommended
        to use a value which has a good mix of 0 and 1 bits.
    epoch : int
        The epoch to start at.
    **kwargs : dict
        Arguments to pass to parent class.

    Example
    -------
    >>> a = ReproducibleWeightedRandomSampler([0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True)
    >>> b = ReproducibleWeightedRandomSampler([0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True)
    >>> list(a)
    [3, 1, 4, 4, 4]
    >>> list(b)
    [3, 1, 4, 4, 4]
    >>> a.set_epoch(1)
    >>> list(a)
    [4, 5, 4, 4, 3]
    >>> b.set_epoch(1)
    >>> list(b)
    [4, 5, 4, 4, 3]


    r   c                    sJ   d|v r
d}t |t j|||fi | t|| _|| _t | _d S r   r   )r   weightsnum_samplesreplacementr   r   r   r   r   r   r    r      s   	
z*ReproducibleWeightedRandomSampler.__init__c                 C   r!   r"   r#   r$   r   r   r    r%      r&   z+ReproducibleWeightedRandomSampler.set_epochc                    r'   r(   r)   r,   r   r   r    r+      r-   z*ReproducibleWeightedRandomSampler.__iter__)r5   r   r.   r   r   r   r    r4   v   s    2r4   c                   @   sH   e Zd ZdZddeefddfddZdd	 Zd
d Zdd Z	dd Z
dS )ConcatDatasetBatchSamplera  This sampler is built to work with a standard Pytorch ConcatDataset.

    It is used to retrieve elements from the different concatenated datasets placing them in the same batch
    with proportion specified by batch_sizes, e.g 8, 16 means each batch will
    be of 24 elements with the first 8 belonging to the first dataset in ConcatDataset
    object and the last 16 to the second.
    More than two datasets are supported, in that case you need to provide 3 batch
    sizes.

    Note
    ----
    Batched are drawn from the datasets till the one with smallest length is exhausted.
    Thus number of examples in your training epoch is dictated by the dataset
    whose length is the smallest.


    Arguments
    ---------
    samplers : list or tuple
        a list or tuple of pytorch samplers
    batch_sizes: list
        Batch sizes.
    epoch : int
        The epoch to start at.

    Example
    -------
    >>> import torch
    >>> from speechbrain.dataio.sampler import ConcatDatasetBatchSampler, ReproducibleRandomSampler
    >>> from speechbrain.dataio.sampler import ReproducibleRandomSampler
    >>> from speechbrain.dataio.dataloader import SaveableDataLoader
    >>> # example "datasets"
    >>> dataset1 = torch.arange(0, 10).unsqueeze(1)
    >>> dataset2 = torch.arange(20, 40).unsqueeze(1)
    >>> tot_dataset = torch.utils.data.ConcatDataset([dataset1, dataset2])
    >>> sampler1 = ReproducibleRandomSampler(dataset1)
    >>> sampler2 = ReproducibleRandomSampler(dataset2)
    >>> tot_sampler = ConcatDatasetBatchSampler([sampler1, sampler2], [2, 4])
    >>> dataloader = SaveableDataLoader(tot_dataset, batch_sampler = tot_sampler,
    ...     num_workers = 3)
    >>> for data_point in dataloader:
    ...      assert len(data_point) == 6
    ...      for i in range(2):
    ...         assert data_point[i] in [x for x in range(0, 10)]
    ...      for i in range(2, 4):
    ...         assert data_point[i] in [x for x in range(10, 40)]
    r   batch_sizesreturnNc                 C   s   t |ttfstd|t |ttfstd|t|t|ks(td|| _|| _dgt	dd | jD 
 d d  | _|| _| | j d S )NzKsamplers should be a list or tuple of Pytorch Samplers, but got samplers={}zIbatch_sizes should be a list or tuple of integers, but got batch_sizes={}z3batch_sizes and samplers should be have same lengthr   c                 S      g | ]}t |qS r   )len.0xr   r   r    
<listcomp>      z6ConcatDatasetBatchSampler.__init__.<locals>.<listcomp>)
isinstancelisttupler   formatr=   r:   samplersnpcumsumtolistoffsetsr   r%   )r   rH   r:   r   r   r   r    r      s.   
z"ConcatDatasetBatchSampler.__init__c                 c   s4    g }|D ]}| ||  t||kr|V  qd S r(   )appendr=   )r   c_batch_size	c_samplerc_offsetbatchidxr   r   r    _iter_one_dataset  s   z+ConcatDatasetBatchSampler._iter_one_datasetc                 C   s.   t | jd dr| jD ]	}|| qdS dS )zYou can also just access self.epoch, but we maintain this interface
        to mirror ``torch.utils.data.distributed.DistributedSampler``.
        r   r   N)hasattrrH   r%   )r   r   sr   r   r    r%     s
   
z#ConcatDatasetBatchSampler.set_epochc                 c   s    dd | j D }g }tt| D ]8}tt| j D ])}g }t|| j| k r>|| j| t||   t|| j| k s'|| q|V  g }qd S )Nc                 S   r<   r   )iterr?   ir   r   r    rA   "  rB   z6ConcatDatasetBatchSampler.__iter__.<locals>.<listcomp>)rH   ranger=   r:   rM   rL   nextextend)r   	iterators	tot_batchb_numsamp_idxc_batchr   r   r    r+      s   z"ConcatDatasetBatchSampler.__iter__c                 C   s<   t d}t| jD ]\}}t|| j|  }t||}q	|S )Ninf)float	enumeraterH   r=   r:   min)r   min_lenrR   samplerc_lenr   r   r    __len__0  s
   z!ConcatDatasetBatchSampler.__len__r   )r/   r0   r1   r2   rF   rE   r   rS   r%   r+   rh   r   r   r   r    r9      s    0r9   c                   @   s   e Zd ZdZddd dddg dddd	d	fd
edededededee dee dedededefddZdd Z	d
ededee fddZ
dd Zdd  Zd!d" Zd#d$ Zd%d& ZdS )'DynamicBatchSamplerar  This BatchSampler batches examples together by grouping them by their length.

    Every example in the batch have approximately the same length and
    thus padding is minimized.
    This enables faster training on datasets
    where length of examples can vary significantly (e.g Librispeech).
    Inspired by: https://www.tensorflow.org/api_docs/python/tf/data/experimental/bucket_by_sequence_length

    Dynamic batching is performed by specifying a max_batch_length which is the
    upper limit for the sum of the length of examples in a batch:
    e.g., if ex1 has length 4, ex2 length 5 and if max_batch_length is set to 6
    ex1 and ex2 will be placed, alone, in two distinct batches.

    Length for each example can be obtained in two manners.
    If the input dataset is a DynamicItemDataset it can be obtained by specifying a
    length_func. Default assumes a "duration" entry is in the annotation.
    Length for each example can also be passed to this class upon instantiation
    by specifying a list containing the length for each example and passing it to
    lengths_list.

    Examples are grouped together by defining a set of possible discrete intervals
    (buckets). Examples whose length fall into these intervals can be batched together.

    The number of buckets can be specified by using the arg num_buckets.
    There is usually an optimal range for the value of this argument.

    If num_buckets == 1, all examples can be batched together. You have maximum randomization
    but your training speed will be slower due to the fact that a large amount of the values will be padding
    as long and short examples can be batched together.
    As the number of buckets grows only examples with similar
    length can be grouped together.
    This trades-off speed with randomization.
    TLDR: Low number -> better randomization, High number -> faster training.
    NOTE THAT: if set too high the training speed will decrease. If num_buckets -> number of examples in the dataset the batch size
    will be small impacting training speed and possibly performance.

    The buckets can also be specified by passing a list to the bucket_boundaries
    argument instead of specifying a left_bucket_length and a bucket_length_multiplier.

    Example
    -------
    >>> import torch
    >>> import speechbrain as sb
    >>> from speechbrain.dataio.sampler import DynamicBatchSampler
    >>> from speechbrain.dataio.dataset import DynamicItemDataset
    >>> from speechbrain.dataio.dataloader import SaveableDataLoader
    >>> from speechbrain.dataio.batch import PaddedBatch
    >>> import numpy as np
    >>> item_lengths = sorted([np.random.randint(10, 100) for x in range(20)])
    >>> dataset = {"ex_{}".format(x) : {"wav" :torch.randn(x)} for x in item_lengths}
    >>> dataset = DynamicItemDataset(dataset)
    >>> dataset.set_output_keys(["wav"])
    >>> length_func = lambda x : len(x) # trivial in this example
    >>> bsampler = DynamicBatchSampler(dataset, 20, 4, length_func, shuffle=False, batch_ordering='descending')
    >>> dataloader = SaveableDataLoader(dataset, batch_sampler=bsampler, collate_fn=PaddedBatch)
    >>> for i, b in enumerate(dataloader):
    ...     data, length = b["wav"]
    >>> assert data.shape[-1] == max(item_lengths)

    Arguments
    ---------
    dataset : torch.utils.data.Dataset
        Pytorch Dataset from which elements will be sampled.
    max_batch_length : int
        Upper limit for the sum of the length of examples in a batch.
        Should be chosen based on your GPU memory.
    num_buckets : int
        Number of discrete buckets used to group examples together.
        If num_buckets == 1, all examples can be batched together. As the number of buckets grows only examples with similar
        length can be grouped together. This trades-off speed with randomization.
        Low number -> better randomization, High number -> faster training.
        However if set too high the training speed will decrease. If num_buckets -> number of examples in the dataset the batch size
        will be small impacting training speed and possibly performance.
        NOTE: you have either to specify manually the bucket_boundaries or the number of buckets.
    length_func : callable
        Function used to get length of each example from the dataset.
        This argument can be used only when the dataset is a Speechbrain DynamicItemDataset object.
        Can be anything: e.g. lambda x: x["duration"]*16000 returns number of samples
        if duration key in the annotation is in seconds and the file has 16kHz sampling freq.
    shuffle : bool
        Whether or not shuffle examples between each epoch.
    batch_ordering : string
        If ``random``, batches are randomly permuted; otherwise ``ascending`` or ``descending`` sorted by length.
    max_batch_ex: int
        If set, it limits the maximum number of examples that can be in a batch superseding max_batch_length
        in instances where the amount of examples will exceed the value specified here.
        E.g. you have a lot of short examples and the batch size for those will be too high, you can use this argument
        to limit the batch size for these short examples.
    bucket_boundaries : list
        Overrides bucket_length_multiplier and left_bucket_length by specifying manually
        the buckets right boundaries.
    lengths_list: list
        Overrides length_func by passing a list containing the length of each example
        in the dataset. This argument must be set when the dataset is a plain
        Pytorch Dataset object and not a DynamicItemDataset object as length_func
        cannot be used on Pytorch Datasets.
    seed : int
        Random seed.
    epoch : int
        The epoch to start at.
    drop_last : bool
         If ``True``, the sampler will drop the last examples which
         have not been grouped.
    verbose: bool
        If ``True``, log also the stats for each batch at the first epoch.
    Nc                 C   s   | d S )Ndurationr   r@   r   r   r    <lambda>  s    zDynamicBatchSampler.<lambda>Trandom*   r   Fmax_batch_lengthnum_bucketsshufflebatch_orderingmax_batch_exbucket_boundarieslengths_listr   r   	drop_lastverbosec                    s  | _ i  _| _|d u rt|dkrtd|	d ur.tt|	D ]}|	|  jt|< q!n$t|ts7t	dtt j D ]}| j j
 j j|   jt|< q>t|dkrtdd |D setdtt|t|ksstdtjjt|tt|dd	 tt| _nt j||d
 _| _| _| _|
 _| _|d u rtj}| _ fddtt jD dg  _| _   d S )Nr   z\Please specify either num_buckets or bucket boundaries.Check the docs, and/or the tutorial !zMDataset should be a Speechbrain DynamicItemDataset when using length functionc                 S   s   g | ]}|d kqS ri   r   r>   r   r   r    rA     rB   z0DynamicBatchSampler.__init__.<locals>.<listcomp>z@All elements in bucket boundaries should be non-negative (>= 0).z0Bucket_boundaries should not contain duplicates.z[The arg bucket_boundaries should be an ascending sorted list of non negative values values!)err_msg)rp   num_quantilesc              
      s.   g | ]}t  jtd t j j|  qS    )rd   _max_batch_exmaxr   _max_batch_length_bucket_boundariesrW   r,   r   r    rA     s    r|   ) _dataset_ex_lengthsrx   r=   RuntimeErrorrY   strrD   r
   NotImplementedErrordatadata_idsallr   setrI   testingassert_array_equalarraysortedr   _get_boundaries_through_warpingr   _shuffle_ex_batch_ordering_seed
_drop_lastra   r}   _bucket_lens_epoch_generate_batches)r   datasetrp   rq   length_funcrr   rs   rt   ru   rv   r   r   rw   rx   indxr   r,   r    r     sn   

	
zDynamicBatchSampler.__init__c                    s    fdd|D S )z,Gets durations of the elements in the batch.c                       g | ]	} j t| qS r   r   r   r?   rR   r,   r   r    rA          z5DynamicBatchSampler.get_durations.<locals>.<listcomp>r   r   rQ   r   r,   r    get_durations  s   z!DynamicBatchSampler.get_durationsrz   r;   c              	      s   t d |d }td| || |}t|d}|| |d    fddt|d D }t dt	t
dj t	t
dj| t	t S )Nz"Batch quantisation in latent spacer|   rC   c                    s    g | ]} |d    |  qS r{   r   r>   ru   r   r    rA         zGDynamicBatchSampler._get_boundaries_through_warping.<locals>.<listcomp>z=Latent bucket boundary - buckets: {} - length multipliers: {}z{:.2f})loggerinforI   linspacer   ppfrY   debugrG   rE   mapr   )r   rp   rz   num_boundarieslatent_boundaries	quantileslength_multipliersr   r   r    r     s&   


z3DynamicBatchSampler._get_boundaries_through_warpingc                    s    j dkr2t }| j j  tjt j|d	 }g }|D ]
}|
 j|  q"| _d S  j dkrEt j fddd _d S  j dkrYt j fddd	d
 _d S t)Nrn   r   	ascendingc                       t  fdd| D S )Nc                    r   r   r   r   r,   r   r    rA   6  r   JDynamicBatchSampler._permute_batches.<locals>.<lambda>.<locals>.<listcomp>r~   rl   r,   r   r    rm   6      z6DynamicBatchSampler._permute_batches.<locals>.<lambda>key
descendingc                    r   )Nc                    r   r   r   r   r,   r   r    rA   ;  r   r   r   rl   r,   r   r    rm   ;  r   T)r   reverse)r   r   r   r*   r   r   randpermr=   _batchesrK   rM   r   r   )r   grf   tmprR   r   r,   r    _permute_batches%  s0   






z$DynamicBatchSampler._permute_batchesc                    s<  t d jr"t }|jj  tjt	j
|d }ntt	j
}g _dd jD }dd jD }|D ]e}jt| }tj|}|| | t|| d ||| d< t|| d ||| d< || d  |7  < || d	  d
7  < t	|| j| kst	|| jkrj||  g ||< q>js|D ]
}|rj| q  jdkrdgj  }	tt	jD ]P}
z#||
 d j }||
 d ||
 d  ||
 d ||
 d	   }W n ty   d}d}Y nw t d|
|	|
 |	|
d
  j|
 ||
 d	 ||d  q͈jrg g g d}jD ]>}tfdd|D }|d | tfdd|D  t fdd|D }|d | |d || d  q+d}d| }tt	jD ]$}t |||d | t	j| |d | |d |  qwd S d S d S )Nz/DynamicBatchSampler: Generating dynamic batchesr   c                 S   s   g | ]}g qS r   r   rW   r   r   r    rA   M  s    z9DynamicBatchSampler._generate_batches.<locals>.<listcomp>c                 S   s    g | ]}t jt j d d dqS )r   )rd   r~   totn_ex)rI   ra   rW   r   r   r    rA   O  r   rd   r~   r   r   r|   r   zDynamicBatchSampler: Bucket {} with boundary {:.1f}-{:.1f} and batch_size {}: Num Examples {:.1f}, Num Full Batches {:.3f}, Pad Factor {:.3f}.d   )
tot_framestot_pad_framespad_%c                    r   r   r   r   r,   r   r    rA     r   r   c                    r   r   r   r   r,   r   r    rA     r   c                    s   g | ]} j t|  qS r   r   r   
max_framesr   r   r    rA     s    r   r   zPBatch {} with {:.1f} frames with {} files - {:.1f} padding, {:.2f} (%) of total.zDynamicBatchSampler: ) r   r   r   r   r   r*   r   r   r   r=   r   rK   rY   r   r   r   r   rI   searchsortedr   rM   rd   r~   r}   r   r   r   ZeroDivisionErrorr   rG   rx   sum)r   r   rf   bucket_batchesstats_trackerrR   item_len	bucket_idrQ   
boundariesbucket_indxnum_batches
pad_factorbatch_statsr   tot_padpadding_detailsrX   r   r   r    r   A  s   











#z%DynamicBatchSampler._generate_batchesc                 c   s<    | j D ]}|V  q| jr|   | jdkr|   d S d S )Nrn   )r   r   r   r   r   r   r   r   r    r+     s   

zDynamicBatchSampler.__iter__c                 C   s   || _ |   dS r"   )r   r   r$   r   r   r    r%     s   zDynamicBatchSampler.set_epochc                 C   s
   t | jS r(   )r=   r   r,   r   r   r    rh     s   
zDynamicBatchSampler.__len__)r/   r0   r1   r2   r   boolr   r   r   r   r   r   r   r+   r%   rh   r   r   r   r    rj   :  sb    o	

X
#}	rj   c                       s8   e Zd ZdZ fddZ fddZ fddZ  ZS )DistributedSamplerWrappera  This wrapper allows using any sampler (for example batch) with Distributed Data Parallel (DDP)
    correctly.

    Passing blindly the sampler to each DDP process will cause to have access
    within each process to all the data in the dataset instead of only a subset
    of it which is unique to each process.  This wrapper prevents this and
    allows to use only a subset of the original data for each process.

    NOTE
    ----
    This is is automatically applied to any sampler in the Brain class when DDP
    training is used.
    c                    s    t  j|d|i| || _d S )Nr   )r   r   rf   )r   rf   argsr   r   r   r    r     s   
z"DistributedSamplerWrapper.__init__c                    s(   t | j }t  }tt| |S r(   )rE   rf   r+   r   rV   r   )r   sampler_indicesindices_of_indicesr   r   r    r+     s   
z"DistributedSamplerWrapper.__iter__c                    s,   t  | t| jdr| j| dS dS )zBPass set_epoch() through to DistributedSampler and the wrapper oner%   N)r   r%   rT   rf   r$   r   r   r    r%     s   z#DistributedSamplerWrapper.set_epoch)r/   r0   r1   r2   r   r+   r%   r3   r   r   r   r    r     s
    
r   c                       s2   e Zd ZdZ				d
 fdd	Zdd	 Z  ZS )BalancingDataSamplera  A data sampler that takes a single key from the dataset and
    ensures an approximately equal distribution by that key

    Arguments
    ---------
    dataset : DynamicItemDataset
        the dataset form which samples will be drawn
    key : str
        the key from which samples will be taken
    num_samples : int
        Number of samples to draw
    replacement : bool
        To draw with replacement or not (within an epoch of num_samples).
    seed : int
        The base seed to use for the random number generator. It is recommended
        to use a value which has a good mix of 0 and 1 bits.
    epoch : int
        The epoch to start at.
    **kwargs : dict
        Arguments to pass to parent class.

    Example
    -------
    >>> from speechbrain.dataio.sampler import BalancingDataSampler
    >>> from speechbrain.dataio.dataset import DynamicItemDataset
    >>> sample_data = {
    ...   1: {"category": "A",
    ...       "text": "This is a test"},
    ...   2: {"category": "A",
    ...       "text": "This is a second test"},
    ...   3: {"category": "B",
    ...       "text": "This is a third test"}
    ...  }
    >>> dataset = DynamicItemDataset(data=sample_data)
    >>> sampler = BalancingDataSampler(
    ...     dataset=dataset,
    ...     key="category",
    ...     num_samples=10
    ... )
    >>> sampler.weights
    tensor([0.5000, 0.5000, 1.0000], dtype=torch.float64)
    >>> it = iter(sampler)
    >>> [next(it) for _ in range(10)]
    [2, 2, 1, 2, 2, 0, 1, 1, 1, 2]
    NTr   r   c           	         s@   || _ || _|st|}|  }t j|||||fi | d S r(   )r   r   r=   _compute_weightsr   r   )	r   r   r   r7   r8   r   r   r   r6   r   r   r    r   *  s   


zBalancingDataSampler.__init__c                    sl   j jg fddj D }t| W d    n1 s!w   Y  dt fdd|D  }|S )Nc                    s   g | ]}| j  qS r   r   )r?   itemr,   r   r    rA   ?  r   z9BalancingDataSampler._compute_weights.<locals>.<listcomp>r|   c                    s   g | ]} | qS r   r   )r?   class_id)class_counterr   r    rA   B  rB   )r   output_keys_asr   r   r   tensor)r   	class_idsr6   r   )r   r   r    r   =  s   
z%BalancingDataSampler._compute_weights)NTr   r   )r/   r0   r1   r2   r   r   r3   r   r   r   r    r     s    2r   )r2   collectionsr   operatorr   typingr   numpyrI   r   scipy.statsr   torch.utils.datar   r   r   r	   speechbrain.dataio.datasetr
   speechbrain.utils.loggerr   r/   r   r   r4   r9   rj   r   r   r   r   r   r    <module>   s(    TNv   &