o
    $i                     @   s   d dl Z d dlm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G d	d
 d
eZeddG dd deZdS )    N)abstractmethod)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 Ray Train'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 W/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/ray/train/tensorflow/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      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+   r3   r    epochr.   r!   r!   r"   on_epoch_begin0      
z_Callback.on_epoch_beginc                 C   r4   )Nr   r5   r6   r!   r!   r"   on_epoch_end4   r9   z_Callback.on_epoch_endc                 C   r4   )Nr   r5   r    batchr.   r!   r!   r"   on_train_batch_begin8   r9   z_Callback.on_train_batch_beginc                 C   r4   )Nr   r5   r;   r!   r!   r"   on_train_batch_end<   r9   z_Callback.on_train_batch_endc                 C   r4   )Nr   r5   r;   r!   r!   r"   on_test_batch_begin@   r9   z_Callback.on_test_batch_beginc                 C   r4   )Nr   r5   r;   r!   r!   r"   on_test_batch_endD   r9   z_Callback.on_test_batch_endc                 C   r4   )Nr   r5   r;   r!   r!   r"   on_predict_batch_beginH   r9   z _Callback.on_predict_batch_beginc                 C   r4   )Nr   r5   r;   r!   r!   r"   on_predict_batch_endL   r9   z_Callback.on_predict_batch_endc                 C      d| j v r| |d d S d S )Nr   r5   r    r.   r!   r!   r"   on_train_beginP   r9   z_Callback.on_train_beginc                 C   rC   )Nr   r5   rD   r!   r!   r"   on_train_endT   r9   z_Callback.on_train_endc                 C   rC   )Nr   r5   rD   r!   r!   r"   on_test_beginX   r9   z_Callback.on_test_beginc                 C   rC   )Nr   r5   rD   r!   r!   r"   on_test_end\   r9   z_Callback.on_test_endc                 C   rC   )Nr   r5   rD   r!   r!   r"   on_predict_begin`   r9   z_Callback.on_predict_beginc                 C   rC   )Nr   r5   rD   r!   r!   r"   on_predict_endd   r9   z_Callback.on_predict_end)r   r   )__name__
__module____qualname____doc__r   r   strr   r%   r   r3   r8   r:   r=   r>   r?   r@   rA   rB   rE   rF   rG   rH   rI   rJ   __classcell__r!   r!   r,   r"   r
      s&     












r
   c                       s   e 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	e
dedefddZe
defddZdedefddZ  ZS )RayReportCallbackr   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&   rO   r'   setr$   r%   _checkpoint_on_report_metrics_on_metrics)r    rR   rS   rT   r   r,   r!   r"   r%   j   s   


zRayReportCallback.__init__r.   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    z;RayReportCallback._get_reported_metrics.<locals>.<dictcomp>c                    s   i | ]	\}}| | qS r!   r!   )r   keyrZ   r[   r!   r"   r\      s    )r&   rX   typerO   r'   dictitems)r    r.   reported_metricsr!   r[   r"   _get_reported_metrics|   s   

z'RayReportCallback._get_reported_metrics
checkpointc                 C   r0   )CSave checkpoint and report metrics corresonding to this checkpoint.r1   r    rT   rc   r!   r!   r"   _save_and_report_checkpoint   s   z-RayReportCallback._save_and_report_checkpointc                 C   r0   )Report metrics.r1   r    rT   r!   r!   r"   _report_metrics   s   z!RayReportCallback._report_metricsr/   c                 C   sj   || j v s|| jv sJ | |}|| j v }|r.t| j}| || tj|j	dd d S | 
| d S )NT)ignore_errors)rV   rW   rb   r   
from_modelmodelrf   shutilrmtreepathri   )r    r.   r/   rT   should_checkpointrc   r!   r!   r"   r3      s   

zRayReportCallback._handle)r   r   N)rK   rL   rM   r   rO   r   r   r   r%   rb   r   r   rf   ri   r3   rP   r!   r!   r,   r"   rQ   i   s*    rQ   alpha)	stabilityc                   @   s0   e Zd ZdZdedefddZdefddZd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:
        .. testcode:: 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".
    rT   rc   c                 C   s   t jj||d dS )rd   rc   Nraytrainreportre   r!   r!   r"   rf      s   z4ReportCheckpointCallback._save_and_report_checkpointc                 C   s   t jj|dd dS )rg   Nrt   ru   rh   r!   r!   r"   ri      s   z(ReportCheckpointCallback._report_metricsN)rK   rL   rM   rN   r   r   rf   ri   r!   r!   r!   r"   rs      s     
rs   )rm   abcr   typingr   r   r   r   tensorflow.keras.callbacksr   KerasCallbackrv   ray.train.tensorflowr   ray.util.annotationsr	   r
   rQ   rs   r!   r!   r!   r"   <module>   s    ]?