a
    –¥»aƒC  ã                   @   sÜ   d dl mZmZ d dlmZmZ d dlmZmZ d dl	m
Z
mZ d dlmZmZmZ G dd„ deƒZdZd	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d„ZG dd„ deƒZG dd „ d eƒZdS )%é    )ÚcoreÚ
queue_util)ÚReaderÚWriter)Ú
NetBuilderÚops)Ú	as_recordÚField)ÚNodeÚTaskÚ	TaskGroupc                   @   s   e Zd ZdZddd„ZdS )ÚOutputz¿
    Represents the result of a processor function. A processor can either
    return an Output, or it can return a record, in which case an Output will be
    created for it afterwards.
    Nc                 C   s|   t  ¡  ¡ }|d u s(t|ƒdks(J dƒ‚|d u r4|}t|tjƒrF|g}|d u rRg nt|ƒ| _|d u rhd nt	|ƒ| _
|| _d S )Nr   z7Cannot both use `ops` syntax and return a list of nets.)r   ÚcurrentÚgetÚlenÚ
isinstancer   ÚNetÚlistÚnetsr   ÚrecordÚshould_stop)Úselfr   r   r   Zbuilder_children© r   úP/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/caffe2/python/pipeline.pyÚ__init__   s    ÿzOutput.__init__)NNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r      s   r   éd   c                 C   s’   | d u r*t j|d ur|ntd�}| ¡ }nTt| tƒrN|d u sDJ dƒ‚d }| }n0t| dƒrv|d u shJ dƒ‚| }|  ¡ }ntdƒ‚| ||¡ ||fS )N)Úcapacityzcapacity would not be used.Úwriterz)output must be a reader, queue or stream.)	r   ÚQueueÚDEFAULT_QUEUE_CAPACITYr!   r   r   ÚhasattrÚ
ValueErrorÚsetup_ex)Úoutputr    Úglobal_init_netÚglobal_exit_netÚ	out_queuer!   r   r   r   Ú_init_output%   s"    ý



r+   Nc                    sR   ˆ d u rdd„ S t ˆ tjƒr$tˆ ƒS ˆd urJtˆ dƒrJ‡ ‡fdd„}|ˆ _ˆ S d S )Nc                 S   s   | S ©Nr   )Úrecr   r   r   Ú<lambda><   ó    z make_processor.<locals>.<lambda>Úschema_funcc                      s
   ˆ   ˆ¡S r,   )r0   r   ©Ú	processorÚreaderr   r   Úprocessor_schemaA   s    z(make_processor.<locals>.processor_schema)r   r   r   ÚNetProcessorr$   Úschema)r2   r3   r4   r   r1   r   Úmake_processor:   s    r7   c                 C   s€   t | tƒr| S t | tƒr"t| d�S t | tƒrtt| ƒdkoTt | d tƒoTt | d tjƒ}|rjtdg| ¢R Ž S t| Ž S nt| ƒS dS )z‰
    Allow for processors to return results in several formats.
    TODO(azzolini): simplify once all processors use NetBuilder API.
    )r   é   r   é   N)r   r   r	   Útupler   r   ÚBlobReference)r'   Zis_record_and_blobr   r   r   Únormalize_processor_outputH   s    



ÿý
r<   r9   c           
   	   C   s   t | |||||||ƒ\}}	|S )a]
  
    Given a Reader, Queue or DataStream in `input`, and optionally, a Writer,
    Queue or DataStream in `output`, creates a Task that, when run, will
    pipe the input into the output, using multiple parallel threads.
    Additionally, if a processor is given, it will be called between reading
    and writing steps, allowing it to transform the record.

    Args:
        input:       either a Reader, Queue or DataStream that will be read
                     until a stop is signaled either by the reader or the
                     writer.
        output:      either a Writer, a Queue or a DataStream that will be
                     written to as long as neither reader nor writer signal
                     a stop condition. If output is not provided or is None,
                     a Queue is created with given `capacity` and written to.
        num_threads: number of concurrent threads used for processing and
                     piping. If set to 0, no Task is created, and a
                     reader is returned instead -- the reader returned will
                     read from the reader passed in and process it.
                     ** DEPRECATED **. Use `num_runtime_threads` instead.
                     This option will be removed once all readers/processors
                     support `num_runtime_threads`.
        processor:   (optional) function that takes an input record and
                     optionally returns a record; this will be called
                     between read and write steps. If the processor does
                     not return a record, a writer will not be instantiated.
                     Processor can also be a core.Net with input and output
                     records properly set. In that case, a NetProcessor is
                     instantiated, cloning the net for each of the threads.
        name:        (optional) name of the task to be created.
        capacity:    when output is not passed, a queue of given `capacity`
                     is created and written to.
        group:       (optional) explicitly add the created Task to this
                     TaskGroup, instead of using the currently active one.
        num_runtime_threads: Similar to `num_threads`, but instead of expanding
                     the tasks with a `for` loop in python, does that at
                     runtime. This is preferable to `num_threads`, but some
                     processors/readers still require to be called multiple
                     times in python.

    Returns:
        Output Queue, DataStream, Reader, or None, depending on the parameters
        passed.
    )Ú
_pipe_step)
Úinputr'   Únum_threadsr2   Únamer    ÚgroupÚnum_runtime_threadsÚresultÚ_r   r   r   Úpipec   s
    /þrE   c	              
   C   s\   |dksJ ‚t | ||||||||ƒ	\}	}
d}|durT|
 ¡ }t|ƒttfvrT|d }|	|fS )aq  
    Similar to `pipe`, with the additional ability for the pipe Task to
    return output values to the `Session` once done.

    Returns:
        Tuple (out_queue, *task_outputs)
            out_queue:    same as return value of `pipe`.
            task_outputs: TaskOutput object, fetchable from the client after
                          session.run() returns.
    r   N)r=   ÚoutputsÚtyper   r:   )r>   r'   r?   r2   r@   r    rA   rB   Úfinal_outputsrC   Útaskr   r   r   Úpipe_and_output˜   s    þrJ   c                 C   sT   t | dƒr| jS t | dƒrL| jdkr*| jS t | dƒrFd| jj| jf S | jS | jjS )Nr@   Ú	func_namez<lambda>Úim_classz%s.%s)r$   r@   rK   r   rL   r   Ú	__class__)r2   r   r   r   Úprocessor_name±   s    



rN   c              	   C   s@  t t ¡ ƒ}d |d| tr"ttƒnd|r0t|ƒnd¡}t| |||d���Þ}	t d¡}
t d¡}| 	||
¡ t d¡}t d	¡}| 
||¡\}}}|jg |gg d
tjjd� |d urÚt||||
ƒ\}}| ||||¡\}}nd }g }t ¡ � t |¡ W d   ƒ n1 �s0    Y  t ¡ � t |¡ W d   ƒ n1 �s@0    Y  t d¡}|jg |d�}t d¡}| |g ¡ t tjd|gt|ƒ t|ƒ |g |d�¡ t |¡ t ¡ � t |¡ W d   ƒ n1 �sÚ0    Y  t ¡ � t |
¡ W d   ƒ n1 �s0    Y  W d   ƒ n1 �s.0    Y  ||	fS )Nú{0}/{1}/{2}/{3}/{4}rE   ÚNoInputÚNoOutput)r@   rA   rF   Znum_instancesz	pipe:exitz	pipe:initzpipe:instance:initzpipe:instance:exitF©ÚshapeÚvalueZdtypeÚtimer_start©Zcounter_nameÚ	timer_endÚbody©Zshould_stop_blob)Ústrr
   r   Úformatr>   rN   r   r   r   r&   Úread_record_exÚConstantFillÚDataTypeÚBOOLr+   Úwrite_record_exr   Z	task_initÚnetZtask_instance_initÚ
TimerBeginÚTimerEndÚexecution_stepr   Ztask_instance_exitZ	task_exit)r@   rA   rH   r3   r?   r'   r    Ú	node_nameÚprofiler_namerI   r)   r(   Úinit_netÚexit_netÚ	read_netsÚstatusr-   r*   r!   Ú
write_netsrD   Útimer_start_netÚtimerÚtimer_end_netr   r   r   Ú_runtime_threads_task½   sl    ûÿ



üÿÿ

*
*

ÿü

*
Jro   c                 C   s@  t t ¡ ƒ}d |d| tr"ttƒnd|r0t|ƒnd¡}t| ||d���à}	t d¡}
t d¡}| 	||
¡ d }d }g }t
|ƒD �]n}td| d	���8}t d¡}t d¡}| ||¡\}}}|jg |gg d
tjjd� |d u�r>|d u �r(t|	jd��" t||||
ƒ\}}W d   ƒ n1 �s0    Y  | ||||¡\}}ng }t d¡}|jg |d�}t d¡}| |g ¡ t |¡ t tjd|gt|ƒ t|ƒ |g |d�¡ t |¡ t |¡ W d   ƒ n1 �sÒ0    Y  | t |¡¡ q|t |¡ t tjd|dd�¡ t |
¡ W d   ƒ n1 �s.0    Y  ||	fS )NrO   rE   rP   rQ   )r@   rA   rF   ÚexitÚinitzt:%d)r@   FrR   )Z	_fullnamerU   rV   rW   rX   rY   T)Zconcurrent_substeps)rZ   r
   r   r[   r>   rN   r   r   r   r&   Úranger   r\   r]   r^   r_   r@   r+   r`   rb   rc   r   ra   rd   r   ÚappendZto_execution_step)r@   rA   rH   r3   r?   r'   r    re   rf   rI   r)   r(   r*   r!   ZstepsZ	thread_idÚnbrg   rh   ri   rj   r-   rk   rD   rl   rm   rn   r   r   r   Ú_static_threads_taskù   st    û



ÿ
ü

þ(ÿ



ÿü
*
*ru   c	           
      C   s   |dks|dksJ dƒ‚t | tƒr(| }	n&t| dƒr<|  ¡ }	ntd t| ƒ¡ƒ‚|dur`t|	|ƒ}	|dksp|dkr„|du s|J ‚|	dfS |du rœ|durœt|ƒ}|du r¸|dur¸dt|ƒ }|du rÌdt| ƒ }|dkrèt	||||	|||ƒS t
||||	|||ƒS dS )	z
    r9   z;Only one of num_threads or num_runtime_threads must be set.r3   z/Input must be a reader, queue or stream. Got {}Nr   zpipe_into:%szpipe_from:%s)r   r   r$   r3   r%   r[   rG   ÚProcessingReaderrN   ru   ro   )
r>   r'   r?   r2   r@   r    rA   rB   rH   r3   r   r   r   r=   :  s:    ÿ


ÿ
ÿþr=   c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )rv   zo
    Reader that reads from an upstream reader, calls the processor, and returns
    the processed record.
    c                 C   s    t  | ¡ || _t||ƒ| _d S r,   )r   r   r3   r7   r2   )r   r3   r2   r   r   r   r   f  s    
zProcessingReader.__init__c                 C   s
   | j  ¡ S r,   )r2   r6   ©r   r   r   r   r6   k  s    zProcessingReader.schemac                 C   s   | j  ||¡ d S r,   )r3   r&   )r   rg   Z
finish_netr   r   r   r&   n  s    zProcessingReader.setup_exc           
      C   sì   | j  ||¡\}}}tƒ �}t|  |¡ƒ}W d   ƒ n1 s>0    Y  ||j7 }|js^|jr¦t 	d¡}|jr‚| 
||jg|g¡ |jrœ| 
||jg|g¡ | |¡ t| jdƒrÂ| tj| j¡ |  |j¡ |jrÞ|j ¡ nd }	|||	fS )NÚstop_netÚsetup)r3   r\   r   r<   r2   r   r   Z
_stop_blobr   r   ÚOrrs   r$   Zadd_attributer   ZLOCAL_SETUPZ_set_schemar   Zfield_blobs)
r   rg   rh   ri   rj   r-   rt   rC   rx   Úfieldsr   r   r   Úread_exq  s     ,


zProcessingReader.read_exN)r   r   r   r   r   r6   r&   r|   r   r   r   r   rv   a  s
   rv   c                   @   s:   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ Zdd„ ZdS )r5   zø
    Processor that clones a core.Net each time it's called, executing
    the cloned net as the processor. It requires the Net to have input
    and (optionally) output records set, with net.set_input_record() and
    net.set_output_record().
    Nc                 C   sb   t |tjƒsJ ‚|d u s(t |tjƒs(J ‚|p2t|ƒ| _|p<g | _|| _|| _g | _	d| _
g | _d S )NF)r   r   r   r;   rZ   r@   Úthread_init_netsra   Ú_stop_signalÚ
_blob_mapsÚ_frozenÚ_cloned_init_nets)r   ra   Ústop_signalr}   r@   r   r   r   r   ”  s    
ÿ
zNetProcessor.__init__c                 C   s
   | j  ¡ S r,   )ra   Úoutput_recordrw   r   r   r   r6      s    zNetProcessor.schemac                 C   s   d| _ | j}g | _|S ©NT)r€   r�   )r   rg   Zcloned_init_netsr   r   r   ry   £  s    zNetProcessor.setupc           	      C   sÎ   | j r
J ‚t ¡ jd }i }| jD ],}t |t|ƒ| ||¡\}}| j 	|¡ q"t | j
t| j
ƒ| |||¡\}}| jd u r‚d }n.t| jƒ|v rªtj|t| jƒ |d�}n| j}| j 	|¡ t|g| ¡ |ƒS )Nú/)ra   )r€   r   r   r@   r}   r   Zclone_and_bind_netrZ   r�   rs   ra   r~   r;   r   r   rƒ   )	r   r-   ÚprefixZ
blob_remapra   Znew_netrD   Z
remappingsr‚   r   r   r   Ú__call__©  s*    

ÿÿ
þzNetProcessor.__call__c                 C   s   d| _ | jS r„   )r€   r   rw   r   r   r   Ú	blob_mapsÁ  s    zNetProcessor.blob_maps)NNN)	r   r   r   r   r   r6   ry   r‡   rˆ   r   r   r   r   r5   �  s   
r5   )N)Nr9   NNNNr9   )Nr9   NNNNr9   N)Nr9   NNNNNN)Zcaffe2.pythonr   r   Zcaffe2.python.dataior   r   Zcaffe2.python.net_builderr   r   Zcaffe2.python.schemar   r	   Zcaffe2.python.taskr
   r   r   Úobjectr   r#   r+   r7   r<   rE   rJ   rN   ro   ru   r=   rv   r5   r   r   r   r   Ú<module>   s.   
  þ
6  þ
<B  þ
',