
    BVh?                     r   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZ  G d de	j*                        Z G d de	j.                        Z G d de	j2                        Z G d de      Z G d de      Z G d de	j:                        Z G d de      Z ddZ!y)z0Various classes representing distributed inputs.    )cardinality)dataset_ops)multi_device_iterator_ops)optional_ops)	input_lib)context)ops)control_flow_ops)data)
deprecatedc                   P     e Zd ZdZ	 	 	 d	 fd	Zd Zd Zd Zd
dZd Z	d Z
 xZS )DistributedDatasetV1zBDistributed dataset that supports prefetching to multiple devices.c                 F    || _         t        t        |   ||||||       y )N)num_replicas_in_syncinput_contextoptions)_input_workerssuperr   __init__)selfdatasetinput_workersstrategyr   r   r   	__class__s          Y/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/distribute/v1/input_lib.pyr   zDistributedDatasetV1.__init__    s4     (D	
.1# /     c                 "    | j                         S )zGet a one time use iterator for DistributedDatasetV1.

    Note: This API is deprecated. Please use `for ... in dataset:` to iterate
    over the dataset or `iter` to create an iterator.

    Returns:
      A DistributedIteratorV1 instance.
    )_make_one_shot_iteratorr   s    r   make_one_shot_iteratorz+DistributedDatasetV1.make_one_shot_iterator0   s     ''))r   c                 `    t        j                         st        d      | j                         S )z)Get an iterator for DistributedDatasetV1.VCannot create a one shot iterator. Please use `make_initializable_iterator()` instead.r   executing_eagerly
ValueError_get_iteratorr   s    r   r   z,DistributedDatasetV1._make_one_shot_iterator;   4    
 $$& B C Cr   c                 "    | j                         S )a  Get an initializable iterator for DistributedDatasetV1.

    Note: This API is deprecated. Please use
    `tf.compat.v1.data.make_initializable_iterator(dataset)` to create an
    initializable iterator.

    Returns:
      A DistributedIteratorV1 instance.
    )_make_initializable_iteratorr   s    r   make_initializable_iteratorz0DistributedDatasetV1.make_initializable_iteratorE   s     ,,..r   c                 `    t        j                         rt        d      | j                         S )z7Get an initializable iterator for DistributedDatasetV1.PCannot create initializable iterator in Eager mode. Please use `iter()` instead.r#   r   shared_names     r   r)   z1DistributedDatasetV1._make_initializable_iteratorQ   s1       " 6 7 7r   c                 l   t        | j                  | j                  | j                        }t	        j
                  | j                  d         }t        | j                  || j                  || j                        }| j                  |_
        t        j                         rt        j                          |S Nr   )_create_iterators_per_worker_cloned_datasetsr   _optionsr   _cardinalityDistributedIteratorV1	_strategy_enable_get_next_as_optionalelement_spec_element_specr   r$   
async_wait)r   worker_iteratorsr   iterators       r   r&   z"DistributedDatasetV1._get_iteratorZ   s    3D4I4I484G4G48MMC (()>)>q)ABK$T%8%8:J%)^^[%)%F%FHH "..H
   "Or   c                     t        j                         st        j                         j                  r| j	                         S t        d      NzV__iter__() is only supported inside of tf.function or when eager execution is enabled.r	   #executing_eagerly_outside_functionsget_default_graphbuilding_functionr&   RuntimeErrorr   s    r   __iter__zDistributedDatasetV1.__iter__m   A    //111!!
 = > >r   )NNNN)__name__
__module____qualname____doc__r   r    r   r*   r)   r&   rD   __classcell__r   s   @r   r   r      s4    J %)! 	* 
/ &>r   r   c                   *    e Zd ZdZddZd Zd Zd Zy)!DistributedDatasetsFromFunctionV1z%Inputs created from dataset function.Nc                 b    ~t        j                         rt        d      | j                         S )zDGet an initializable iterator for DistributedDatasetsFromFunctionV1.r,   r#   r-   s     r   r)   z>DistributedDatasetsFromFunctionV1._make_initializable_iterator|   s4       " 6 7 7r   c                 `    t        j                         st        d      | j                         S )zEGet an iterator for iterating over DistributedDatasetsFromFunctionV1.r"   r#   r   s    r   r   z9DistributedDatasetsFromFunctionV1._make_one_shot_iterator   r'   r   c                 l   t        | j                  | j                  | j                        }t	        j
                  | j                  d         }t        | j                  || j                  || j                        }| j                  |_	        t        j                         rt        j                          |S r0   )r1   	_datasetsr   r3   r   r4   r5   r6   r7   r9   r   r$   r:   )r   	iteratorsr   r<   s       r   r&   z/DistributedDatasetsFromFunctionV1._get_iterator   s    ,T^^-1-@-@$--QI(():;K$T%8%8)%)^^[%)%F%FHH "//H
   "Or   c                     t        j                         st        j                         j                  r| j	                         S t        d      r>   r?   r   s    r   rD   z*DistributedDatasetsFromFunctionV1.__iter__   rE   r   rF   )rG   rH   rI   rJ   r)   r   r&   rD    r   r   rN   rN   x   s    -  $>r   rN   c                       e Zd ZdZed        Z edd      d        Zed        Zed        Z	ed        Z
ed	        Zd
 Zed        Zy)r5   z)Input Iterator for a distributed dataset.c                     g }| j                   D ]!  }|j                  |j                                # t        j                  |      S rF   )
_iteratorsextend
initializer
   group)r   init_opsits      r   _initializerz"DistributedIteratorV1._initializer   s=    Hoo 'oobmmo&'!!(++r   Nz2Use the iterator's `initializer` property instead.c                     | j                   S )zkInitialize underlying iterators.

    Returns:
      A list of any initializer ops that should be run.
    )r^   r   s    r   rZ   z DistributedIteratorV1.initialize   s     r   c                 "    | j                         S )z3Returns a list of ops that initialize the iterator.)rZ   r   s    r   initializerz!DistributedIteratorV1.initializer   s     ??r   c                 4    | j                   d   j                  S r0   )rX   output_classesr   s    r   rc   z$DistributedIteratorV1.output_classes   s    ??1,,,r   c                 4    | j                   d   j                  S r0   )rX   output_shapesr   s    r   re   z#DistributedIteratorV1.output_shapes   s    ??1+++r   c                 4    | j                   d   j                  S r0   )rX   output_typesr   s    r   rg   z"DistributedIteratorV1.output_types   s    ??1***r   c                 ~    t        | j                  j                        D ]  \  }}||k(  s| j                  |   c S  y rF   )	enumerater   worker_devicesrX   )r   workeriws       r   get_iteratorz"DistributedIteratorV1.get_iterator   sA    $--<<= "1	1q!!" r   c                     | j                   S )z6The type specification of an element of this iterator.)r9   r   s    r   r8   z"DistributedIteratorV1.element_spec   s     r   )rG   rH   rI   rJ   propertyr^   r   rZ   ra   rc   re   rg   rn   r8   rU   r   r   r5   r5      s    1
 , , dHI J  
 - - , , + +  r   r5   c                   (     e Zd ZdZ	 	 d fd	Z xZS )DatasetIteratorz$Iterator created from input dataset.c                     t        |||||      }t        |j                  |      }t        t        |   ||||j                  |j                         |j                  | _	        y)ai  Make an iterator for the dataset on given devices.

    If `num_replicas_in_sync` is not None, we split each batch of the dataset
    into `num_replicas_in_sync` smaller batches, to be distributed among that
    worker's replicas, so that the batch size for a global step (across all
    workers and replicas) is as expected.

    Args:
      dataset: `tf.data.Dataset` that will be used as the input source.
      input_workers: an `InputWorkers` object.
      strategy: a `tf.distribute.Strategy` object, used to run all-reduce to
        handle last partial batch.
      num_replicas_in_sync: Optional integer. If this is not None, the value is
        used to decide how to rebatch datasets into smaller batches so that the
        total batch size for each step (across all workers and replicas) adds up
        to `dataset`'s batch size.
      input_context: `InputContext` for sharding. Only pass this in for between
        graph multi-worker cases where there is only one `input_worker`. In
        these cases, we will shard based on the `input_pipeline_id` and
        `num_input_pipelines` in the `InputContext`.
    )r   r   N)
r   r1   r2   r   rr   r   r   r7   r8   r9   )	r   r   r   r   r   r   dist_datasetr;   r   s	           r   r   zDatasetIterator.__init__   ss    6 (1#%L 4%%}6	/
&(8(%11%BBD &22Dr   )NNrG   rH   rI   rJ   r   rK   rL   s   @r   rr   rr      s    , %)!(3 (3r   rr   c                   "     e Zd ZdZ fdZ xZS )InputFunctionIteratorz%Iterator created from input function.c                    t        |t        j                        sJ |j                  t	        |      k7  r#t        d|j                  t	        |      fz        g }t        |      D ]  \  }}|j                  |   }t        j                  |      5   ||      }	|j                  |      }
t        |	t        j                        rt        |	||
      }n$t        |	      rt        |	||
      }nt        d      |j!                  |       ddd        t"        t$        | O  |||t(        j*                  d       d| _        y# 1 sw Y   xY w)a|  Make an iterator for input provided via an input function.

    Currently implements PER_WORKER mode, in which the `input_fn` is called
    once on each worker.

    TODO(priyag): Add other replication modes.

    Args:
      input_fn: Input function that returns a `tf.data.Dataset` object.
      input_workers: an `InputWorkers` object.
      input_contexts: A list of `InputContext` instances to be passed to call(s)
        to `input_fn`. Length and order should match worker order in
        `worker_device_pairs`.
      strategy: a `tf.distribute.Strategy` object, used to run all-reduce to
        handle last partial batch.
    zINumber of input workers (%d) is not same as number of input_contexts (%d)z5input_fn must return a tf.data.Dataset or a callable.NF)r   enable_get_next_as_optional)
isinstancer   InputWorkersnum_workerslenr%   ri   rj   r	   devicecompute_devices_for_worker
data_types	DatasetV2_SingleWorkerDatasetIteratorcallable_SingleWorkerCallableIteratorappendr   rw   r   cardinality_libUNKNOWNr7   )r   input_fnr   input_contextsr   rS   rl   ctxrk   resultdevicesr<   r   s               r   r   zInputFunctionIterator.__init__  sS   " mY%;%;<<<  C$77 -%113~3FGH I I IN+ #3++A.f::f 
##::1=fj2231&&'J(f2667K(EG G"
# 
## 

/#++$) 0 + ).D%%
# 
#s   A7D??E	ru   rL   s   @r   rw   rw     s    -,. ,.r   rw   c                   L    e Zd ZdZd Zd Zed        Zed        Zed        Z	y)r   z4Iterator for a single DistributedDatasetV1 instance.c                    t        j                  | j                        5  | j                  [t	        j
                  | j                  | j                  | j                  j                  | j                  j                        | _	        n/t	        j
                  | j                  | j                        | _	        ddd       y# 1 sw Y   yxY w)z)Make appropriate iterator on the dataset.N)max_buffer_sizeprefetch_buffer_size)
r	   r~   _workerr3   r   MultiDeviceIterator_dataset_devices$experimental_per_replica_buffer_size	_iteratorr   s    r   _make_iteratorz+_SingleWorkerDatasetIterator._make_iteratorH  s    	DLL	! 
		"2FFMMMM MMNN!%113 3FFMMMM

 
 
s   BC  C	c                     t        j                         r| j                  j                          g S | j                  j                  gS )a
  Initialize underlying iterator.

    In eager execution, this simply recreates the underlying iterator.
    In graph execution, it returns the initializer ops for the underlying
    iterator.

    Returns:
      A list of any initializer ops that should be run.
    )r	   r@   r   _eager_resetra   r   s    r   rZ   z'_SingleWorkerDatasetIterator.initializeX  s8     ..0
nn!!#inn(())r   c                 @    t        j                  | j                        S rF   )r   get_legacy_output_classesr   r   s    r   rc   z+_SingleWorkerDatasetIterator.output_classesh  s    00@@r   c                 @    t        j                  | j                        S rF   )r   get_legacy_output_shapesr   r   s    r   re   z*_SingleWorkerDatasetIterator.output_shapesl  s    //??r   c                 @    t        j                  | j                        S rF   )r   get_legacy_output_typesr   r   s    r   rg   z)_SingleWorkerDatasetIterator.output_typesp  s    ..t~~>>r   N)
rG   rH   rI   rJ   r   rZ   rp   rc   re   rg   rU   r   r   r   r   E  sO    <
 *  A A @ @ ? ?r   r   c                   2    e Zd ZdZd ZddZddZd Zd Zy)	r   z0Iterator for a single tensor-returning callable.c                 .    || _         || _        || _        y rF   )_fnr   r   )r   fnrk   r   s       r   r   z&_SingleWorkerCallableIterator.__init__x  s    DHDLDMr   Nc                     ~~t        j                  | j                        5  | j                         cddd       S # 1 sw Y   yxY w)z8Get next element for the given device from the callable.N)r	   r~   r   r   )r   r~   names      r   get_nextz&_SingleWorkerCallableIterator.get_next}  s5    	DLL	! XXZ  s	   <Ac                     ~t        j                  | j                        5  | j                  D cg c]  }| j	                          }}|cddd       S c c}w # 1 sw Y   yxY w)z#Get next element from the callable.N)r	   r~   r   r   r   )r   r   _	data_lists       r   get_next_as_listz._SingleWorkerCallableIterator.get_next_as_list  sR    	DLL	! '+}}5!488:5i5 5 s   AAAAA"c                    t        j                  | j                        5  | j                  D cg c]/  }t        j
                  j                  | j                               1 }}|cd d d        S c c}w # 1 sw Y   y xY wrF   )r	   r~   r   r   r   Optional
from_valuer   )r   r   r   s      r   get_next_as_optional_listz7_SingleWorkerCallableIterator.get_next_as_optional_list  sk    	DLL	! @D;<,


*
*488:
6i  	  s   A54A0#A50A55A>c                     g S rF   rU   r   s    r   rZ   z(_SingleWorkerCallableIterator.initialize  s    Ir   rF   )	rG   rH   rI   rJ   r   r   r   r   rZ   rU   r   r   r   r   u  s    8
r   r   Nc                 |   t        |t        j                        sJ t        |       t        |j                        k(  sJ g }t        |j                        D ]V  \  }}t        j                  |      5  |j                  |      }t        | |   |||      }|j                  |       ddd       X |S # 1 sw Y   dxY w)z5Create a multidevice iterator on each of the workers.N)rz   r   r{   r}   rj   ri   r	   r~   r   r   r   )worker_datasetsr   r   rS   rl   rk   rj   r<   s           r   r1   r1     s    	M9#9#9	::	:	_	]%A%A!B	BB	B)]99: !ia	F	 !$??Bn-
!



	h
 x ! !! 
! !s   24B22B;	rF   )"rJ   'tensorflow.python.data.experimental.opsr   r   tensorflow.python.data.opsr   r   r   tensorflow.python.distributer   tensorflow.python.eagerr   tensorflow.python.frameworkr	   tensorflow.python.opsr
   tensorflow.python.typesr   r   "tensorflow.python.util.deprecationr   DistributedDatasetr   DistributedDatasetsFromFunctionrN   DistributedIteratorBaser5   rr   rw    _SingleWorkerDatasetIteratorBaser   objectr   r1   rU   r   r   <module>r      s    7 R 2 @ 3 2 + + 2 6 9V>977 V>v0>--0>j4I== 4n+3+ +3^/.1 /.d-?9#M#M -?`F Br   