a
    Sic\5                     @   s   d Z ddlZ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
 zddlmZ ddlmZ W n* ey   ddlZdd	 ZejjZY n0 g d
ZG dd de
jZdddZdd Zdd ZG dd deZdddZejeddZdS )zB
Support for random optimizers, including the random-greedy path.
    N)deque   )helperspaths)choices)seedc                    s(   t | tjj|  fdd|D ddS )Nc                    s   g | ]}|  qS  r   ).0wnormr   R/var/www/html/django/DPS/env/lib/python3.9/site-packages/opt_einsum/path_random.py
<listcomp>       z"random_choices.<locals>.<listcomp>r   )psize)sumnprandomchoice)
populationweightsr   r   r   random_choices   s    r   )RandomGreedyrandom_greedyrandom_greedy_128c                   @   sh   e Zd ZdZdddZed	d
 Zedd Zejdd Zdd Z	dd Z
dd Zdd Zdd ZdS )RandomOptimizera  Base class for running any random path finder that benefits
    from repeated calling, possibly in a parallel fashion. Custom random
    optimizers should subclass this, and the ``setup`` method should be
    implemented with the following signature::

        def setup(self, inputs, output, size_dict):
            # custom preparation here ...
            return trial_fn, trial_args

    Where ``trial_fn`` itself should have the signature::

        def trial_fn(r, *trial_args):
            # custom computation of path here
            return ssa_path, cost, size

    Where ``r`` is the run number and could for example be used to seed a
    random number generator. See ``RandomGreedy`` for an example.


    Parameters
    ----------
    max_repeats : int, optional
        The maximum number of repeat trials to have.
    max_time : float, optional
        The maximum amount of time to run the algorithm for.
    minimize : {'flops', 'size'}, optional
        Whether to favour paths that minimize the total estimated flop-count or
        the size of the largest intermediate created.
    parallel : {bool, int, or executor-pool like}, optional
        Whether to parallelize the random trials, by default ``False``. If
        ``True``, use a ``concurrent.futures.ProcessPoolExecutor`` with the same
        number of processes as cores. If an integer is specified, use that many
        processes instead. Finally, you can supply a custom executor-pool which
        should have an API matching that of the python 3 standard library
        module ``concurrent.futures``. Namely, a ``submit`` method that returns
        ``Future`` objects, themselves with ``result`` and ``cancel`` methods.
    pre_dispatch : int, optional
        If running in parallel, how many jobs to pre-dispatch so as to avoid
        submitting all jobs at once. Should also be more than twice the number
        of workers to avoid under-subscription. Default: 128.

    Attributes
    ----------
    path : list[tuple[int]]
        The best path found so far.
    costs : list[int]
        The list of each trial's costs found so far.
    sizes : list[int]
        The list of each trial's largest intermediate size so far.

    See Also
    --------
    RandomGreedy
        NflopsF   c                 C   sd   |dvrt d|| _|| _|| _t|| _|| _|| _g | _	g | _
tdtdd| _d| _d S )N)r   r   z.`minimize` should be one of {'flops', 'size'}.infr   )
ValueErrormax_repeatsmax_timeminimizer   get_better_fnbetterparallelpre_dispatchcostssizesfloatbest_repeats_start)selfr"   r#   r$   r'   r(   r   r   r   __init__U   s    zRandomOptimizer.__init__c                 C   s   t | jd S )z$The best path found so far.
        ssa_path)r   ssa_to_linearr,   r.   r   r   r   pathg   s    zRandomOptimizer.pathc                 C   s   | j S N)	_parallelr2   r   r   r   r'   m   s    zRandomOptimizer.parallelc                 C   s   t | ddr| j  || _d| _|du r4d | _d S |du rZddlm} | | _d| _d S t|tj	rddlm} ||| _d| _d S || _d S )N_managing_executorFTr   )ProcessPoolExecutor)
getattr	_executorshutdownr5   r6   concurrent.futuresr7   
isinstancenumbersNumber)r.   r'   r7   r   r   r   r'   q   s$    

c                 c   sn   t  | _|D ]D}t| j| jk r@| j| jj||g|R   q| j  V  q| jrj| j  V  qRdS )zVLazily generate results from an executor without submitting all jobs at once.
        N)	r   _futureslenr(   appendr9   submitpopleftresult)r.   repeatstrial_fnargsrr   r   r   _gen_results_parallel   s    z%RandomOptimizer._gen_results_parallelc                 C   s"   | j d ur| jD ]}|  qd S r4   )r9   r?   cancel)r.   fr   r   r   _cancel_futures   s    

zRandomOptimizer._cancel_futuresc                 C   s   t d S r4   )NotImplementedError)r.   inputsoutput	size_dictr   r   r   setup   s    zRandomOptimizer.setupc                    s  |  ||| | jd ur t }| |||\ | jt| j }|| j }t||}| j	d urp| 
| }	n fdd|D }	|	D ]\}
}}| j| | j| | ||| jd | jd }|r|| jd< || jd< |
| jd< | jd urt || j kr qq|   | jS )Nc                 3   s   | ]}|g R  V  qd S r4   r   )r	   rH   Z
trial_argsrF   r   r   	<genexpr>   r   z+RandomOptimizer.__call__.<locals>.<genexpr>r   r   r0   )_check_args_against_first_callr#   timerQ   r-   r@   r)   r"   ranger9   rI   rA   r*   r&   r,   rL   r3   )r.   rN   rO   rP   memory_limitt0Zr_startZr_stoprE   Ztrialsr0   costr   Zfound_new_bestr   rR   r   __call__   s,    






zRandomOptimizer.__call__c                 C   s   t | ddr| j  d S )Nr6   F)r8   r9   r:   r2   r   r   r   __del__   s    zRandomOptimizer.__del__)r   Nr   Fr   )__name__
__module____qualname____doc__r/   propertyr3   r'   setterrI   rL   rQ   rZ   r[   r   r   r   r   r      s   6



)r      Tc                    s  d}g }| rT||k rTt | \}}}	}
||vs|	|vr8q||||	|
f |d7 }q|dkr`dS |dkrp|d S dd |D }|d  |rtdt 9 dkr fdd|D }n fdd|D }tt||d	\}||\}}}	}
|D ]}t | | q|||	|
fS )
a  A contraction 'chooser' that weights possible contractions using a
    Boltzmann distribution. Explicitly, given costs ``c_i`` (with ``c_0`` the
    smallest), the relative weights, ``w_i``, are computed as:

        w_i = exp( -(c_i - c_0) / temperature)

    Additionally, if ``rel_temperature`` is set, scale ``temperature`` by
    ``abs(c_0)`` to account for likely fluctuating cost magnitudes during the
    course of a contraction.

    Parameters
    ----------
    queue : list
        The heapified list of candidate contractions.
    remaining : dict[str, int]
        Mapping of remaining inputs' indices to the ssa id.
    temperature : float, optional
        When choosing a possible contraction, its relative probability will be
        proportional to ``exp(-cost / temperature)``. Thus the larger
        ``temperature`` is, the further random paths will stray from the normal
        'greedy' path. Conversely, if set to zero, only paths with exactly the
        same cost as the best at each step will be explored.
    rel_temperature : bool, optional
        Whether to normalize the ``temperature`` at each step to the scale of
        the best cost. This is generally beneficial as the magnitude of costs
        can vary significantly throughout a contraction.
    nbranch : int, optional
        How many potential paths to calculate probability for and choose from
        at each step.

    Returns
    -------
    cost, k1, k2, k12
    r   r   Nc                 S   s   g | ]}|d  d  qS )r   r   )r	   r   r   r   r   r     r   z#thermal_chooser.<locals>.<listcomp>g        c                    s   g | ]}| krd ndqS )r   r   r   r	   c)cminr   r   r     r   c                    s    g | ]}t |    qS r   )mathexprc   re   temperaturer   r   r     r   )r   )	heapqheappoprA   maxabsr   rV   popheappush)queue	remainingnbranchri   rel_temperaturenr   rY   k1k2k12r)   ZenergiesZchosenotherr   rh   r   thermal_chooser   s0    #
ry   c              	   C   s   t tt|}t|}ttt|}d}d}| D ]f\}}t||||||\}	}
|| || |	t| |
|	 ||
7 }t|t|	|}q2||fS )z3Compute the flops and max size of an ssa path.
    r   )listmap	frozensetsetrV   r@   r   calc_k12_flopsdiscardaddrA   rl   r   compute_size_by_dict)r0   rN   rO   rP   rq   
total_costmax_sizeijrw   flops12r   r   r   ssa_path_compute_cost  s    


r   c           	      C   sB   | dkrd}t |  t|||||}t||||\}}|||fS )zKA single, repeatable, greedy trial run. Returns ``ssa_path`` and cost.
    r   N)random_seedr   ssa_greedy_optimizer   )	rH   rN   rO   rP   	choose_fncost_fnr0   rY   r   r   r   r   _trial_greedy_ssa_path_and_cost3  s    r   c                       s6   e Zd ZdZd fdd	Zedd	 Zd
d Z  ZS )r   a-  

    Parameters
    ----------
    cost_fn : callable, optional
        A function that returns a heuristic 'cost' of a potential contraction
        with which to sort candidates. Should have signature
        ``cost_fn(size12, size1, size2, k12, k1, k2)``.
    temperature : float, optional
        When choosing a possible contraction, its relative probability will be
        proportional to ``exp(-cost / temperature)``. Thus the larger
        ``temperature`` is, the further random paths will stray from the normal
        'greedy' path. Conversely, if set to zero, only paths with exactly the
        same cost as the best at each step will be explored.
    rel_temperature : bool, optional
        Whether to normalize the ``temperature`` at each step to the scale of
        the best cost. This is generally beneficial as the magnitude of costs
        can vary significantly throughout a contraction. If False, the
        algorithm will end up branching when the absolute cost is low, but
        stick to the 'greedy' path when the cost is high - this can also be
        beneficial.
    nbranch : int, optional
        How many potential paths to calculate probability for and choose from
        at each step.
    kwargs
        Supplied to RandomOptimizer.

    See Also
    --------
    RandomOptimizer
    memory-removed-jitter      ?Trb   c                    s.   || _ || _|| _|| _t jf i | d S r4   )r   ri   rs   rr   superr/   )r.   r   ri   rs   rr   kwargs	__class__r   r   r/   b  s
    zRandomGreedy.__init__c                 C   s&   | j dkrdS tjt| j| j | jdS )zThe function that chooses which contraction to take - make this a
        property so that ``temperature`` and ``nbranch`` etc. can be updated
        between runs.
        r   N)ri   rr   rs   )rr   	functoolspartialry   ri   rs   r2   r   r   r   r   i  s    
zRandomGreedy.choose_fnc                 C   s   t }|||| j| jf}||fS r4   )r   r   r   )r.   rN   rO   rP   fnrG   r   r   r   rQ   w  s    zRandomGreedy.setup)r   r   Trb   )	r\   r]   r^   r_   r/   r`   r   rQ   __classcell__r   r   r   r   r   B  s
   
r   c                 K   s   t f i |}|| |||S )z
    )r   )rN   rO   idx_dictrW   optimizer_kwargs	optimizerr   r   r   r   }  s    r   r   )r"   )rb   r   T)N)r_   r   rj   rf   r=   rU   collectionsr    r   r   r   r   r   r   r   ImportErrornumpyr   __all__PathOptimizerr   ry   r   r   r   r   r   r   r   r   r   r   <module>   s.    7
J;
