o
    wiB-                     @   sL  d dl Z d dlmZmZmZ d dlZd dlmZ d dlm	Z	 ddgZ
deee  ded	ed
efddZdee ded
eee  fddZdee ded
eee  fddZdee ded
eee  fddZdejdefddZ	d dee deded
eeee  ef fddZdeee  deeee f deded
ee f
ddZdS )!    N)DictListTuple)tqdm)loggingfirst_fit_decreasingfirst_fit_shufflebinssbin_sizereturnc                 C   s.   t | D ]\}}t|| |kr|  S qdS )a  
    Finds the first bin in a list of bins that has enough space to fit a sequence of size 's'.

    Args:
      bins: A list of lists, where each inner list represents a bin and contains the current elements in that bin.
      s: The size of the sequence to be placed in a bin.
      bin_size: The maximum capacity of each bin.

    Returns:
      The index of the first bin that can fit the sequence 's', or -1 if no such bin exists.
    )	enumeratesum)r	   r
   r   iabin r   ^/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/nemo/utils/sequence_packing_utils.pyfind_first_bin_that_fits   s
   r   seqlens	pack_sizec                 C   sB   g }| D ]}t |||}|dkr||g q|| | q|S )a  
    Packs sequences of varying lengths into bins using the First-Fit algorithm.

    Args:
      seqlens: A list of integers, representing the lengths of the sequences to be packed.
      pack_size: The maximum capacity of each bin.

    Returns:
      A list of lists, where each inner list represents a bin and contains the indices
        of the sequences assigned to that bin.
    r   )r   append)r   r   resr
   	first_binr   r   r   	first_fit,   s   r   c                 C   s   t | dd}t||S )a  
    Packs sequences of varying lengths into bins using the First-Fit Decreasing algorithm.

    This is a variation of the First-Fit algorithm where the sequences are sorted by decreasing length before packing.

    Args:
      seqlens: A list of integers, representing the lengths of the sequences to be packed.
      pack_size: The maximum capacity of each bin.

    Returns:
      A list of lists, similar to the output of the 'first_fit' function.
    T)reverse)sortedr   )r   r   sorted_seqlensr   r   r   r   B   s   
c                 C   s"   | dd }t j| t||S )a  
    Packs sequences of varying lengths into bins using the First-Fit with Shuffling algorithm.

    This variation shuffles the order of the sequences before applying the First-Fit algorithm.

    Args:
      seqlens: A list of integers, representing the lengths of the sequences to be packed.
      pack_size: The maximum capacity of each bin.

    Returns:
      A list of lists, similar to the output of the 'first_fit' function.
    N)nprandomshuffler   )r   r   shuffled_seqlensr   r   r   r   S   s   
datasettruncate_seq_lenc                 C   s   t d tt}dg|d  }| D ]}t|d d }|| | ||  d7  < qt d t | g }t|d D ]}|t||  q?||fS )a  
    Creates a histogram of sequence lengths from a tokenized dataset.

    This function analyzes the tokenized dataset and creates a histogram showing the distribution of sequence lengths.

    Args:
      dataset: A NumPy array containing the tokenized sequences. Each element is a dictionary that contains at minimum
               the key `input_ids`.
      truncate_seq_len: The maximum sequence length to consider in the histogram.

    Returns:
      sequences: A dictionary where keys are sequence lengths and values are lists
                 of corresponding sequences from the dataset.
      histogram: A list representing the histogram data (number of sequences for each length).
    z,Creating histogram from tokenized dataset...r      	input_idszHistogram of sequence lengths)	r   infocollectionsdefaultdictlistlenr   debugrange)r"   r#   	sequencescounts	item_dictseq_len	histogramr   r   r   create_histe   s   



r2   r1   packing_algorithmc                 C   s  t d| d g }t| D ]\}}||g|  qt | }|||}dd |D }t|t| }	t|}
tdd |D }t|}|
|t|	dtt	|t| | d d||d}t 
d	 t 
| t d
t	|t| | d dd t d| d|	dd ||fS )a  
    Packs sequences into bins using the specified packing algorithm.

    This function takes the histogram of sequence lengths, desired pack size, and a string representing the packing
    algorithm to use. It then calls the corresponding function (e.g., 'first_fit_decreasing') and performs the
    packing process using only sequence lengths as input (without the actual sequences).

    Args:
          histogram: A list representing the histogram data (number of sequences for each length).
          pack_size: The maximum capacity of each bin.
          packing_algorithm: One of the supported packing algorithms from ['first_fit_decreasing', 'first_fit_shuffle']

    Returns:
          assignments: A list of lists, where each inner list represents a bin and contains the indices of the
                        sequence lengths assigned to that bin.
          pack_metadata: A dict that records packing metadata, for instance the max number of samples per bin.
    zPacking sequences to length z...c                 S      g | ]}t |qS r   )r   .0xr   r   r   
<listcomp>       z+create_packing_strategy.<locals>.<listcomp>c                 S   r4   r   )r*   )r6   br   r   r   r8      r9      d   )dataset_max_seqlenmax_samples_per_binpacking_factorpacking_efficiencyr   min_packed_seqlenzPacked sequence lengths:zPacking is z.2fz% efficientz>>>>> For pack size z., average number of sequences per pack is n = z.3fz <<<<<)r   r&   r   extendglobalsr*   maxminroundr   r+   )r1   r   r3   all_seq_lensr   count
packing_fnassignmentspacked_seq_lensr?   
max_seqlenr>   rA   packing_metadatar   r   r   create_packing_strategy   s2   



(rN   rJ   r-   pad_idc                    s4  t  }tt|d D ]~}|| }t|dkrtjt|}tdd |D |  }ztdd |D |  }	dd |	D }	W n> t	y   zt fdd|D |  }	W n" t	y }
 zd}||
 d	|d  7 }t
| t|d
}
~
ww Y nw ||	f||< qi i i }}	}tt| t| dD ]?\}}g g dg}}}|D ]}||| d   ||| d   |t| q|||< ||	|< |d
d ||< qg }tt|D ]}|| |	| || d}|| qtdd | D sJ dtdd | D sJ d|S )a  
    Fills the packing strategy with actual sequence data based on assignments and sequence information.

    This function takes the assignments generated by the packing algorithm (containing sequence length indices),
    the original sequences data, and the pack size. It iterates through the assignments, retrieves the corresponding
    sequences from the sequences dictionary, and constructs the final output data structure with input IDs, loss masks
    (if available), and starting indices for each sequence in a packed sequence.

    Args:
          assignments: A list of lists, where each inner list represents a bin and contains the indices of the
                        sequence lengths assigned to that bin (output of 'create_packing_strategy').
          sequences: A dictionary where keys are sequence lengths and values are lists of corresponding sequences
                      from the dataset (output of 'create_hist').
          pack_size: The maximum capacity of each bin.
          pad_id: The tokenizer's padding token.

    Returns:
          output_data: A list of dictionaries, where each dictionary represents a packed sequence with its input IDs,
                        loss mask (if available), and starting indices.
    r$   r   c                 S      g | ]}|d  qS )r%   r   r5   r   r   r   r8      r9   z)fill_packing_strategy.<locals>.<listcomp>c                 S   rP   )	loss_maskr   r5   r   r   r   r8      r9   c                 S   s   g | ]}|d d dg qS )r$   NFr   r5   r   r   r   r8      s    c                    s,   g | ]  fd dt t d D qS )c                    s,   g | ]}|d  d kod |  kqS )answer_start_idxr$   r%   r   )r6   idx)rO   r7   r   r   r8      s    z4fill_packing_strategy.<locals>.<listcomp>.<listcomp>r%   )r,   r*   )r6   rO   )r7   r   r8      s    z?Key errors loss_mask and answer_start_idx missing in example -  N)totalr   )r%   rQ   seq_start_idc                 s       | ]}|d   V  qdS )r   Nr   r6   seqr   r   r   	<genexpr>      z(fill_packing_strategy.<locals>.<genexpr>z4Error: There are items left over from the assignmentc                 s   rX   )r$   Nr   rY   r   r   r   r[     r\   )dictr   r,   r*   r   r   permutationarraytolistKeyErrorr   error
ValueErrorr   rB   popr   allvalues)rJ   r-   r   rO   ifile_handlesr0   per_seq_datapermr%   rQ   errerr_msgrW   oindex
assignment
_input_ids
_loss_mask_seq_start_id
seq_lengthoutput_datar   r/   r   rT   r   fill_packing_strategy   sf   



  rs   )r   )r'   typingr   r   r   numpyr   r   
nemo.utilsr   PACKING_ALGOSintr   r   r   r   r_   r2   strr]   rN   rs   r   r   r   r   <module>   s@   """"*
4
