U
    Jcq                     @   sB   d Z ddlmZmZmZ dgZdee eeee  dddZdS )	up   Implements "Block Partitions of Sequences" by Imre Bárány et al.

Paper: https://arxiv.org/pdf/1308.2452.pdf

    )IteratorListTuplesolve   )sequence
partitionsreturnc                    st  dk rt d dtk r>t d d dtt dkrjdd	 D nfd
d	D fdd	td D g ttdfdd ttttf  d fdd}t| \}}t| \}}||d kr&fdd	t	dgdd  D S ||k rJ|d }|  d8  < n|d }|  d7  < ||krqqqdS )u   Splits a sequence into several partitions to minimize variance for each
    partition.

    The result might not be optimal. However, it can be done only in O(kn³),
    where k is the number of partitions and n is the length of the sequence.

    r   z'partitions must be a positive integer (z < 1)z.sequence is shorter than intended partitions (z < )r   c                 S   s   g | ]}d qS )r    ).0_r   r   [/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/pipeline/sync/_balance/blockpartition.py
<listcomp>'   s     zsolve.<locals>.<listcomp>c                    s   g | ]}|   qS r   r   r   x)maximumminimumr   r   r   )   s     c                    s   g | ]}  |d   qS )r   r   r   )nr   r   r   r   +   s     )ir	   c                    s0   | dkr| d  nd}|  }t  || S )Nr   r   )sum)r   startstop)normal_sequencesplitsr   r   
block_size-   s    zsolve.<locals>.block_size)r	   c                      s    fddt D S )Nc                 3   s   | ]} ||fV  qd S )Nr   )r   r   )r   r   r   	<genexpr>3   s     z-solve.<locals>.leaderboard.<locals>.<genexpr>)ranger   )r   r   r   r   leaderboard2   s    zsolve.<locals>.leaderboardc                    s   g | ]\}} || qS r   r   )r   r   j)r   r   r   r   D   s     N)

ValueErrorlenminmaxr   intfloatr   r   zip)r   r   r   max_sizepZmin_sizeqhr   )r   r   r   r   r   r   r   r   r   r      s0    " &	
N)r   )__doc__typingr   r   r   __all__r%   r   r   r   r   r   <module>   s   