U
    da}                     @   s   d dl Z d dlZd dlmZmZ d dlmZ d dlmZm	Z	m
Z
mZmZmZ eeZG dd dejZdd Zdd	d
ZG dd deZG dd deZG dd deZG dd deZdd ZdS )    N)corecontext)ops)final_outputNodeTask	TaskGroup
TaskOutputWorkspaceTypec                       sN   e Zd ZdZdddZdd Zdd Z fd	d
Z fddZdd Z	  Z
S )Jobad  
    A Job defines three TaskGroups: the `init_group`, the `epoch_group` and the
    `exit_group` which will be run by a JobRunner.

    The `init_group` will be run only once at startup. Its role is to
    initialize globally persistent blobs such as model weights, accumulators
    and data file lists.

    The `epoch_group` will be run in a loop after init_group. The loop will
    exit when any of the stop signals added with `add_stop_condition` is True
    at the end of an epoch.

    The download_group will be run only once, after all the executions of
    epoch_group finish. Its role is to collect the distribute scattered
    parameters back after training.

    The `exit_group` will be run only once at the very end of the job, the
    role of this group is to save the results of training in the end of the job.

    Jobs are context-driven, so that Tasks can be added to the active Job
    without having to explicitly pass the job object around.

    Example of usage:

    def build_reader(partitions):
        with Job.current().init_group:
            reader = HiveReader(init_reader, ..., partitions)
            Task(step=init_reader)
        with Job.current().epoch_group:
            limited_reader = ReaderWithLimit(reader, num_iter=10000)
            data_queue = pipe(limited_reader, num_threads=8)
            Job.current().add_stop_condition(limited_reader.data_finished())
        return data_queue

    def build_hogwild_trainer(reader, model):
        with Job.current().init_group:
            Task(step=model.param_init_net)
        with Job.current().epoch_group:
            pipe(reader, processor=model, num_threads=8)
        with Job.current().exit_group:
            Task(step=model.save_model_net)

    with Job() as job:
        reader = build_reader(partitions)
        model = build_model(params)
        build_hogwild_trainer(reader, model)
    Nc                 C   sJ   |pt tjd| _|pt  | _|p&t  | _|p2t  | _|p<g | _|| _d S )N)Zworkspace_type)	r   r
   GLOBAL
init_groupepoch_groupdownload_group
exit_groupstop_conditions_nodes_to_checkpoint)selfr   r   r   r   r   nodes_to_checkpoint r   </tmp/pip-unpacked-wheel-ua33x9lu/caffe2/python/checkpoint.py__init__I   s    
zJob.__init__c                 C   s   | j r| j S | j S d S N)r   r   Z
used_nodesr   r   r   r   r   U   s    zJob.nodes_to_checkpointc                 C   sF   |   | _|| j| _|| j| _|| j| _|| j| _d S r   )r   r   compiler   r   r   r   )r   Zsession_classr   r   r   r   [   s
    
zJob.compilec                    s   t t|   | j  | S r   )superr   	__enter__r   r   	__class__r   r   r   b   s    
zJob.__enter__c                    s   | j   tt| j|  d S r   )r   __exit__r   r   )r   argsr   r   r   r   g   s    
zJob.__exit__c                 C   sF   t |tjr(t|g| jd}| d }t |ts6t| j	| d S )N)outputsgroupr   )

isinstancer   ZBlobReferencer   r   r!   r	   AssertionErrorr   append)r   outputtr   r   r   add_stop_conditionk   s
    zJob.add_stop_condition)NNNNNN)__name__
__module____qualname____doc__r   r   r   r   r   r(   __classcell__r   r   r   r   r      s   0         
r   c                 C   s   | d t | S )zReturns the checkpoint filename.

    Args:
        node_name: A string. The name of the node.
        epoch: An integer. The checkpoint epoch.

    Returns:
        ckpt_filename: A string. The filename of the checkpoint.
    .str)	node_nameepochr   r   r   get_ckpt_filenames   s    
r3   c                 C   s0   |r|t ||  }nt || }tj||}|S )a  Returns the full db name where checkpoint files are saved.

    Args:
        epoch: An integer. The checkpoint epoch.
        node_name: A string. The name of the node.
        db_prefix: A string. The prefix used to construct full db name.
        path_prefix: A string. Optional param used to construct db name or path
            where checkpoint files are stored.
    Returns:
        db_name: A string. The absolute path of full_db_name where checkpoint
            files are saved
    )r3   ospathjoin)r2   r1   	db_prefixpath_prefixdb_nameZckpt_filenamer   r   r   r9      s
    
r9   c                   @   s   e Zd ZdZdZd ddZd!ddZdd	 Zd
d Zdd Z	d"ddZ
dd Zdd Zdd Zdd Zdd Zd#ddZd$ddZd%ddZdS )&CheckpointManagera  
    Controls saving and loading of workspaces on every epoch boundary of a job.
    If a CheckpointManager instance is passed to JobRunner, then JobRunner will
    call `init`, `read` and `save` at different moments in between epoch runs.

    Args:
        db_prefix: The prefix used to construct full db name. Since `absolute_path`
            is set to True, this will be used as db_name in SaveOp.
        node_name: Name of the node where this checkpoint_manager is used.
        db_type: Type of database to use for storing checkpoint.
        metadata_handler: An optional object capable of reading/writing
            checkpoint info in storage of choice.
    
blob_namesNc                 C   sV   || _ || _|| _|| _td| _| j| j| _	d | _
d | _d | _d | _d | _d S )Nz!!checkpoint_mngr)
_db_prefix
_node_name_db_type_metadata_handlerr   NetZ_netZAddExternalInput
BLOB_NAMES_blob_names_names_output_path_prefix
_path_type_current_db_name_current_checkpoint_duration)r   r7   r1   db_typemetadata_handlerr   r   r   r      s    zCheckpointManager.__init__c              	   C   s   |dkst |dkstdt| jgdd}|dkrHtjg | jdd nBt|| j| j|}|pb| j	}t
d|  tjg | j||ddd	 W 5 Q R X | d
 | _|S )a!  
        Build a Task that will be run once after the job's `init_group` is run.
        This task will determine which blobs need to be checkpointed.
        If retrieve_from_epoch is not None, then the checkpoint metadata is
        retrieved from a previously saved checkpoint.
        N   z,CheckpointManager only supports single node.)r!   F)Zinclude_sharedz"Initializing checkpoints from = %sTdbrH   absolute_pathZkeep_devicer   )lenr$   r   rB   r   ZGetAllBlobNamesr9   r=   r<   r>   loggerinfoLoadr!   rC   )r   nodesretrieve_from_epochr8   	path_typetaskZfull_db_namerH   r   r   r   init   s:      
 zCheckpointManager.initc                 C   s   | j s
t| j   S r   )rC   r$   fetchtolistr   r   r   r   	blob_list   s    
zCheckpointManager.blob_listc              
   C   sl   t |dX}t  tjg | jd}W 5 Q R X |  t  t|}W 5 Q R X t|| _W 5 Q R X |S )an  
        Build a Task that will measure the time span of checkpoint operations,
        once operation is done, time can be read from _current_checkpoint_duration.

        Args:
            cp_op_name: A string name of the checkpoint operation.
            add_op: A functor to add the checkpoint operation.

        Returns:
            A task with timer.
        )name)Zcounter_name)	r   r   Z	task_initZ
TimerBeginr=   Z	task_exitZTimerGetAndEndr   rG   )r   Z
cp_op_nameadd_oprU   ZtimerZtime_span_blobr   r   r   _timed_task   s    

zCheckpointManager._timed_taskc                 C   s8   | j r"| jr"| j d || j < ntd| j  dS )z
        Add one checkpoint stats into the stats.

        Args:
            stats: A dict of checkpoint stats that will be reported.
        r   z&Failed to collect checkpoint stats: {}N)rF   rG   rW   rO   rP   format)r   statsr   r   r   collect_checkpoint_stats   s    z*CheckpointManager.collect_checkpoint_statsc                    sH   t |jj|_|pj tdj   fdd}d|S )z
        Build a Task that will be run by JobRunner when the job is to be
        resumed from a given epoch. This task will run a Load op that will
        load and deserialize all relevant blobs from a persistent storage.
        zLoading checkpoints from = %sc                      s    t jg  j ddd d S )NTrK   )r   rQ   rY   rF   r   rH   r   r   r   r[     s    z&CheckpointManager.load.<locals>.add_opcheckpoint_load)r9   r=   r<   rF   r>   rO   rP   r\   )r   r2   r8   rT   r[   r   r`   r   load  s       

zCheckpointManager.loadc                    s<   t |jj_tdj   fdd}d|S )a  
        Builds a Task that loads only the necessary blobs from a checkpoint of
        the given epoch. The necessary blobs are given in the blob_names
        argument.

        Args:
            blob_names: A list of strings. Each string is the name of a
                blob.
            epoch: The checkpoint epoch to load from.

        Returns:
            A Task which loads the specified blobs from the checkpoint of the
            given epoch.
        zLoad from %sc                      s   t jg  jjddd d S )NT)rL   rH   rM   Zallow_incomplete)r   rQ   rF   r>   r   r;   r   r   r   r[   9  s    z<CheckpointManager.load_blobs_from_checkpoint.<locals>.add_opcheckpoint_partial_loadr9   r=   r<   rF   rO   rP   r\   )r   r;   r2   r[   r   rc   r   load_blobs_from_checkpoint'  s    	z,CheckpointManager.load_blobs_from_checkpointc              	   C   sh   t dt|| j| j  t >}td}tjg |gt|| j| j| j	dd |
| W 5 Q R X |S )NzCheck existence of %sFT)r9   rH   rM   )rO   rP   r9   r=   r<   r   r   ZConstZDBExistsr>   Z
add_output)r   r2   rU   	existencer   r   r   check_db_existsD  s    
z!CheckpointManager.check_db_existsc                 C   s&   i }|  | | jr"| j|| dS )z
        Report checkpoint operation stats for current node.

        Args:
            action_name: A string of the name of checkpoint operation.
        N)r_   r?   report)r   action_name	all_statsr   r   r   report_checkpoint_statsR  s    
z)CheckpointManager.report_checkpoint_statsc                    s:   t | j j _td j   fdd} d|S )z
        Build a Task that is run once after `init_group` and after each
        epoch is run. This will execute a Save ops to serialize and persist
        blobs present in the global workspace.
        zSaving to %sc                      s    t j  g  j jdd d S )NT)rL   rH   rM   )r   ZSaverY   rF   r>   r   r   r   r   r[   g  s     z&CheckpointManager.save.<locals>.add_opcheckpoint_savere   )r   r2   r[   r   r   r   save^  s    zCheckpointManager.savec                 C   s   | j dk	r| j j|d dS z
        Write metadata for checkpoint

        Args:
            epoch: An integer. The epoch-id for which checkpoint metadata is
                written
        Nr2   r?   writer   r2   r   r   r   write_checkpoint_metadatap  s    
z+CheckpointManager.write_checkpoint_metadatac                 C   s    |}| j dk	r| j j|d}|S a^  
        Identify the epoch-id from which Job must resume

        Args:
            user_epoch: An integer. Optional parameter for user to explicitly
                identify the epoch-id to load checkpoint from
        Returns:
            epoch: the epoch-id to load checkpoints from
                or None if no checkpoints were written
        N)
user_epochr?   
last_epochr   rv   rx   r   r   r   get_resume_from_epoch_id{  s    
z*CheckpointManager.get_resume_from_epoch_idc                 C   sD   |r
|| _ |r|| _| jr@| jj| j| jt| jg| j | jd dS )R  Set parameters associated with CP manager

        Args:
            nodes: An array of nodes where this checkpoint manager is running.
            path_prefix: Used to construct db name or path where checkpoint files are
                stored.
            path_type: Indicate the type of path where checkpoint files are stored.
        r7   rH   Z
node_namesr8   rT   N)rD   rE   r?   
set_paramsr<   r>   r0   r=   r   rR   r8   rT   r   r   r   r}     s    	
zCheckpointManager.set_paramsc                 C   s   | j dk	r| j |S dS dS aE  Returns True if Checkpoint data is accessible

        Args:
            epoch: An integer. The epoch of the checkpoint. If None,
                it implies we need to check if checkpoint directory is accessible

        Returns:
            is_cp_accessible: A boolean. Returns True if Checkpoint data is accessible
        NTr?   cp_accessiblers   r   r   r   r     s    

zCheckpointManager.cp_accessible)N)NNNN)NN)N)NN)N)r)   r*   r+   r,   rA   r   rV   rY   r\   r_   rb   rf   rh   rl   rn   rt   rz   r}   r   r   r   r   r   r:      s(   
    
&


r:   c                   @   s|   e Zd ZdZdddZdd ZdddZdd	d
Zdd Zdd Z	dd Z
dd Zdd ZdddZdddZd ddZdS )!MultiNodeCheckpointManagera?  
    Coordinates checkpointing and checkpointing across multiple nodes.
    Each of `init`, `load` and `save` will build TaskGroups which will
    trigger checkpointing on each of the nodes involved in a distributed job.

    Args:
        db_prefix: The prefix used to construct full db name. Since `absolute_path`
            is set to True, this will be used as db_name in SaveOp.
        db_type: Type of database to use for storing checkpoint.
        metadata_handler: An optional object capable of reading/writing
            checkpoint info in storage of choice.
    Nc                 C   s(   d | _ || _|| _|| _d | _d | _d S r   )_node_managersr<   r>   r?   rD   rE   )r   r7   rH   rI   r   r   r   r     s    z#MultiNodeCheckpointManager.__init__c                 O   sl   | j d k	stdttjF}| j D ],\}}t| ||f|| W 5 Q R X q$|W  5 Q R  S Q R X d S )Nzinit must be called first.)r   r$   r   r
   r   r   )r   funcr    kwZ
task_groupnodemanagerr   r   r   _task_group  s    
z&MultiNodeCheckpointManager._task_groupc              
   C   s   | j d k	r,dd | j D |ks"tttjS g | _ |D ]>}t|, t| jt|| j	d}| j 
||f W 5 Q R X q6| jtj|g|||dS )Nc                 S   s   g | ]\}}|qS r   r   .0r   _r   r   r   
<listcomp>  s     z3MultiNodeCheckpointManager.init.<locals>.<listcomp>r7   r1   rH   )rR   rS   r8   rT   )r   r$   r   r
   r   r   r:   r<   r0   r>   r%   r   rV   )r   rR   rS   r8   rT   r   r   r   r   r   rV     s&    


zMultiNodeCheckpointManager.initc                 C   s   | j tj|||dS )N)r8   rT   )r   r:   rb   )r   r2   r8   rT   r   r   r   rb     s    zMultiNodeCheckpointManager.loadc              
   C   s   | j dk	r$dd | j D |ksntnJg | _ |D ]>}t|, t| jt|| jd}| j ||f W 5 Q R X q.| j dk	std| j D ]f\}}||}|	| |
 d  }	|	stdt||j|j   dS |||}
|	|
 qtd	 d
S )a:  Loads the necessary blobs from the checkpoints to the current node.

        Args:
            blob_names: A list of strings. Each string is the name of a
                blob.
            epoch: An integer. The checkpoint epoch to load from.
            session: A Session object to execute the Load ops.
        Nc                 S   s   g | ]\}}|qS r   r   r   r   r   r   r     s     zAMultiNodeCheckpointManager.load_blobs_locally.<locals>.<listcomp>r   zmust initialize node managersr   zDB %s does not exist!Fz%Successfully loaded from checkpoints.T)r   r$   r   r:   r<   r0   r>   r%   rh   runr!   rW   rO   rP   r9   r=   rf   )r   rR   r;   r2   sessionr   r   r   Zexistence_taskrg   Z	load_taskr   r   r   load_blobs_locally  s2    	




z-MultiNodeCheckpointManager.load_blobs_locallyc                 C   s4   | j D ](\}}t||krt||j|j  S qdS )a  Returns the DB name of the given node and the given epoch.

        The DB name is effectively the checkpoint path of the given node and
        the given epoch.

        Args:
            node_name: A string. The node name of interest.
            epoch: An integer. The epoch of the checkpoint.

        Returns:
            checkpoint_db_name: A string. The checkpoint path of the given
                node and the given epoch.
        N)r   r0   r9   r=   r<   )r   r1   r2   r   r   r   r   r   get_ckpt_db_name  s    z+MultiNodeCheckpointManager.get_ckpt_db_namec                 C   sF   i }| j D ]\}}|| q
td| | jrB| j|| dS )a  
        Report the checkpoint stats for all the nodes, we need to aggregate all
        the node's stats together so that we know which node's checkpoint
        operation dominates.

        Args:
            action_name: A string of the name of checkpoint operation.
        zcheckpoint stats: {}N)r   r_   rO   debugr]   r?   ri   )r   rj   rk   r   r   r   r   r   rl   %  s    	z2MultiNodeCheckpointManager.report_checkpoint_statsc                 C   s   |  tj|S )z
        Build a Task that will execute a Save ops to serialize and persist
        blobs present in the global workspace.
        )r   r:   rn   rs   r   r   r   rn   5  s    zMultiNodeCheckpointManager.savec                 C   s   | j dk	r| j j|d dS ro   rq   rs   r   r   r   rt   <  s    
z4MultiNodeCheckpointManager.write_checkpoint_metadatac                 C   s    |}| j dk	r| j j|d}|S ru   rw   ry   r   r   r   rz   G  s    
z3MultiNodeCheckpointManager.get_resume_from_epoch_idc                 C   sN   dd |D | _ |r|| _|r$|| _| jrJ| jj| j| j| j | j| jd dS )r{   c                 S   s   g | ]}t |qS r   r/   )r   r   r   r   r   r   `  s     z9MultiNodeCheckpointManager.set_params.<locals>.<listcomp>r|   N)Z_node_namesrD   rE   r?   r}   r<   r>   r~   r   r   r   r}   W  s    	z%MultiNodeCheckpointManager.set_paramsc                 C   s   | j dk	r| j |S dS dS r   r   rs   r   r   r   r   m  s    

z(MultiNodeCheckpointManager.cp_accessible)N)NNN)NN)N)NN)N)r)   r*   r+   r,   r   r   rV   rb   r   r   rl   rn   rt   rz   r}   r   r   r   r   r   r     s    
     

"

r   c                   @   s   e Zd ZdZdd ZdS )UploadTaskGroupBuilderz%A simple class to upload checkpoints.c                 C   s
   t  dS )a  Builds the task group to upload checkpoints.

        Args:
            epoch: An integer. The checkpoint epoch to be uploaded.
            checkpoint_manager: Can be a CheckpointManager for single machine
                or a MultiNodeCheckpointManager for multi-machine. The manager
                that initializes/saves/loads checkpoints.

        Raises:
            NotImplementedError: This base class only has the interface,
                the implementation will be in the subclasses.
        N)NotImplementedError)r   r2   checkpoint_managerr   r   r   build  s    zUploadTaskGroupBuilder.buildN)r)   r*   r+   r,   r   r   r   r   r   r   }  s   r   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )	JobRunnera  
    Implement the runtime logic for jobs with checkpointing at the level of
    epoch. Can be used to run either single-host or distributed jobs. Job
    runner is a callable to be called once from the master, passing a session
    as an argument. This call will block until the Job execution is complete.

    If a checkpoint_manager is passed, checkpoints will be taken after
    initialization and after each epoch execution. If, in addition,
    `resume_from_epoch` is an epoch number, the corresponding checkpoint will
    be loaded and job execution will continue from the given epoch. In
    this case, the job's init_group will not be run.

    Refer to checkpoint_test.py for an example.
    Nc                 C   s   || _ || _|| _|| _dS )a"  Initializes the JobRunner.

        Args:
            job: A Job object. The job to be executed.
            checkpoint_manager: Can be a CheckpointManager for single machine
                or a MultiNodeCheckpointManager for multi-machine. The manager
                that initializes/saves/loads checkpoints.
            resume_from_epoch: An integer. The epoch to resume from.
            upload_task_group_builder: A subclass of the
                UploadTaskGroupBuilder. Creates a task group to upload
                checkpoints.
        N)resume_from_epochr   jobupload_task_group_builder)r   r   r   r   r   r   r   r   r     s    zJobRunner.__init__c                 C   s  | j rF| j j| j d | j | j| _| jdk	rFtd| j | jdk}|rb|	| jj
 | j rtd |	| j j| j | jd |r| d| n<td| j |	| j | j | j d td	 td
 |rdn| jd }td|  |	| jj td|  dd | jjD }| j rJ| || t|rbtd ql|d7 }qtd | jr| j|| j }|	| td |	| jj td |	| jj td |S )zRuns the training flow.

        Args:
            session: A Session object. Valid choises are: LocalSession,
                LocalHostScheduler, and DistributedSession. It is used to
                execute one TaskGroup a time.
        )rR   NzResuming from epoch {}zPreparing checkpoints ...)rS   r   z$Loading checkpoints for epoch {} ...ra   zCheckpoint loadedzFinished initializingrJ   zStarting epoch %dzFinished epoch %dc                 S   s   g | ]}|  qS r   )rW   )r   or   r   r   r     s     z#JobRunner.train.<locals>.<listcomp>ZStoppingzFinished trainingz"Finished uploading the checkpointsz#Finished downloading the parameterszFinished running the exit group)r   r}   r   r   rz   r   rO   rP   r]   r   r   rV   save_checkpointsrb   rl   r   r   anyr   r   r   r   )r   r   Zfrom_scratchr2   r   Zupload_task_groupr   r   r   train  sf    	









 



zJobRunner.trainc                 C   sF   | j stdtd| | j | j |||}| j d |S )aP  Loads the necessary blobs from the checkpoints.

        Checkpoints store the snapshots of the workspace in each node.
        Sometimes we only need to load a subset of the blobs from the
        checkpoints. One common scenario is to load only the model blobs from
        the checkpoints for evaluation purpose. Given the names of the
        necessary blobs, this function goes over all the checkpoints of all the
        nodes, but only loads the blobs specified in the blob_names to the
        current workspace.

        Args:
            blob_names: A list of strings. Each string is the name of a
                blob.
            epoch: An integer. The checkpoint epoch to load from.
            session: A Session object to execute the load ops.

        Raises:
            ValueError: When the checkpoint manager is invalid.
        Checkpoint manager is Nonez#Loading checkpoint for epoch {} ...rd   )	r   
ValueErrorrO   rP   r]   r   r   r   rl   )r   r;   r2   r   resultr   r   r   load_blobs_from_checkpoints  s       z%JobRunner.load_blobs_from_checkpointsc              
   C   s   | j stdzf| j jdd}|rhtd| || j | | j | td | j 	d n
t
d W n4 tk
r } zt
d|| W 5 d}~X Y nX dS )	a  Triggers operation to save checkpoints

        This method will trigger the Save ops to serialize and persist the
        blobs present in the global workspaace.

        Args:
            epoch: An integer. The checkpoint epoch-id that we are saving.
            session: A Session object to execute the save ops.

        Raises:
            ValueError: When the checkpoint manager is invalid.
        r   Nrp   zSaving checkpoints for epoch {}zCheckpoints savedrm   z$Checkpoint files cannot be accessed!z1Unable to write checkpoint for epoch {}. Error={})r   r   r   rO   rP   r]   r   rn   rt   rl   warning	Exception)r   r2   r   Zis_accessibleexr   r   r   r     s     
 zJobRunner.save_checkpoints)NNN)r)   r*   r+   r,   r   r   r   r   r   r   r   r   r     s     
Hr   c              	   C   s   | j , td}|jg |d d}t|d W 5 Q R X | j. td}||}t||d d }W 5 Q R X | | dS )	z^
    Creates a task that will output True when a given
    number of epochs has finished.
    Zepoch_counter_initrJ   )Z
init_count)stepZepoch_countdown)r   r!   r   N)	r   r   r@   ZCreateCounterr   r   Z	CountDownr!   r(   )r   Z
num_epochsZinit_netcounterZ	epoch_netfinishedr&   r   r   r   epoch_limiter3  s    


r   )N)r4   loggingZcaffe2.pythonr   r   Zcaffe2.python.net_builderr   Zcaffe2.python.taskr   r   r   r   r	   r
   	getLoggerr)   rO   ZManagedr   r3   r9   objectr:   r   r   r   r   r   r   r   r   <module>   s"    	
Z
   N %