
    &`i                        d dl 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	m
Z
mZmZmZmZ d dlZd dlmZ d dlmZ d dlmZ d dlmZmZ d dlmZ erd d	lmZ  e j        e          Z  ed
           G d d                      Z! ed
           G d de!                      Z" e!d          Z# e!d          Z$ ed
           G d de                      Z%dS )    N)deepcopy)	TYPE_CHECKINGAnyCallableDictListOptionalSetTupleUnion_sum_bundles)PlacementGroupFactory)Trial)FIFOSchedulerTrialScheduler)	PublicAPI)TuneControllerbeta)	stabilityc                   X   e Zd ZdZ	 	 	 	 d7dedeeeef                  de	deeeef                  fd	Z
d
edeeef         defdZdddeeef         fdZdedeeef         fdZdeeeef                  deeef         fdZdeeef         defdZ	 d8deeeef                  deeeef                  deeef         dede	f
dZ	 	 	 d9deeef         dedede	de	f
d Zdeeeef                  deeef         d!e	deeeef                  fd"Zdeeef         d!e	deeeef                  fd#Zddd$deeeef                  deeef         d%ed&ede	de	fd'Zdeeeef                  d(eeeef                  deeeef                  fd)Z	 	 	 d:deeeef                  d(eeeeef                           d*ee         d+ee         fd,Zd-ed.ee         d(eeeef                  deeef         d/ed0ed1ed2edeeeef                  fd3Zddd-edeeef         d4d5dee         f
d6ZdS );DistributeResourcesae  This class creates a basic uniform resource allocation function.

    The function naively balances free resources (CPUs and GPUs) between
    trials, giving them all equal priority, ensuring that all resources
    are always being used. The free resources will be placed in new bundles.
    The function assumes that all bundles are equal (there is no "head"
    bundle).

    If for some reason a trial ends up with
    more resources than there are free ones, it will adjust downwards.
    It will also ensure that trial as at least as many resources as
    it started with (``base_trial_resource``).

    The function returns a new ``PlacementGroupFactory`` with updated
    resource requirements, or None. If the returned
    ``PlacementGroupFactory`` is equal by value to the one the
    trial has currently, the scheduler will skip the update process
    internally (same with None).

    If you wish to implement your own resource distribution logic,
    you can do so by extending this class, as it provides several
    generic methods. You can also implement a function instead.

    Args:
        add_bundles: If True, create new bundles from free resources.
            Otherwise, spread them among base_trial_resource bundles.
        increase_by: A dict with key-value
            pairs representing an atomic unit of resources (name-amount)
            the trial will be increased by. If not set, the trial will
            increase by 1 CPU/GPU.
        increase_by_times: If set to >=1 and ``increase_by`` is set,
            the trial will increase by maximum of
            ``increase_by_times * increase_by`` resources. If set to <1,
            no upper limit is set. Ignored if ``increase_by`` is not set.
        reserve_resources: A dict of
            resource_name-amount pairs representing the resources
            that will not be allocated to resized trials.
    FNadd_bundlesincrease_byincrease_by_timesreserve_resourcesc                 F    || _         |pi | _        || _        |pi | _        d S N)r   r   r   r   )selfr   r   r   r   s        /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/schedulers/resource_changing_scheduler.py__init__zDistributeResources.__init__>   s4     '&,"!2!2!8b    base_trial_resourceresultreturnc                    t          |t                    st          | j        j         d          | j        s=t          |j                  dk    r%t          dt          |j                   d          |d         dk     rdS dS )z>Return False if we should keep the current resources outright.z' only supports PlacementGroupFactories.   zYIf `add_bundles` is False, the number of bundles in `resources_per_trial` must be 1 (got z).training_iterationFT)
isinstancer   
ValueError	__class____name__r   lenbundles)r    r$   r%   s      r!   	_validatezDistributeResources._validateJ   s     -/DEE 	>*SSS    	C(;(C$D$Dq$H$H=/788= = =   &'!++5tr#   tune_controllerr   c                     |j                                         | j                            dd          z
  }|j                                         | j                            dd          z
  }||fS )zBGet the number of CPUs and GPUs avaialble in total (not just free)CPUr   GPU)_resource_updaterget_num_cpusr   getget_num_gpus)r    r1   total_available_cpustotal_available_gpuss       r!   _get_total_available_resourcesz2DistributeResources._get_total_available_resources_   sx    
 -::<<$((223 	
 -::<<$((223 	 $%999r#   tc                     |j         j                            dd          |j         j                            dd          fS )z7Check how many CPUs and GPUs a trial is using currentlyr3   r   r4   )placement_group_factoryrequired_resourcesr7   )r    r<   s     r!   _get_used_cpus_and_gpusz+DistributeResources._get_used_cpus_and_gpusm   s@     %8<<UAFF%8<<UAFF
 	
r#   r/   c                 .    |sdddS t          |          S )z&Get total sums of resources in bundlesr   r3   r4   r   )r    r/   s     r!   _get_resources_from_bundlesz/DistributeResources._get_resources_from_bundlest   s(      	(Q'''G$$$r#   bundlec                 \    |                     dd          p|                     dd           S )Nr3   r   r4   )r7   )r    rD   s     r!   _is_bundle_emptyz$DistributeResources._is_bundle_empty|   s,    JJua((@FJJua,@,@AAr#   	bundles_a	bundles_blimit_to_increase_by_timesmax_increase_by_timesc                     |r9|dk    r! j         dk    rt          | j                   }n j         dk    r j         } j        r. fd|D              fd|D             z   }|dk    r
|d|         }n|pi g}|pi g}|d                             dd          |d                             dd          z   |d                             dd          |d                             dd          z   dg}|dk    rxt          |d         d         |                    dd          |z            |d         d<   t          |d         d         |                    dd          |z            |d         d<   |S )a  Add two bundles together.

        If ``limit_to_increase_by_times`` is True, ``self.increase_by_times`` > 0
        and ``max_increase_by_times`` > 0, ensure that the resulting number of
        bundles is not above ``min(max_increase_by_times, self.increase_by_times)``.

        If ``limit_to_increase_by_times`` is True and ``self.increase_by_times`` > 0,
        ensure that the resulting number of bundles is not above
        `self.increase_by_times``.
        r   c                 >    g | ]}                     |          |S  rF   .0br    s     r!   
<listcomp>z8DistributeResources._add_two_bundles.<locals>.<listcomp>   s,    LLLQ43H3H3K3KLqLLLr#   c                 >    g | ]}                     |          |S rM   rN   rO   s     r!   rR   z8DistributeResources._add_two_bundles.<locals>.<listcomp>   sC     P P PD,A,A!,D,DPP P Pr#   Nr3   r4   rB   )r   minr   r7   )r    rG   rH   r   rI   rJ   r/   s   `      r!   _add_two_bundlesz$DistributeResources._add_two_bundles   s   $ & 	?$q((T-Ca-G-G(+)4+A) )%% '!++(,(>% 	LLLL)LLL P P P P$P P P G %q((!"8#8"89!)bTI!)bTI %Q<++E155	!8H8HPQ8R8RR$Q<++E155	!8H8HPQ8R8RR G %q(($'AJu%OOE1--0EE% %
5! %(AJu%OOE1--0EE% %
5!
 r#   r   cpusgpusmax_multiplierc                    |                     dd          rU|                     dd          r?t          ||                     dd          z  ||                     dd          z            }nI|                     dd          r||                     dd          z  }n||                     dd          z  }|dk    r|dk    rt          ||          }t          |          S )zRGet how many times ``increase_by`` bundles
        occur in ``cpus`` and ``gpus``.r3   r   r4   )r7   rT   int)r    r   rV   rW   rX   
multipliers         r!   _get_multiplierz#DistributeResources._get_multiplier   s     ??5!$$ 	;)B)B 	;q111q111 JJ __UA&& 	;!:!::JJ!:!::JA*q..^Z88J:r#   r[   c                    t          |           }| j        r|d|         }nt          |          }|d         dxx         |                    dd          |z  z  cc<   |d         dxx         |                    dd          |z  z  cc<   t	          |d         d         d          |d         d<   t	          |d         d         d          |d         d<   |S )z?Remove ``multiplier`` ``increase_by`` bundles from ``bundles``.Nr   r3   r4   )absr   r   r7   max)r    r/   r   r[   s       r!   _remove_bundlesz#DistributeResources._remove_bundles   s     *oo%
 	:kzk*GGw''GAJu!:!:Z!GGAJu!:!:Z!GG #GAJu$5q 9 9GAJu #GAJu$5q 9 9GAJur#   c                     t          |          }| j        r|gt          |          z  }nGi g}|                    dd          |z  |d         d<   |                    dd          |z  |d         d<   |S )zICreate a list of new bundles containing ``increase_by`` * ``multiplier``.r3   r   r4   )r^   r   rZ   r7   )r    r   r[   r/   s       r!   _create_new_bundlesz'DistributeResources._create_new_bundles   s}     __
 	G"mc*oo5GGdG +q 9 9J FGAJu +q 9 9J FGAJur#   )rX   rJ   	free_cpus	free_gpusc                    |                      ||||          }|dk     r|                     |||          }n5|dk    r/|                     ||          }|                     |||d|          }|S )zUGiven free resources, increase/decrease the number of bundles in
        ``bundles``.r   T)r\   r`   rb   rU   )	r    r/   r   rc   rd   rX   rJ   r[   bundles_to_adds	            r!   #_modify_bundles_with_free_resourcesz7DistributeResources._modify_bundles_with_free_resources   s     ))I~
 

 >>**7KLLGG!^^!55k:NNN++d<Q G r#   base_bundlesc                 L   | j         r|t          |          d         }n|sdddg}|sdddg}|d                             dd          |d                             dd          z
  |d                             dd          |d                             dd          z
  dg}|S )z6Return the difference between bundles and base_bundlesNr   rB   r3   r4   )r   r.   r7   )r    r/   rh   added_bundless       r!   _get_added_bundlesz&DistributeResources._get_added_bundles  s      	#C$5$5$7$78MM 1#$Q//0 6()! 4 45 #1:>>%33l1o6I6I%QR6S6SS"1:>>%33l1o6I6I%QR6S6SS M r#   max_added_cpusmax_added_gpusc                    |s;| j         dk    r$| j                            dd          | j         z  }nt          j        }|s;| j         dk    r$| j                            dd          | j         z  }nt          j        }|                     |r|                     ||          n|          }|                    dt          j                   |k     p$|                    dt          j                   |k     }|S )Nr   r3   r4   )r   r   r7   npinfrC   rk   )r    r/   rh   rl   rm   added_resourcesrets          r!   _are_bundles_below_limitz,DistributeResources._are_bundles_below_limit  s     	(%))!%!1!5!5eQ!?!?$BX!X!# 	(%))!%!1!5!5eQ!?!?$BX!X!#::>JWD##G\:::PW
 
 w//.@ D""526'22^C 	 
r#   trial
all_trialsr9   r:   	used_cpus	used_gpusc	                    d t          t          |                    D             }	||z
  }
||z
  }|                     |          }||                    dd          t          |          z  z
  }||                    dd          t          |          z  z
  }d}d}t	                      }t          |          t          |          k     r||                    dd          k    rm||                    dd          k    rR|t          |	          z  }t          |	|                   }|                     |	|         |||d          |	|<   |                     |                     |	|         |                    }|                    dd          s,|                    dd          s|                    |           n|dk    r|dz  }||                    dd          z  }||                    dd          z  }|dz  }t          |          t          |          k     r5||                    dd          k    r||                    dd          k    R|                     |                     |j	        j
        |          ||
||          S )zReturns updated added bundles.c                 *    g | ]}t                      S rM   )list)rP   _s     r!   rR   z>DistributeResources._get_new_added_bundles.<locals>.<listcomp>?  s    )Q)Q)QQ$&&)Q)Q)Qr#   r3   r   r4   r(   )rX   )rJ   )ranger.   rC   r7   setr   rg   rk   addr>   r/   )r    rt   ru   rh   r   r9   r:   rv   rw   upper_limit_all_trials_bundlesrc   rd   base_resourcesupper_limit_cpus_to_distributeupper_limit_gpus_to_distributerJ   itrials_at_limitidxold_bundlesrq   s                        r!   _get_new_added_bundlesz*DistributeResources._get_new_added_bundles3  s    *R)Q%J:P:P)Q)Q)Q&(94	(94	99,GG)=ua((3z??:*
& *>ua((3z??:*
& !" %%  3z??22 /+//%2K2KKK.+//%2K2KKKc8999C"#A##FGGK 88.s3..  9   + #>>''237  O
 #&&ua00 +9L9LUTU9V9V +##C((((%*%*o.A.A%.K.KK**o.A.A%.K.KK*FA9   3z??22 /+//%2K2KKK.+//%2K2KKK8 77##-5|  "7 8 
 
 	
r#   	schedulerResourceChangingSchedulerc           
      \    |j         }                     ||          sdS |t          dddg          } j        rU j        }                     |          rJ |                    dd          dk    r|                    dd          dk    sJ n? j        r|j        d         }n*|j        d                             dd          rddi}nddi}t          |j                  } 	                    |	          \  }}	|
                                }
 fd
|
D             }t          | \  }}t          |          }t          |          }                     ||
||||	||          }                     |||d          }t          |g|j        R d|j        i|j        }|j        |_        |S )a  Run resource allocation logic.

        Returns a new ``PlacementGroupFactory`` with updated
        resource requirements, or None. If the returned
        ``PlacementGroupFactory`` is equal by value to the one the
        trial has currently, the scheduler will skip the update process
        internally (same with None).

        Args:
            tune_controller: Trial runner for this Tune run.
                Can be used to obtain information about other trials.
            trial: The trial to allocate new resources to.
            result: The latest results of trial.
            scheduler: The scheduler calling
                the function.
        )r$   r%   Nr(   r   rB   r3   r4   r   )r1   c                 :    g | ]}                     |          S rM   )r@   )rP   r<   r    s     r!   rR   z0DistributeResources.__call__.<locals>.<listcomp>  s'    RRR!d::1==RRRr#   Fstrategy)base_trial_resourcesr0   r   r   rF   r7   r   r/   r   r;   get_live_trialszipsumr   rU   _argsr   _kwargs_head_bundle_is_empty)r    r1   rt   r%   r   r$   r   rh   r9   r:   ru   used_cpus_and_gpusrv   rw   rj   new_bundlespgfs   `                r!   __call__zDistributeResources.__call__~  s*   2 (<~~2Ef~UU 	4 &"719M9M8N"O"O 		%*K,,[99999??5!,,11kooeQ6O6OST6T6T6TT6T 	%-5b9KK (+//q99 	% !*KK !*K 3 ;<<
 ///PP	
   %4466
RRRRzRRR"$67	9	NN		NN	33  	
 	
 ++-e
 
 $
 !&
 
 
(1
 ")	
 
 %8$M!
r#   )FNr   N)r   )r   r   r   )NNN)r-   
__module____qualname____doc__boolr	   r   strfloatrZ   r"   r   r   r0   r   r;   r   r@   r   rC   rF   rU   r\   r`   rb   rg   rk   rs   r   r   rM   r#   r!   r   r      s7       % %R "26!#8<
9 
9
9 d3:./
9 	
9
 $De$45
9 
9 
9 
9#8BFsCx.	   *:/:	ue|	: : : :
 
53F 
 
 
 
%De,-%	c5j	% % % %BtCJ'7 BD B B B B &(3 3S%Z()3 S%Z()3 #u*%	3
 %)3  #3 3 3 3p   #u*%  	
  
   .d3:&' #u*% 	
 
d3:	   $#u*%  
d3:		   0 !%'  d3:&' #u*% 	
    #   0De,-=A$sEzBR=S	d3:	   , :>*.*. d3:&' tDe$456 !	
 !   4I
I
 KI
 4U
+,	I

 #u*%I
 $I
 $I
 I
 I
 
d3:	I
 I
 I
 I
VQ)Q Q S#X	Q
 /Q 
'	(Q Q Q Q Q Qr#   r   c                   6    e Zd ZdZ	 	 	 	 	 	 ddedeeeef                  de	deeeef                  d	ee         d
ee         f fdZ
edefd            Zdedee         deeeef                  deeef         dededededeeeef                  fdZ xZS )DistributeResourcesToTopJoba  This class creates a "TopJob" resource allocation function.

    The function will assign all of the free resources to the best
    performing trial (as defined by ``metric`` and ``mode``). The
    previous best trials will not have their resources deallocated,
    unless in the case outlined below.

    If for some reason a trial ends up with
    more resources than there are free ones, it will adjust downwards.
    It will also ensure that trial as at least as many resources as
    it started with (``base_trial_resource``).

    The function returns a new ``PlacementGroupFactory`` with updated
    resource requirements, or None. If the returned
    ``PlacementGroupFactory`` is equal by value to the one the
    trial has currently, the scheduler will skip the update process
    internally (same with None).

    Args:
        add_bundles: If True, create new bundles from free resources.
            Otherwise, spread them among base_trial_resource bundles.
        increase_by: A dict with key-value
            pairs representing an atomic unit of resources (name-amount)
            the trial will be increased by. If not set, the trial will
            increase by 1 CPU/GPU.
        increase_by_times: If set to >=1 and ``increase_by`` is set,
            the trial will increase by maximum of
            ``increase_by_times * increase_by`` resources. If set to <1,
            no upper limit is set. Ignored if ``increase_by`` is not set.
        reserve_resources: A dict of
            resource_name-amount pairs representing the resources
            that will not be allocated to resized trials.
            is that the attribute should increase monotonically.
        metric: The training result objective value attribute. Stopping
            procedures will use this attribute. If None, will use the metric
            of the scheduler.
        mode: One of {min, max}. Determines whether objective is
            minimizing or maximizing the metric attribute. If None, will use the metric
            of the scheduler.

    FNr   r   r   r   r   metricmodec                 l    t                                          ||||           || _        || _        d S r   )superr"   r   r   )r    r   r   r   r   r   r   r,   s          r!   r"   z$DistributeResourcesToTopJob.__init__  s7     	k3DFWXXX			r#   r&   c                 P    | j         dvrt          d          | j         dk    rdS dS )N)rT   r_   z1The mode parameter can only be either min or max.r_   g      ?g      )r   r+   r    s    r!   
_metric_opz&DistributeResourcesToTopJob._metric_op  s5    9N**PQQQ93tr#   rt   ru   rh   r9   r:   rv   rw   c	                 ~     j         t          d          ||z
  }	||z
  }
t          | fd          }                     |j        j                  }t           fd|D             |d                   }|j        |j        k    r                     ||	|
          dk    r|S  	                    |||	|
          S )NzThe metric parameter cannot be None. The parameter can be set in either `DistributeResourcesToTopJob`, the base scheduler or in `tune.TuneConfig()` (highest to lowest priority).c                 j    j          | j                            j        t          j                  z  S r   )r   last_resultr7   r   ro   rp   )r<   r    s    r!   <lambda>zDDistributeResourcesToTopJob._get_new_added_bundles.<locals>.<lambda>*  s'    4?*Q]->->t{BF-S-SS r#   )keyc              3   \   K   | ]&}                     |j        j                  "|V  'd S r   )rs   r>   r/   )rP   r<   rh   r    s     r!   	<genexpr>zEDistributeResourcesToTopJob._get_new_added_bundles.<locals>.<genexpr>2  sX        00-5|      r#   r   )
r   r+   sortedrk   r>   r/   nexttrial_idr\   rg   )r    rt   ru   rh   r   r9   r:   rv   rw   rc   rd   sorted_trialsrj   
best_trials   `  `          r!   r   z2DistributeResourcesToTopJob._get_new_added_bundles  s     ;D   )94	(94	SSSS
 
 

 //)1<
 
     &   !	
 	

 Nj111$$[)YGG1LL  77	
 
 	
r#   )FNr   NNN)r-   r   r   r   r   r	   r   r   r   rZ   r"   propertyr   r   r   r   __classcell__r,   s   @r!   r   r     s{       ( (X "26!#8< $"  d3:./ 	
 $De$45  sm      E    X5
5
 K5
 4U
+,	5

 #u*%5
 $5
 $5
 5
 5
 
d3:	5
 5
 5
 5
 5
 5
 5
 5
r#   r   F)r   Tc                       e Zd ZdZdefdee         deedee	e
ef         d gee         f                  ddf fdZed             Zedee         fd	            Zd
ee
         dee
         defdZdddefdZdddefdZdddede	de
fdZdddede	fdZdddefdZdddee         fdZde
fdZde
fdZde
fdZdedee	ef         defdZdedefdZdddede	deeeef                  fdZ  xZ!S )r   a  A utility scheduler to dynamically change resources of live trials.

    .. versionadded:: 1.5.0

    .. note::
        Experimental. API may change in future releases.

    The ResourceChangingScheduler works by wrapping around any other
    scheduler and adjusting the resource requirements of live trials
    in response to the decisions of the wrapped scheduler
    through a user-specified ``resources_allocation_function``.

    An example of such a function can be found in
    :doc:`/tune/examples/includes/xgboost_dynamic_resources_example`.

    If the functional API is used, the current trial resources can be obtained
    by calling `tune.get_trial_resources()` inside the training function.
    The function should be able to
    :ref:`load and save checkpoints <tune-function-trainable-checkpointing>`
    (the latter preferably every iteration).

    If the Trainable (class) API is used, you can obtain the current trial
    resources through the ``Trainable.trial_resources`` property.

    Cannot be used if ``reuse_actors`` is True in ``tune.TuneConfig()``. A ValueError
    will be raised in that case.

    Args:
        base_scheduler: The scheduler to provide decisions
            about trials. If None, a default FIFOScheduler will be used.
        resources_allocation_function: The callable used to change
            live trial resource requiements during tuning. This callable
            will be called on each trial as it finishes one step of training.
            The callable must take four arguments: ``TrialRunner``, current
            ``Trial``, current result :class:`dict` and the
            ``ResourceChangingScheduler`` calling it. The callable must
            return a ``PlacementGroupFactory``
            or None (signifying no need for an update). If
            ``resources_allocation_function`` is None, no resource
            requirements will be changed at any time.
            By default, :class:`DistributeResources` will be used,
            distributing available CPUs and GPUs over all running trials
            in a robust way, without any prioritization.

    Warning:
        If the ``resources_allocation_function`` sets trial resource
        requirements to values bigger than possible, the trial will
        not run. Ensure that your callable accounts for that possibility
        by setting upper limits. Consult :class:`DistributeResources`
        to see how that may be done.

    Example:
        .. code-block:: python

            base_scheduler = ASHAScheduler(max_t=16)
            def my_resources_allocation_function(
                tune_controller: "TuneController",
                trial: Trial,
                result: Dict[str, Any],
                scheduler: "ResourceChangingScheduler"
            ) -> Optional[Union[PlacementGroupFactory, Resource]]:
                # logic here
                # usage of PlacementGroupFactory is strongly preferred
                return PlacementGroupFactory(...)
            scheduler = ResourceChangingScheduler(
                            base_scheduler,
                            my_resources_allocation_function
                        )

        See :doc:`/tune/examples/includes/xgboost_dynamic_resources_example` for a
        more detailed example.
    Nbase_schedulerresources_allocation_functionr   r&   c                 
   t                                                       |t          j        d           || _        |pt                      | _        d | _        i | _        t                      | _
        d | _        d | _        d S )Nz`resources_allocation_function` is None. No resource requirements will be changed at any time. Pass a correctly defined function to enable functionality.)r   r"   warningswarn_resources_allocation_functionr   _base_scheduler_base_trial_resources_trials_to_reallocater}   _reallocated_trial_ids_metric_mode)r    r   r   r,   s      r!   r"   z"ResourceChangingScheduler.__init__  s     	(0MF  
 /L+-@FJ"  	" 14#


r#   c                     | j         j        S r   )r   r   r   s    r!   r   z ResourceChangingScheduler.metric  s    #++r#   c                     | j         S r   )r   r   s    r!   r   z.ResourceChangingScheduler.base_trial_resources  s    ))r#   r   r   c                 F    || _         || _         | j        j        ||fi |S r   )r   r   r   set_search_properties)r    r   r   specs       r!   r   z/ResourceChangingScheduler.set_search_properties  s2     
9t#9&$OO$OOOr#   r1   rt   c           	          | j         |j        | _         n>|j        | j        vr0|j        }|| j         k    rt	          d| j          d| d| d           | j        j        ||fi |S )Nz^ResourceChangingScheduler doesn't support trials with varying base resources. First trial had z, trial z has .)r   r>   r   r   RuntimeErrorr   on_trial_add)r    r1   rt   kwargstrial_resourcess        r!   r   z&ResourceChangingScheduler.on_trial_add  s    %-).)FD&&
 ^4#>>>#;O$"<<<"*1* *;@* * '* * *   1t#0%RR6RRRr#   c                 *     | j         j        ||fi |S r   )r   on_trial_errorr    r1   rt   r   s       r!   r   z(ResourceChangingScheduler.on_trial_error  s"    2t#2?ETTVTTTr#   r%   c                     | j                             |||          }|t          j        k    r/|                     |||          }|r|| j        |<   t          j        S |S r   )r   on_trial_resultr   CONTINUE$reallocate_trial_resources_if_neededr   PAUSE)r    r1   rt   r%   base_scheduler_decisionnew_resourcess         r!   r   z)ResourceChangingScheduler.on_trial_result  sv     #'"6"F"FUF#
 #
 #n&=== EE M  ,4A*51%++&&r#   c                 ,     | j         j        |||fi |S r   )r   on_trial_complete)r    r1   rt   r%   r   s        r!   r   z+ResourceChangingScheduler.on_trial_complete  s2     6t#5UF
 
.4
 
 	
r#   c                 *     | j         j        ||fi |S r   )r   on_trial_remover   s       r!   r   z)ResourceChangingScheduler.on_trial_remove  s$     4t#3OUUUfUUUr#   c                 `   t          |dd          rt          d          d}i }| j                                        D ]U\  }}|j        t
          j        k    r#|||<   t                              | d           =|p| 	                    ||          }V|| _         | j
        j        |fi |}|S )N_reuse_actorsFzResourceChangingScheduler cannot be used with `reuse_actors=True`. FIX THIS by setting `reuse_actors=False` in `tune.TuneConfig()`.z# is still running, skipping for now)getattrr+   r   itemsstatusr   RUNNINGloggerdebugset_trial_resourcesr   choose_trial_to_run)r    r1   r   any_resources_changednew_trials_to_reallocatert   r   s          r!   r   z-ResourceChangingScheduler.choose_trial_to_run  s     ?OU;; 	?   !&#% $($>$D$D$F$F 	 	 E=|u},,2?(/JJJKKK$9 %T=U=U}> >!! &>"8$8SSFSSr#   c                 :    d| j                                          S )Nz(ResourceChangingScheduler) )r   debug_stringr   s    r!   r   z&ResourceChangingScheduler.debug_string  s    V1E1R1R1T1TVVVr#   checkpoint_pathc                     | j         }t          |d          5 }t          j        ||           d d d            d S # 1 swxY w Y   d S )Nwb)__dict__openpickledump)r    r   save_object
outputFiles       r!   savezResourceChangingScheduler.save  s    m/4(( 	1JKZ000	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1s   ;??c                     t          |d          5 }t          j        |          }d d d            n# 1 swxY w Y   | j                            |           d S )Nrb)r   r   loadr   update)r    r   	inputFiler   s       r!   restorez!ResourceChangingScheduler.restore!  s    /4(( 	1I +i00K	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1[)))))s   266r   c                     |ret                               d| d| d|j                    d|_        |                    |           | j                            |j                   dS dS )z'Returns True if new_resources were set.zSetting trial z resource to z with NTF)r   info_bundlesr>   update_resourcesr   r~   r   r    rt   r   s      r!   r   z-ResourceChangingScheduler.set_trial_resources&  s      		KK1 1 1] 1 1%.1 1   -1E)""=111'++EN;;;4ur#   c                     t          |t                    r?|j        |k    r4t                              | d|j        j         d|j         d           dS dS )zReturns True if trial's resources are value equal to new_resources.

        Only checks for PlacementGroupFactories at this moment.
        z PGF z and z are the same, skippingTF)r*   r   r>   r   r   r?   r   s      r!   _are_resources_the_samez1ResourceChangingScheduler._are_resources_the_same6  s|     }&;<<	->>LL + +0C+ +%8+ + +   45r#   c                 h   | j         dS t          | j         dd          s%t          | j        d| j                  | j         _        t          | j         dd          s%t          | j        d| j                  | j         _        |                      ||||           }|r|                     ||          s|S dS )zCalls user defined resources_allocation_function. If the returned
        resources are not none and not the same as currently present, returns
        them. Otherwise, returns None.Nr   r   r   r   )r   r   r   r   r   r   r   r   )r    r1   rt   r%   r   s        r!   r   z>ResourceChangingScheduler.reallocate_trial_resources_if_neededM  s     .64t:HdKK 	9@$i: :D/6 t:FDII 	7>$gtz8 8D/4 ;;UFD
 
  	!!=!=e]!S!S 	!  tr#   )"r-   r   r   r   _DistributeResourcesDefaultr	   r   r   r   r   r   r   r   r"   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   dictr   r   r   s   @r!   r   r   O  s3       G GV 48 (  0 (0$cN/	 ./1
(
 
     @ , , X, *h/D&E * * * X*PsmP+3C=P	P P P PS,< SU S S S S(U.> Uu U U U U'/'8='GK'	' ' ' '	
)	
 	
 		
 	
 	
 	
V/V8=V V V V
/	%   4Wc W W W W1C 1 1 1 1
*s * * * *
+07L1L+M	     
	   ./8=GK	%334	5       r#   r   )&loggingr   r   copyr   typingr   r   r   r   r   r	   r
   r   r   numpyro   #ray.air.execution.resources.requestr   #ray.tune.execution.placement_groupsr   ray.tune.experimentr   #ray.tune.schedulers.trial_schedulerr   r   ray.util.annotationsr   "ray.tune.execution.tune_controllerr   	getLoggerr-   r   r   r   r  &_DistributeResourcesDistributedDefaultr   rM   r#   r!   <module>r     s(            X X X X X X X X X X X X X X X X X X X X X X     < < < < < < E E E E E E % % % % % % M M M M M M M M * * * * * * BAAAAAA		8	$	$ Vy y y y y y y yx Vu
 u
 u
 u
 u
"5 u
 u
 u
p 21eDDD )<)<)N)N)N & VW W W W W W W W W Wr#   