o
    ίio                  &   @   sj  d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
 d dlmZmZmZ d dlmZ d dlmZ d dlmZmZ d d	lmZmZmZmZmZ d dlZd d
lmZm Z m!Z! e" Z#	 d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e*de+de+de+de+f
ddZ,de*de+de+de+de+f
ddZ-	daded e.d!e.d"e*d#ee* f
d$d%Z/d&ee*ef d'ee*ef d(e*d)ee*e0f d*ee*ef f
d+d,Z1d-d. Z2ded/e(fd0d1Z3d2ed3e+d4e+d5e+d6e+d7e)fd8d9Z4e$fd:e*d;e+d<e*fd=d>Z5d:e*d?e+d;e+d<e*fd@dAZ6d(e*d)ee*e0f dBe+d?e+d;e+d<e*fdCdDZ7de$ddddfd(e*d)ee*e0f d3e+d4e+d5e+d6e+dBe+d?e+d;e+d e.d!e.dEe*d#ee* d<e*dFee+ dGee+ dHee+ dIee* f$dJdKZ8dLdM Z9e j:d7e)fdNdOZ;dPedQefdRdSZ<dTedPefdUdVZ=e j:dWe+fdXdYZ>eG dZd[ d[Z?d\e?d?e+d;e+fd]d^Z@	dad\e?d7ee) fd_d`ZAdS )b    Ndeepcopy)	dataclassfield)partial)EventProcessQueue)r   )Path)EmptyFull)AnyDictIteratorOptional	TypedDict)
ChatFormatTokenizerArgsbuild_tokenizerz*.chunk.*.jsonlc                   @   s:   e Zd ZU dZeed< eed< eed< eed< eed< dS )
JSONLStatea  Represents the current state of a JSON line reader.

    Attributes:
        content (Dict): The JSON content of the line.
        file_path (str): The path to the JSONL file.
        position (int): The file position after reading the line (in bytes).
        window (int): The window size used for iteration.
        offset (int): The offset used for iteration.
        current_iter (Optional[int]): Number of iterations over the jsonl file (for infinite iteration).
    	file_pathposition
block_sizeoffsetcurrent_iterN)__name__
__module____qualname____doc__str__annotations__int r"   r"   B/home/ubuntu/.local/lib/python3.10/site-packages/core/data/data.pyr   B   s   
 r   c                   @   sJ   e Zd ZU dZeed< eeef ed< eeef ed< eeef ed< dS )MultiChoiceStateaf  Represents the current state of a Multi choice iterator.

    Attributes:
        root_dir: path to dataset root directory
        sources Dict[str, float]: Dict from subdirectory to the weight used for sampling
        source_states: Dict[str, Any] Dict from source to iterator state
        rng_state: dict numpy bit generator state used to resume rng
    root_dirsourcessource_to_state	rng_stateN)	r   r   r   r   r   r    r   floatr   r"   r"   r"   r#   r$   U   s   
 	r$   c                   @   s:   e Zd ZU eed< eed< eed< eed< ee ed< dS )TokenizerStateit_statenameadd_bosadd_eospathN)r   r   r   r   r    r   boolr   r"   r"   r"   r#   r*   e   s   
 r*   c                   @   s:   e Zd ZU dZeed< eed< eed< eed< eed< dS )PackTokensStateaG  Represents the current state of a packing iterator.

    Attributes:
        start_token: int index to start reading from in the current sequence
        output_seq_len: int Length of sequences to output
        n_views: dict int Number of views to output. Each view is the same sequence but shifted by 1 from the previous
    start_tokenr+   output_seq_lenn_viewsseq_lenN)r   r   r   r   r!   r    r   r"   r"   r"   r#   r1   m   s   
 r1   c                   @   sB   e Zd ZU dZeed< eed< eeef ed< eed< eed< dS )PrefetchStatea  Represents the current state of a prefetching iterator.

    Attributes:
        prefetch_buffer: numpy array to store prefetched data
        seq_idx: int index of the current sequence to resume from
        rng_state: dict numpy bit generator state used to resume rng
    r+   seq_idxr(   prefetch_size
batch_sizeN)	r   r   r   r   r   r    r!   r   r   r"   r"   r"   r#   r6   }   s   
 r6   r   r   r   r   r   c           	      c   s    |dk s	||krt d|dkr|d nd}t| ||||d}t| dA}|| |  }r^|d7 }|d | |krPt| | |||d}t||fV  |  }s1W d   dS W d   dS 1 siw   Y  dS )az  Iterates over a JSON Lines file, yielding a line every `block_size` lines with an offset

    Example : If block_size = 3, offset = 1, iterator will yield lines 1 4 7 10 ...
    Example : If block_size = 2, offset = 0, iterator will yield lines 0 2 4 6 ...

    Args:
        file_path (str): Path to the JSONL file.
        position (int): The file position (in bytes) from which to start reading.
        block_size (int): The number of lines to skip between yields
        offset (int): The initial number of lines skipped

    Yields:
        JSONLState: Represents the state of each line read according to window and offset.
    r   z&JSONL iterator offset value is invalid   r   r   r   r   r   rN)RuntimeErrorr   openseekreadlinetelljsonloads)	r   r   r   r   r   current_linestatefileliner"   r"   r#   
read_jsonl   s8   
"rH   c                 c   sF    z	 t | ||||}|D ]	\}}||fV  q|d7 }d}q|  w )zBMakes the block jsonl iterator infinite and updates n_iter counterTr:   r   )rH   close)r   r   r   r   r   itcontentjsonl_stater"   r"   r#   loop_on_jsonl   s   
rM   iteratorr-   r.   tokenizer_typetokenizer_pathc              	   c   s$   t ||d}|dkrt|}| D ]~\}}d|v rc|dks!J dg }	d}
d|v r-|d }
|d D ]+}|d dkr;dnd	}|d
 }|dkrT|
rT|	||d|
d d q1|	||d q1||	}n d|v sod|v soJ dd|v rudnd}|| }|j|||d}|t|||||dfV  qdS )a]  
    Tokenizes text from an iterator of content-state pairs using a specified tokenizer.

    Parameters:
    - iterator: An iterable of (content, state) pairs where content is a dict with a 'text' or 'content' key.
    - tokenizer: Tokenizer object with an `encode` method to convert text to tokens, supporting `add_bos` and `add_eos`.
    - add_bos (bool): Flag to add a beginning-of-sequence token.
    - add_eos (bool): Flag to add an end-of-sequence token.

    Yields:
    - (tokens, state) pairs, where `tokens` is a list of tokenized text, and `state` is the original state from the iterator.
    )r,   r/   llama3conversationsz7conversations should be tokenized with llama3 tokenizerNimagefromhuman	assistantvalue
num_chunks)rolerK   typerX   )rY   rK   textrK   z1JSON line must contain either text or content key)r-   r.   r+   r-   r.   r,   r/   )r   r   appendencode_dialog_promptencoder*   )rN   r-   r.   rO   rP   	tokenizerchat_formatrK   rE   dialogfirst_user_mediaconversationrY   r[   tokenscontent_keyr"   r"   r#   tokenize   sP   
	rg   source_to_iteratorr'   r%   r&   r(   c                 c   s    t |}t| }t| }tj }||j_	 t	|t	|
  }	||j||	d }
t| |
 \}}i ||
|i}t||||jjd}||fV  q)a  
    Iterates over multiple data sources, selecting sequences based on weighted random choice.

    Parameters:
    - source_to_iterator (Dict[str, Iterator]): Dict from source paths to their iterators.
    - source_to_state (Dict[str, State]): Initial state for each source, allowing state tracking.
    - root_dir str: Root dir of data sources
    - sources Dict[str, float]: Dict from subdirectory to the weight used for sampling
    - rng_state (dict): State of the random number generator for reproducibility.

    Yields:
    - Tuple of (seq, multi_choice_state) where `seq` is the next sequence from the chosen source,
    and `multi_choice_state` includes the current state of all sources and the RNG.

    This function ensures that sequences are chosen from the provided sources based on the specified weights,
    maintaining state information for each source and the RNG to allow for reproducible iteration.
    T)pr%   r&   r'   r(   )lenlistkeysvaluesnprandomdefault_rngbit_generatorrE   arraysumchoicenextr$   )rh   r'   r%   r&   r(   	n_sourcespossible_sourcesweightsrngnorm_weightssource_choiceseqrE   multi_choice_stater"   r"   r#   choose_source  s&   

r   c                 C   s\   d}| dk r|d8 }| || d 7 } | dk st || }| |d< |d|= d|v r,|d= |S )aI  
    Calculates the state to resume iteration after the buffer is cleared.

    This function determines the starting point for resuming iteration by rewinding `n_views` from the `end_token`.
    It handles cases where the rewind goes beyond the current sequence, adjusting the starting sequence and token index accordingly.
    r   r:   r5   r2   Nr   )r2   statesseq_to_resume_fromresume_stater"   r"   r#   get_empty_buffer_state?  s   
r   empty_buffer_statec              
   c   s   g }g }|d }|d }|d }|d }|| d }t | D ]\}	\}
}|}d}|s|t|
k s=J d| dt|
 |t| }t|t|
| }|| }||
||  |}|t|||||d	 t||ksqJ d
t||krt|}|jdksJ dtj	j
j||dd}||d  }t||}||d }t||d ksJ ||fV  |t|
krd}d}|}|r+qdS )a  
    Iterates over tokens, packing them into chunks.

    This function aggregates tokens into a buffer and yields fixed-size chunks with dimensions `(output_seq_len, n_views)`,
    where each column represents shifted sequences of tokens. It ensures continuity in token sequences across chunks,
    preventing boundary effects and maintaining consistency regardless of `n_views`.

    Parameters:
    - iterator: An iterator that yields pairs of (tokens, state), where tokens is a 1D sequence of tokens and state contains all necessary information to resume iterator from current position.
    - it_state: State of the iterator currently.
    - start_token (int): The index of the first token to start reading from for the first sequence.
    - output_seq_len (int): The length of the output sequences to be generated.
    - n_views (int): The number of shifted views to include in each output chunk.

    Yields:
    - numpy.ndarray: An array of shape `(output_seq_len, n_views)` containing the packed tokens.
    - PackTokensState: The state required to resume packing tokens from where the last returned chunk.

    The function handles the complexity of determining the correct state for resuming iteration after the buffer is cleared, ensuring seamless continuation of token sequences.
    r3   r4   r2   r+   r:   FzStart token index z bigger than sequence )r2   r5   r+   r3   r4   zBuffer overflowz#Iterator should return 1D sequencesr   axisNT)	enumeraterk   minextendr]   r1   ro   rs   ndimlibstride_trickssliding_window_viewr   )rN   r   bufferr   r3   r4   r2   previous_statebuffer_sizeire   rE   	end_tokensample_is_read
free_spacer5   outrewinded_idxr"   r"   r#   pack_tokens[  sd   	


r   data_loaderr9   r8   r5   r4   rE   c                 c   sb   dt j|| ||ftd }t j }|d |j_|d }|dkr&||k s*J d|d }	|d }
t|| D ]
}t| \||< }q8|j	|dd t|| D ]
}t| \||< }qP|}	 ||d
 krj|}
|jj}	t
|
|d
 | |	||d}||| |d
 |   |fV  t|D ]}t| \||| | < }q||d
 kr|}|j	|dd |d
 | }q^)a  
    Prepare batch in advance and shuffle them to reduce correlation inside batches (for ex when very long document is encountered).

    This function aggregates batches into a buffer and yields fixed-size batch size and seqlen with dimensions `(batch_size, seqlen, n_views)`,

    It uses a prefetch buffer to store batches in advance and shuffles them, the prefetch buffer is similar to `reservoir sampling`,
    but by block to preserve a smooth, easy and deterministic reloading. To ensure more uniform sequence sampling -> prefetch_size * batch_size * seq_len >> max_document_seqlength.

    Parameters:
    - iterator: An iterator that yields pairs of (sequence, state), where is a random sequence sampled from a corpus (as done by pack_tokens for example).
    - batch_size: The desired batch size.
    - prefetch_size: The number of batches to prefetch in advance.
    - seq_len (int): The length of the output sequences to be generated.
    - n_views (int): The number of shifted views to include in each output chunk.

    Yields:
    - numpy.ndarray: An array of shape `(batch_size, seq_len, n_views)` containing the packed tokens.
    - PrefetchState: The state required to resume prefetched batch. Contains also the internal of iterator.
    r   )dtyper(   r7   r   zAPrefetch state seq_idx should be in 0 <= seq_idx < prefetch_size.r+   r   Tr:   r+   r7   r(   r9   r8   )ro   onesr!   rp   rq   rr   rE   rangerv   shuffler6   copy)r   r9   r8   r5   r4   rE   prefetch_bufferrz   r7   
_rng_state	_it_stater   next_it_state_idx
pack_stater"   r"   r#   &batch_and_shuffle_prefetched_sequences  sJ   

"r   dataset_path
world_sizefile_patternc                 C   s   dd t | |D }t|}|dkrtd| d|   ||kr.|| }|d | }n
|| dks8J d|dksCJ d|  |S )Nc                 S   s   g | ]}t |qS r"   )r   ).0ri   r"   r"   r#   
<listcomp>  s    z,find_and_sanitize_chunks.<locals>.<listcomp>r   zNo valid chunks of pattern z in z3World size should be a multiple of number of chunkszNo valid chunks in )r
   globrk   loggerfatal)r   r   r   dataset_chunksn_chunks	n_discardr"   r"   r#   find_and_sanitize_chunks  s   r   rankc           	      C   sT   t | ||}|t| }g }|D ]}t|D ]}|t|d||dd qq|| S )aW  
    Distributes the chunk files in a dataset path to each worker.
    If world_size is smaller than the number of chunks, the extra chunks are discarded.
    Otherwise, world_size is assumed to be a multiple of number of chunks.
    In that case there are world_size//nb_chunks workers on each chunk file, reading with different offsets.
    r   r;   )r   rk   r   r]   r   )	r   r   r   r   r   n_ranks_per_chunkrank_to_jsonl_iterator_params
chunk_pathr   r"   r"   r#   distribute_data_to_rank  s    	r   seedc              	   C   sv   t  }|D ] }td| d| d|   ttj| ||||}|||< qtj	|||fj
j}	t| |||	d}
|
S )NzDistributing data to rank z for dataset z from root rj   )dictr   infor   osr/   joinro   rp   rq   rr   rE   r$   )r%   r&   r   r   r   r   data_path_to_jsonl_stater   rL   multi_rng_stater~   r"   r"   r#   init_choice_state"  s*   
r   tokenizer_name
image_size
patch_sizemax_num_tilesvision_input_typec                 C   sd   t | |||||d}t||	|
||d}td|||dd}tj|d ||fjj}t|d|||dS )N)r%   r&   r   r   r   r   r\   r   )r2   r+   r3   r4   r5   r:   r   )	r   r*   r1   ro   rp   rq   rr   rE   r6   )r%   r&   r9   r8   r5   r4   r   r   r   r-   r.   r   rP   r   r   r   r   r   r~   tokenizer_stater   prefetch_rng_stater"   r"   r#   
init_stateA  sD   r   c                 C   sL   t  }| d D ]}| d | }t|d |d |d |d |d ||< q|S )Nr&   r'   r   r   r   r   r   )r   rM   )multi_statepath_to_itersourcerL   r"   r"   r#   setup_sourcesy  s   
r   c                 c   s    | d }|d }|d }t |}t||d |d |d |d d}t||d |d |d	 |d
 }t||}t||d |d | d | d | d}|V  | D ]}|  qP|  d S )Nr+   r'   r%   r&   r(   )rh   r'   r%   r&   r(   r-   r.   r,   r/   r3   r4   r9   r8   )r   r5   r4   r9   r8   rE   )r   r   rg   r   r   rn   rI   )rE   r   r   r   r   data_itrJ   r"   r"   r#   build_dataloader  sF   
r   queue
stop_eventc              
   C   s   | 7}|D ]#}|  s#z	| j|dd W n ty   Y nw |  r|  r) n	qW d   dS W d   dS 1 s=w   Y  dS )z
    Producer function to fetch data from an iterable dataset and put it into a queue.
    Incorporates timeout management to avoid hanging on queue.put() when the queue is full.
    皙?timeoutN)is_setputr   )r   r   iterator_builderrN   itemr"   r"   r#   feed_buffer  s&   "r   producerc                 c   sH    | j du r z|jdd}|V  W n	 ty   Y nw | j du std)z
    Consumer function to process items from the queue.
    Handles cases where the queue might be empty by implementing timeouts on queue.get().
    Nr   r   zDData loader quit unexpectedly, real error has been raised previously)exitcodegetr   r=   )r   r   r   r"   r"   r#   consume_buffer  s   


	r   r   c                 c   s    t | d}t }tt|||fd}td |  t||}z:|V  W |  |	  |j
dd |jdu rGtd|j d |  ntd	|j d
|j  td dS |  |	  |j
dd |jdu r}td|j d |  ntd	|j d
|j  td w )zb
    Context manager to setup and manage asynchronous iteration with producer-consumer model.
    )maxsize)targetargszAsync dataloader startedg?r   NzKilling async data process z ...zAsync data process z exited with code zAsync dataloader cleaned up)r	   r   r   r   r   r   startr   setrI   r   r   pidkill)r   r   r   r   r   consumerr"   r"   r#   async_iterator  s:   






r   c                   @   s   e Zd ZU dZee ed< eedZ	e
eef ed< dZeed< dZeed< dZeed	< d
Zeed< dZeed< dZeed< dZeed< dZeed< dZee ed< dZee ed< dZee ed< dZee ed< eedZeed< dS )DataArgsNr%   )default_factoryr&      r9   i   r5   r4   *   r   Tr-   r.   
load_async@   r8   r   r   r   r   r`   )r   r   r   r%   r   r   r    r   r   r&   r   r)   r9   r!   r5   r4   r   r-   r0   r.   r   r8   r   r   r   r   r   r`   r"   r"   r"   r#   r     s    
 r   r   c                 C   s   t di d| jd| jd| jd| jd| jd| jd| jd|d	|d
| jj	d| jj
d| jd| jd| jd| jd| jd| jS )Nr%   r&   r5   r9   r8   r4   r   r   r   r   rP   r-   r.   r   r   r   r   r"   )r   r%   r&   r5   r9   r8   r4   r   r`   r,   r/   r-   r.   r   r   r   r   )r   r   r   r"   r"   r#   init_dataloader_state_from_args  sF   	
r   c                 C   s"   t t|}| jrt| j|S | S N)r   r   r   r   r8   )r   rE   data_builderr"   r"   r#   build_dataloader_from_args"  s   
r   r   )B
contextlibrB   loggingr   r   r   dataclassesr   r   	functoolsr   multiprocessingr   r   r	   multiprocessing.synchronize
EventClasspathlibr
   r   r   r   typingr   r   r   r   r   numpyro   core.tokenizerr   r   r   	getLoggerr   TRAIN_DATA_FILE_PATTERNr   r$   r*   r1   r6   r   r!   rH   rM   r0   rg   r)   r   r   r   r   r   r   r   r   r   contextmanagerr   r   r   r   r   r   r   r"   r"   r"   r#   <module>   sn  )
3

>




.
L
K



,
	

8*
