o
    ?eS                     @   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
d ZedddgdedG dd dZedG dd dZedG dd dZdS )z3A Python interface for creating TensorFlow servers.    )cluster_pb2)device_filters_pb2)tensorflow_server_pb2)pywrap_tf_session)errors)compat)deprecation)	tf_exportc                 C   s  t  }t| t jr0||  |dur||_|dur||_|dur$||_|dur.|j| |S zt| }W n t	yA   t	dw |du rWt
|jdkrS|jd }ntd|du ro||}t
|dkrk|d }ntd|du rud}t j| |||d}|dur|j| |S )	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.
  Nz^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   Z	ServerDef
isinstance	MergeFromr   r   r   Zdefault_session_configClusterSpec	TypeErrorlenjobs
ValueErrortask_indicesas_cluster_def)server_or_cluster_defr   r   r   config
server_defZcluster_specr    r   f/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/tensorflow/python/training/server_lib.py_make_server_def   sJ   


r   zdistribute.Serverztrain.Server)v1c                   @   sb   e Zd ZdZ					dddZdd Zdd	 Zd
d Zedd Z	edd Z
edddZdS )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.
  NTc                 C   s8   t |||||| _t| j | _|r|   dS dS )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_apiZTF_NewServerZSerializeToString_serverstart)selfr   r   r   r   r   r$   r   r   r   __init__k   s   #zServer.__init__c                 C   sR   t d urt j}nt}zt| j W n ty   Y n	 |y#   Y nw d | _d S N)r   ZUnimplementedError	Exceptionr"   ZTF_ServerStopr#   AttributeError)r%   	exceptionr   r   r   __del__   s   
zServer.__del__c                 C      t | j dS )zStarts this server.

    Raises:
      tf.errors.OpError: Or one of its subclasses if an error occurs while
        starting the TensorFlow server.
    N)r"   ZTF_ServerStartr#   r%   r   r   r   r$      s   zServer.startc                 C   r,   )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"   ZTF_ServerJoinr#   r-   r   r   r   join   s   	zServer.joinc                 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-   r   r   r   r      s   zServer.server_defc                 C   s   t | 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"   ZTF_ServerTargetr#   r-   r   r   r   target   s   zServer.targetc                 C   s   t ddgid| |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$   r   r   r   create_local_server   s
   
zServer.create_local_server)NNNNT)NT)__name__
__module____qualname____doc__r&   r+   r$   r.   propertyr   r0   staticmethodr2   r   r   r   r   r    ^   s"    
)	
	
r    ztrain.ClusterSpecc                   @   s   e Zd ZdZdd Zdd ZeZdd Zdd	 Zd
d Z	dd Z
dd Zedd Zdd Zdd Zdd Zdd Zdd ZdS )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                 C   s*  t |trBi | _| D ]/\}}t |ttfr!dd t|D }nt |tr0dd | D }ntd| || j|< q|   dS t |t	j
re|| _i | _| jjD ]}dd |j D | j|j< qRdS t |trt	
 | _| j|  i | _| jjD ]}dd |j D | j|j< q~dS td)	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.
    c                 S      i | ]\}}||qS r   r   .0itaskr   r   r   
<dictcomp>"  s    z(ClusterSpec.__init__.<locals>.<dictcomp>c                 S   s   i | ]	\}}t ||qS r   )intr:   r   r   r   r>   $      zMThe tasks for job %r must be a list or a dictionary from integers to strings.c                 S   r9   r   r   r;   r<   tr   r   r   r>   .      
c                 S   r9   r   r   rA   r   r   r   r>   6  rC   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	enumerater   _make_cluster_defr   
ClusterDef_cluster_defjobtasksnamer   r   r   )r%   r   r   rN   	job_tasksjob_defr   r   r   r&     s<   



zClusterSpec.__init__c                 C   s
   t | jS r'   )boolrE   r-   r   r   r   __bool__>     
zClusterSpec.__bool__c                 C   s
   | j |kS r'   rE   r%   otherr   r   r   __eq__D  rT   zClusterSpec.__eq__c                 C   s
   | j |kS r'   rU   rV   r   r   r   __ne__G  rT   zClusterSpec.__ne__c                    s0   |     fddt D }dd| d S )Nc                    s$   g | ]}t |d  t  |  qS )z: )repr)r;   k
key_valuesr   r   
<listcomp>L  s    z(ClusterSpec.__repr__.<locals>.<listcomp>zClusterSpec({z, z}))as_dictsortedr.   )r%   Zstring_itemsr   r\   r   __repr__J  s
   
zClusterSpec.__repr__c                    sp   i }j D ]0  }t|dkri | < qt|d t|kr) | < q fdd|D | < q|S )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
   c                    s   i | ]	}|  |qS r   )task_address)r;   r<   rM   r%   r   r   r>   i  r@   z'ClusterSpec.as_dict.<locals>.<dictcomp>)r   r   r   maxrP   )r%   retr   r   rc   r   r_   Q  s   

zClusterSpec.as_dictc                 C   r/   )zFReturns a `tf.train.ClusterDef` protocol buffer based on this cluster.)rL   r-   r   r   r   r   l  s   zClusterSpec.as_cluster_defc                 C   s   t | 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.
    )rG   rE   keysr-   r   r   r   r   p  s   zClusterSpec.jobsc                 C   s0   z
| j | }W t|S  ty   td| 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)rE   KeyErrorr   r   r%   r   rM   r   r   r   	num_tasksy  s   zClusterSpec.num_tasksc                 C   s:   z| j | }W n ty   td| w tt| S )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.
    rg   )rE   rh   r   rG   r`   rf   ri   r   r   r   r     s   zClusterSpec.task_indicesc                 C   sT   z| j | }W n ty   td| w z|| W S  ty)   td||f 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.
    rg   zNo task with index %r in job %r)rE   rh   r   )r%   r   r   rM   r   r   r   rb     s   
zClusterSpec.task_addressc                 C   sf   z| j | }W n ty   td| w dd tt| d D }| D ]\}}|||< q(|S )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.
    rg   c                 S   s   g | ]}d qS r'   r   )r;   _r   r   r   r^         z)ClusterSpec.job_tasks.<locals>.<listcomp>r
   )rE   rh   r   rangerd   rf   rF   )r%   r   rM   re   r<   r=   r   r   r   rP     s   
zClusterSpec.job_tasksc              
   C   s   t  | _t| j D ]G\}}zt|}W n ty$   td| w | jj	
 }||_t| D ]\}}zt|}W n tyL   td| w ||j|< q4qdS )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   rK   rL   r`   rE   rF   r   as_bytesr   rM   addrO   rN   )r%   r   rN   rQ   r<   rb   r   r   r   rJ     s(   
zClusterSpec._make_cluster_defN)r3   r4   r5   r6   r&   rS   __nonzero__rX   rY   ra   r_   r   r7   r   rj   r   rb   rP   rJ   r   r   r   r   r      s"    ,
r   z(config.experimental.ClusterDeviceFiltersc                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )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                 C   s   i | _ d | _d S r'   )_device_filters_cluster_device_filtersr-   r   r   r   r&     s   
zClusterDeviceFilters.__init__c                 C   sF   t dd |D sJ | j|i  dd |D | j| |< d| _dS )z6Set the device filters for given job name and task id.c                 s   s    | ]}t |tV  qd S r'   )r   strr;   Zdfr   r   r   	<genexpr>  s    z:ClusterDeviceFilters.set_device_filters.<locals>.<genexpr>c                 S   s   g | ]}|qS r   r   rv   r   r   r   r^     rl   z;ClusterDeviceFilters.set_device_filters.<locals>.<listcomp>N)allrs   
setdefaultrt   )r%   r   r   device_filtersr   r   r   set_device_filters  s   
z'ClusterDeviceFilters.set_device_filtersc                 C   s   | j r| j S |   | j S )z8Returns a serialized protobuf of cluster device filters.)rt   _make_cluster_device_filtersr-   r   r   r   _as_cluster_device_filters  s   z/ClusterDeviceFilters._as_cluster_device_filtersc                 C   s   t  | _t| j D ]P\}}zt|}W n ty$   td| w | jj	
 }||_t| D ]'\}}|D ] }zt|}W n tyP   td| w |j| j| q:q4qdS )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.
    rn   z)Device filter %r must be bytes or unicodeN)r   rr   rt   r`   rs   rF   r   ro   r   r   rp   rO   rN   rz   append)r%   r   rN   Zjdfr<   Ztask_device_filtersZtdfr   r   r   r|   %  s(   
z1ClusterDeviceFilters._make_cluster_device_filtersN)r3   r4   r5   r6   r&   r{   r}   r|   r   r   r   r   rr     s    	rr   N)r6   Ztensorflow.core.protobufr   r   r   Ztensorflow.python.clientr   r"   Ztensorflow.python.frameworkr   Ztensorflow.python.utilr   r   Z tensorflow.python.util.tf_exportr	   r   Zdeprecated_endpointsr    r   rr   r   r   r   r   <module>   s&   C  }