
    BVhS                        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
 Z edddg       ej                   d       G d d                    Z ed       G d d             Z ed       G d d             Zy)z3A Python interface for creating TensorFlow servers.    )cluster_pb2)device_filters_pb2)tensorflow_server_pb2)pywrap_tf_session)errors)compat)deprecation)	tf_exportc                    t        j                         }t        | t         j                        rK|j                  |        |||_        |||_        |||_        ||j                  j                  |       |S 	 t        |       }|3t        |j                        dk(  r|j                  d   }nt        d      |0|j                  |      }t        |      dk(  r|d   }nt        d      |d}t        j                  |j                         |||      }||j                  j                  |       |S # t        $ r t        d      w xY w)a  Creates a `tf.train.ServerDef` protocol buffer.

  Args:
    server_or_cluster_def: A `tf.train.ServerDef` or `tf.train.ClusterDef`
      protocol buffer, or a `tf.train.ClusterSpec` object, describing the server
      to be defined and/or the cluster of which it is a member.
    job_name: (Optional.) Specifies the name of the job of which the server is a
      member. Defaults to the value in `server_or_cluster_def`, if specified.
    task_index: (Optional.) Specifies the task index of the server in its job.
      Defaults to the value in `server_or_cluster_def`, if specified. Otherwise
      defaults to 0 if the server's job has only one task.
    protocol: (Optional.) Specifies the protocol to be used by the server.
      Acceptable values include `"grpc", "grpc+verbs"`. Defaults to the value in
      `server_or_cluster_def`, if specified. Otherwise defaults to `"grpc"`.
    config: (Options.) A `tf.compat.v1.ConfigProto` that specifies default
      configuration options for all sessions that run on this server.

  Returns:
    A `tf.train.ServerDef`.

  Raises:
    TypeError: If the arguments do not have the appropriate type.
    ValueError: If an argument is not specified and cannot be inferred.
  z^Could not convert `server_or_cluster_def` to a `tf.train.ServerDef` or `tf.train.ClusterSpec`.   r   z$Must specify an explicit `job_name`.z&Must specify an explicit `task_index`.grpc)clusterjob_name
task_indexprotocol)r   	ServerDef
isinstance	MergeFromr   r   r   default_session_configClusterSpec	TypeErrorlenjobs
ValueErrortask_indicesas_cluster_def)server_or_cluster_defr   r   r   config
server_defcluster_specr   s           U/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/server_lib.py_make_server_defr"      sy   4 %..0*%'<'F'FG./$j(j$j''11&98 
5I !67l 	\	1	$$$Q'?@@!..x8l	\	a	!!_
ABBh&00++-	J
 ''11&9	1  I H I IIs   ;D7 7Ezdistribute.Serverztrain.Server)v1c                   f    e Zd ZdZ	 	 	 	 	 d
dZd Zd Zd Zed        Z	ed        Z
edd	       Zy)Servera  An in-process TensorFlow server, for use in distributed training.

  A `tf.distribute.Server` instance encapsulates a set of devices and a
  `tf.compat.v1.Session` target that
  can participate in distributed training. A server belongs to a
  cluster (specified by a `tf.train.ClusterSpec`), and
  corresponds to a particular task in a named job. The server can
  communicate with any other server in the same cluster.
  Nc                     t        |||||      | _        t        j                  | j                  j	                               | _        |r| j                          yy)a  Creates a new server with the given definition.

    The `job_name`, `task_index`, and `protocol` arguments are optional, and
    override any information provided in `server_or_cluster_def`.

    Args:
      server_or_cluster_def: A `tf.train.ServerDef` or `tf.train.ClusterDef`
        protocol buffer, or a `tf.train.ClusterSpec` object, describing the
        server to be created and/or the cluster of which it is a member.
      job_name: (Optional.) Specifies the name of the job of which the server is
        a member. Defaults to the value in `server_or_cluster_def`, if
        specified.
      task_index: (Optional.) Specifies the task index of the server in its job.
        Defaults to the value in `server_or_cluster_def`, if specified.
        Otherwise defaults to 0 if the server's job has only one task.
      protocol: (Optional.) Specifies the protocol to be used by the server.
        Acceptable values include `"grpc", "grpc+verbs"`. Defaults to the value
        in `server_or_cluster_def`, if specified. Otherwise defaults to
        `"grpc"`.
      config: (Options.) A `tf.compat.v1.ConfigProto` that specifies default
        configuration options for all sessions that run on this server.
      start: (Optional.) Boolean, indicating whether to start the server after
        creating it. Defaults to `True`.

    Raises:
      tf.errors.OpError: Or one of its subclasses if an error occurs while
        creating the TensorFlow server.
    N)r"   _server_defc_apiTF_NewServerSerializeToString_serverstart)selfr   r   r   r   r   r,   s          r!   __init__zServer.__init__k   sQ    F ((=x(2HfFD%%d&6&6&H&H&JKDL
jjl     c                     t         t         j                  }nt        }	 t        j                  | j
                         d | _        y # t        $ r
 Y d | _        y |$ r
 Y d | _        y w xY wN)r   UnimplementedError	Exceptionr(   TF_ServerStopr+   AttributeError)r-   	exceptions     r!   __del__zServer.__del__   si    ++ii
$,,' DL  
 DL  
DLs   A 	A&A&%A&c                 B    t        j                  | j                         y)zStarts this server.

    Raises:
      tf.errors.OpError: Or one of its subclasses if an error occurs while
        starting the TensorFlow server.
    N)r(   TF_ServerStartr+   r-   s    r!   r,   zServer.start   s     
&r/   c                 B    t        j                  | j                         y)zBlocks until the server has shut down.

    This method currently blocks forever.

    Raises:
      tf.errors.OpError: Or one of its subclasses if an error occurs while
        joining the TensorFlow server.
    N)r(   TF_ServerJoinr+   r:   s    r!   joinzServer.join   s     
%r/   c                     | j                   S )zReturns the `tf.train.ServerDef` for this server.

    Returns:
      A `tf.train.ServerDef` protocol buffer that describes the configuration
      of this server.
    )r'   r:   s    r!   r   zServer.server_def   s     r/   c                 @    t        j                  | j                        S )az  Returns the target for a `tf.compat.v1.Session` to connect to this server.

    To create a
    `tf.compat.v1.Session` that
    connects to this server, use the following snippet:

    ```python
    server = tf.distribute.Server(...)
    with tf.compat.v1.Session(server.target):
      # ...
    ```

    Returns:
      A string containing a session target for this server.
    )r(   TF_ServerTargetr+   r:   s    r!   targetzServer.target   s    "   ..r/   c                 &    t        ddgid| |      S )ad  Creates a new single-process cluster running on the local host.

    This method is a convenience wrapper for creating a
    `tf.distribute.Server` with a `tf.train.ServerDef` that specifies a
    single-process cluster containing a single task in a job called
    `"local"`.

    Args:
      config: (Options.) A `tf.compat.v1.ConfigProto` that specifies default
        configuration options for all sessions that run on this server.
      start: (Optional.) Boolean, indicating whether to start the server after
        creating it. Defaults to `True`.

    Returns:
      A local `tf.distribute.Server`.
    	localhostzlocalhost:0r   )r   r   r,   )r%   )r   r,   s     r!   create_local_serverzServer.create_local_server   s#    ( ;0! r/   )NNNNT)NT)__name__
__module____qualname____doc__r.   r7   r,   r=   propertyr   rA   staticmethodrD    r/   r!   r%   r%   ^   si     'R&'	&   / /$  r/   r%   ztrain.ClusterSpecc                   l    e Zd ZdZd Zd ZeZd Zd Zd Z	d Z
d Zed	        Zd
 Zd Zd Zd Zd Zy)r   a  Represents a cluster as a set of "tasks", organized into "jobs".

  A `tf.train.ClusterSpec` represents the set of processes that
  participate in a distributed TensorFlow computation. Every
  `tf.distribute.Server` is constructed in a particular cluster.

  To create a cluster with two jobs and five tasks, you specify the
  mapping from job names to lists of network addresses (typically
  hostname-port pairs).

  ```python
  cluster = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222",
                                             "worker1.example.com:2222",
                                             "worker2.example.com:2222"],
                                  "ps": ["ps0.example.com:2222",
                                         "ps1.example.com:2222"]})
  ```

  Each job may also be specified as a sparse mapping from task indices
  to network addresses. This enables a server to be configured without
  needing to know the identity of (for example) all other worker
  tasks:

  ```python
  cluster = tf.train.ClusterSpec({"worker": {1: "worker1.example.com:2222"},
                                  "ps": ["ps0.example.com:2222",
                                         "ps1.example.com:2222"]})
  ```
  c                 l   t        |t              ri | _        |j                         D ]  \  }}t        |t        t
        f      rt        |      D ci c]  \  }}||
 }}}nKt        |t              r-|j                         D ci c]  \  }}t        |      | }}}nt        d|z        || j                  |<    | j                          yt        |t        j                        ro|| _        i | _        | j                  j                  D ]G  }|j                  j                         D ci c]  \  }}||
 c}}| j                  |j                  <   I yt        |t               rt        j                         | _        | j                  j#                  |j%                                i | _        | j                  j                  D ]G  }|j                  j                         D ci c]  \  }}||
 c}}| j                  |j                  <   I yt        d      c c}}w c c}}w c c}}w c c}}w )a  Creates a `ClusterSpec`.

    Args:
      cluster: A dictionary mapping one or more job names to (i) a list of
        network addresses, or (ii) a dictionary mapping integer task indices to
        network addresses; or a `tf.train.ClusterDef` protocol buffer.

    Raises:
      TypeError: If `cluster` is not a dictionary mapping strings to lists
        of strings, and not a `tf.train.ClusterDef` protobuf.
    zMThe tasks for job %r must be a list or a dictionary from integers to strings.z}`cluster` must be a dictionary mapping one or more job names to lists of network addresses, or a `ClusterDef` protocol bufferN)r   dict_cluster_specitemslisttuple	enumerateintr   _make_cluster_defr   
ClusterDef_cluster_defjobtasksnamer   r   r   )	r-   r   r   rY   itask	job_tasksjob_defts	            r!   r.   zClusterSpec.__init__  s    '4 d$]]_ 1/(EedE]+.7.>?71dq$w?)?t$38;;=A4s1vt|A)A 68@A B B'08$1 	G[33	4!dd&&** 
'$]]002,
QAqD,
7<<(
 
G[	)%002d
!!'"8"8":;d&&** 
'$]]002,
QAqD,
7<<(

  5 6 61 @A,
,
s   HH$.H*(H0c                 ,    t        | j                        S r1   )boolrO   r:   s    r!   __bool__zClusterSpec.__bool__>  s    ""##r/   c                      | j                   |k(  S r1   rO   r-   others     r!   __eq__zClusterSpec.__eq__D      &&r/   c                      | j                   |k7  S r1   rd   re   s     r!   __ne__zClusterSpec.__ne__G  rh   r/   c                     | j                         }t        |      D cg c]  }t        |      dz   t        ||         z   ! }}ddj                  |      z   dz   S c c}w )Nz: zClusterSpec({z, z}))as_dictsortedreprr=   )r-   
key_valueskstring_itemss       r!   __repr__zClusterSpec.__repr__J  sb    J6<Z6H12Q$jm,,L  TYY|44t;;s   $Ac           	      &   i }| j                   D ]z  }| j                  |      }t        |      dk(  ri ||<   (t        |      dz   t        |      k(  r| j	                  |      ||<   W|D ci c]  }|| j                  ||       c}||<   | |S c c}w )a  Returns a dictionary from job names to their tasks.

    For each job, if the task index space is dense, the corresponding
    value will be a list of network addresses; otherwise it will be a
    dictionary mapping (sparse) task indices to the corresponding
    addresses.

    Returns:
      A dictionary mapping job names to lists or dictionaries
      describing the tasks in those jobs.
    r   r   )r   r   r   maxr]   task_address)r-   retrX   r   r[   s        r!   rl   zClusterSpec.as_dictQ  s     Cyy H&&s+l	\	a	C	\	Q	#l"3	3 >>#&C:FGQAt((a00GCH J Hs   *Bc                     | j                   S )zFReturns a `tf.train.ClusterDef` protocol buffer based on this cluster.)rW   r:   s    r!   r   zClusterSpec.as_cluster_defl  s    r/   c                 H    t        | j                  j                               S )zReturns a list of job names in this cluster.

    Returns:
      A list of strings, corresponding to the names of jobs in this cluster.
    )rQ   rO   keysr:   s    r!   r   zClusterSpec.jobsp  s     ""'')**r/   c                 n    	 | j                   |   }t        |      S # t        $ r t        d|z        w xY w)a  Returns the number of tasks defined in the given job.

    Args:
      job_name: The string name of a job in this cluster.

    Returns:
      The number of tasks defined in the given job.

    Raises:
      ValueError: If `job_name` does not name a job in this cluster.
    No such job in cluster: %r)rO   KeyErrorr   r   r-   r   rX   s      r!   	num_taskszClusterSpec.num_tasksy  sG    @x(c s8O  @3h>??@s    4c                     	 | j                   |   }t        t	        |j                                     S # t        $ r t        d|z        w xY w)aV  Returns a list of valid task indices in the given job.

    Args:
      job_name: The string name of a job in this cluster.

    Returns:
      A list of valid task indices in the given job.

    Raises:
      ValueError: If `job_name` does not name a job in this cluster,
      or no task with index `task_index` is defined in that job.
    r{   )rO   r|   r   rQ   rm   ry   r}   s      r!   r   zClusterSpec.task_indices  sT    @x(c sxxz"##  @3h>??@s	   3 Ac                     	 | j                   |   }	 ||   S # t        $ r t        d|z        w xY w# t        $ r t        d|d|      w xY w)a  Returns the address of the given task in the given job.

    Args:
      job_name: The string name of a job in this cluster.
      task_index: A non-negative integer.

    Returns:
      The address of the given task in the given job.

    Raises:
      ValueError: If `job_name` does not name a job in this cluster,
      or no task with index `task_index` is defined in that job.
    r{   zNo task with index z in job )rO   r|   r   )r-   r   r   rX   s       r!   ru   zClusterSpec.task_address  sr    @x(c/_  @3h>??@  /"H. / //s    2 /Ac                    	 | j                   |   }t        t	        |j                               dz         D cg c]  }d }}|j                         D ]
  \  }}|||<    |S # t        $ r t        d|z        w xY wc c}w )a  Returns a mapping from task ID to address in the given job.

    NOTE: For backwards compatibility, this method returns a list. If
    the given job was defined with a sparse set of task indices, the
    length of this list may not reflect the number of tasks defined in
    this job. Use the `tf.train.ClusterSpec.num_tasks` method
    to find the number of tasks defined in a particular job.

    Args:
      job_name: The string name of a job in this cluster.

    Returns:
      A list of task addresses, where the index in the list
      corresponds to the task index of each task. The list may contain
      `None` if the job was defined with a sparse set of task indices.

    Raises:
      ValueError: If `job_name` does not name a job in this cluster.
    r{   r   N)rO   r|   r   rangert   ry   rP   )r-   r   rX   _rv   r[   r\   s          r!   r]   zClusterSpec.job_tasks  s    (@x(c s388:23
4A4
4C
499; 4c!fJ  @3h>??@
4s   A" 	A="A:c                    t        j                         | _        t        | j                  j                               D ]  \  }}	 t        j                  |      }| j                  j                  j                         }||_        t        |j                               D ]*  \  }}	 t        j                  |      }||j                  |<   ,  y# t        $ r t        d|z        w xY w# t        $ r t        d|z        w xY w)zCreates a `tf.train.ClusterDef` based on the given `cluster_spec`.

    Raises:
      TypeError: If `cluster_spec` is not a dictionary mapping strings to lists
        of strings.
    $Job name %r must be bytes or unicodez(Task address %r must be bytes or unicodeN)r   rV   rW   rm   rO   rP   r   as_bytesr   rX   addrZ   rY   )r-   r   rY   r^   r[   ru   s         r!   rU   zClusterSpec._make_cluster_def  s    $..0D "$"4"4":":"<= (%K??8, !!%%))+ggl#EKKM2 (/!\	(6, (a((  K>IJJK  	(D&' ( (	(s   C$C(C%(D N)rE   rF   rG   rH   r.   rb   __nonzero__rg   rj   rr   rl   r   rI   r   r~   r   ru   r]   rU   rK   r/   r!   r   r      s_    <*6X$ +''<6 + +$$&/0:(r/   r   z(config.experimental.ClusterDeviceFiltersc                   (    e Zd ZdZd Zd Zd Zd Zy)ClusterDeviceFiltersaa  Represent a collection of device filters for the remote workers in cluster.

  NOTE: this is an experimental API and subject to changes.

  Set device filters for selective jobs and tasks. For each remote worker, the
  device filters are a list of strings. When any filters are present, the remote
  worker will ignore all devices which do not match any of its filters. Each
  filter can be partially specified, e.g. "/job:ps", "/job:worker/replica:3",
  etc. Note that a device is always visible to the worker it is located on.

  For example, to set the device filters for a parameter server cluster:

  ```python
  cdf = tf.config.experimental.ClusterDeviceFilters()
  for i in range(num_workers):
    cdf.set_device_filters('worker', i, ['/job:ps'])
  for i in range(num_ps):
    cdf.set_device_filters('ps', i, ['/job:worker'])

  tf.config.experimental_connect_to_cluster(cluster_def,
                                            cluster_device_filters=cdf)
  ```

  The device filters can be partically specified. For remote tasks that do not
  have device filters specified, all devices will be visible to them.
  c                      i | _         d | _        y r1   )_device_filters_cluster_device_filtersr:   s    r!   r.   zClusterDeviceFilters.__init__  s     D $(D r/   c                     t        d |D              sJ | j                  j                  |i        |D cg c]  }| c}| j                  |   |<   d| _        yc c}w )z6Set the device filters for given job name and task id.c              3   <   K   | ]  }t        |t                y wr1   )r   str).0dfs     r!   	<genexpr>z:ClusterDeviceFilters.set_device_filters.<locals>.<genexpr>  s     <rz"c"<s   N)allr   
setdefaultr   )r-   r   r   device_filtersr   s        r!   set_device_filtersz'ClusterDeviceFilters.set_device_filters  sZ    <^<<<<##Hb1?M1N"1ND":.#'D  2Os   	Ac                 j    | j                   r| j                   S | j                          | j                   S )z8Returns a serialized protobuf of cluster device filters.)r   _make_cluster_device_filtersr:   s    r!   _as_cluster_device_filtersz/ClusterDeviceFilters._as_cluster_device_filters  s/    ##)))%%''''r/   c                 F   t        j                         | _        t        | j                  j                               D ]  \  }}	 t        j                  |      }| j                  j                  j                         }||_        t        |j                               D ]J  \  }}|D ]@  }	 t        j                  |      }|j                  |   j                  j                  |       B L  y# t        $ r t        d|z        w xY w# t        $ r t        d|z        w xY w)zCreates `ClusterDeviceFilters` proto based on the `_device_filters`.

    Raises:
      TypeError: If `_device_filters` is not a dictionary mapping strings to
      a map of task indices and device filters.
    r   z)Device filter %r must be bytes or unicodeN)r   r   r   rm   r   rP   r   r   r   r   r   rZ   rY   r   append)r-   r   rY   jdfr[   task_device_filterstdfs          r!   r   z1ClusterDeviceFilters._make_cluster_device_filters%  s    $6#J#J#LD  "$"6"6"<"<">? 2%K??8, ((--113cch$*5;;=$9 2
 ! & 	2CO//#&C ))A,
%
%
,
,S
1	222  K>IJJK  OG#MNNOs   C-)D-DD 	N)rE   rF   rG   rH   r.   r   r   r   rK   r/   r!   r   r     s    6(((2r/   r   N)rH   tensorflow.core.protobufr   r   r   tensorflow.python.clientr   r(   tensorflow.python.frameworkr   tensorflow.python.utilr   r	    tensorflow.python.util.tf_exportr
   r"   deprecated_endpointsr%   r   r   rK   r/   r!   <module>r      s    : 0 7 : ? . ) . 6@F $7#HI!!!.1O O 2 JOd y( y(  y(x 56N2 N2 7N2r/   