o
    `۷iz                     @   sz   d dl Z d dlmZmZmZmZ d dlmZ d dl	Z	d dl
mZ d dlmZ G dd deZedd	G d
d deZdS )    N)DictListOptionalUnion)Callback)TensorflowCheckpoint)	PublicAPIc                       s   e Zd ZdZg dZd(deeee f f fddZde	defd	d
Z
d)ddZd)ddZd)ddZd)ddZd)ddZd)ddZd)ddZd)ddZd)ddZd)ddZd)d d!Zd)d"d#Zd)d$d%Zd)d&d'Z  ZS )*	_Callbackz%Base class for Air's Keras callbacks.)epoch_begin	epoch_endtrain_batch_begintrain_batch_endtest_batch_begintest_batch_endpredict_batch_beginpredict_batch_endtrain_begin	train_end
test_begintest_endpredict_beginpredict_endvalidation_endonc                    sP   t t   t|ts|g}t fdd|D r#td| j| _	d S )Nc                 3   s    | ]}| j vV  qd S N)_allowed).0wself P/home/ubuntu/vllm_env/lib/python3.10/site-packages/ray/air/integrations/keras.py	<genexpr>$   s    z%_Callback.__init__.<locals>.<genexpr>z4Invalid trigger time selected: {}. Must be one of {})
superr	   __init__
isinstancelistany
ValueErrorformatr   _on)r   r   	__class__r   r!   r$      s   

z_Callback.__init__logswhenc                 C   s   t r   )NotImplementedError)r   r-   r.   r    r    r!   _handle,   s   z_Callback._handleNc                 C      d| j v r| |d d S d S )Nr
   r*   r0   r   epochr-   r    r    r!   on_epoch_begin/      
z_Callback.on_epoch_beginc                 C   r1   )Nr   r2   r3   r    r    r!   on_epoch_end3   r6   z_Callback.on_epoch_endc                 C   r1   )Nr   r2   r   batchr-   r    r    r!   on_train_batch_begin7   r6   z_Callback.on_train_batch_beginc                 C   r1   )Nr   r2   r8   r    r    r!   on_train_batch_end;   r6   z_Callback.on_train_batch_endc                 C   r1   )Nr   r2   r8   r    r    r!   on_test_batch_begin?   r6   z_Callback.on_test_batch_beginc                 C   r1   )Nr   r2   r8   r    r    r!   on_test_batch_endC   r6   z_Callback.on_test_batch_endc                 C   r1   )Nr   r2   r8   r    r    r!   on_predict_batch_beginG   r6   z _Callback.on_predict_batch_beginc                 C   r1   )Nr   r2   r8   r    r    r!   on_predict_batch_endK   r6   z_Callback.on_predict_batch_endc                 C      d| j v r| |d d S d S )Nr   r2   r   r-   r    r    r!   on_train_beginO   r6   z_Callback.on_train_beginc                 C   r@   )Nr   r2   rA   r    r    r!   on_train_endS   r6   z_Callback.on_train_endc                 C   r@   )Nr   r2   rA   r    r    r!   on_test_beginW   r6   z_Callback.on_test_beginc                 C   r@   )Nr   r2   rA   r    r    r!   on_test_end[   r6   z_Callback.on_test_endc                 C   r@   )Nr   r2   rA   r    r    r!   on_predict_begin_   r6   z_Callback.on_predict_beginc                 C   r@   )Nr   r2   rA   r    r    r!   on_predict_endc   r6   z_Callback.on_predict_end)r   r   )__name__
__module____qualname____doc__r   r   strr   r$   r   r0   r5   r7   r:   r;   r<   r=   r>   r?   rB   rC   rD   rE   rF   rG   __classcell__r    r    r+   r!   r	      s&     












r	   alpha)	stabilityc                       s   e Zd ZdZ			ddeeee f deeee f deeeee eeef f  f fddZ	d	ed
efddZ
d	edefddZ  ZS )ReportCheckpointCallbacka  Keras callback for Ray Train reporting and checkpointing.

    .. note::
        Metrics are always reported with checkpoints, even if the event isn't specified
        in ``report_metrics_on``.

    Example:
        .. code-block:: python

            ############# Using it in TrainSession ###############
            from ray.air.integrations.keras import ReportCheckpointCallback
            def train_loop_per_worker():
                strategy = tf.distribute.MultiWorkerMirroredStrategy()
                with strategy.scope():
                    model = build_model()

                model.fit(dataset_shard, callbacks=[ReportCheckpointCallback()])

    Args:
        metrics: Metrics to report. If this is a list, each item describes
            the metric key reported to Keras, and it's reported under the
            same name. If this is a dict, each key is the name reported
            and the respective value is the metric key reported to Keras.
            If this is None, all Keras logs are reported.
        report_metrics_on: When to report metrics. Must be one of
            the Keras event hooks (less the ``on_``), e.g.
            "train_start" or "predict_end". Defaults to "epoch_end".
        checkpoint_on: When to save checkpoints. Must be one of the Keras event hooks
            (less the ``on_``), e.g. "train_start" or "predict_end". Defaults to
            "epoch_end".
    r   Ncheckpoint_onreport_metrics_onmetricsc                    sT   t |tr|g}t |tr|g}tt|| }t j|d || _|| _|| _d S )N)r   )	r%   rL   r&   setr#   r$   _checkpoint_on_report_metrics_on_metrics)r   rQ   rR   rS   r   r+   r    r!   r$      s   


z!ReportCheckpointCallback.__init__r-   r.   c                 C   st   || j v s|| jv sJ | |}|| j v }|r0t| j}tjj||d t	j
|jdd d S tjj|d d d S )N)
checkpointT)ignore_errors)rU   rV   _get_reported_metricsr   
from_modelmodelraytrainreportshutilrmtreepath)r   r-   r.   rS   should_checkpointrX   r    r    r!   r0      s   

z ReportCheckpointCallback._handlereturnc                    s   t | jtd tttfsJ | jd u r }n2t | jtr%| j | j i}n#t | jtr6 fdd| jD }nt | jtrH fdd| j D }t |tsOJ |S )Nc                    s   i | ]}| | qS r    r    )r   metricr-   r    r!   
<dictcomp>   s    zBReportCheckpointCallback._get_reported_metrics.<locals>.<dictcomp>c                    s   i | ]	\}}| | qS r    r    )r   keyre   rf   r    r!   rg      s    )r%   rW   typerL   r&   dictitems)r   r-   reported_metricsr    rf   r!   rZ      s   

z.ReportCheckpointCallback._get_reported_metrics)r   r   N)rH   rI   rJ   rK   r   rL   r   r   r   r$   r0   rZ   rM   r    r    r+   r!   rP   h   s    "rP   )r`   typingr   r   r   r   tensorflow.keras.callbacksr   KerasCallbackr]   ray.train.tensorflowr   ray.util.annotationsr   r	   rP   r    r    r    r!   <module>   s    ]