o
    2h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   	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    r   `/var/www/html/chatgem/venv/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_apiTF_NewServer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   UnimplementedError	Exceptionr%   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%   TF_ServerStartr(   r*   r   r   r    r)      s   zServer.startc                 C   r3   )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(   r5   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$   r5   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%   TF_ServerTargetr(   r5   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+   r2   r)   r7   propertyr   r:   staticmethodr<   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   )intrD   r   r   r    rH   $      zMThe tasks for job %r must be a list or a dictionary from integers to strings.c                 S   rC   r   r   rE   rF   tr   r   r    rH   .      
c                 S   rC   r   r   rK   r   r   r    rH   6  rM   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   rX   	job_tasksjob_defr   r   r    r+     s<   



zClusterSpec.__init__c                 C   s
   t | jS r,   )boolrO   r5   r   r   r    __bool__>     
zClusterSpec.__bool__c                 C   s
   | j |kS r,   rO   r*   otherr   r   r    __eq__D  r^   zClusterSpec.__eq__c                 C   s
   | j |kS r,   r_   r`   r   r   r    __ne__G  r^   zClusterSpec.__ne__c                    s0   |     fddt D }dd| d S )Nc                    s$   g | ]}t |d  t  |  qS )z: )repr)rE   k
key_valuesr   r    
<listcomp>L  s    z(ClusterSpec.__repr__.<locals>.<listcomp>zClusterSpec({z, z}))as_dictsortedr7   )r*   string_itemsr   rf   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)rE   rF   rW   r*   r   r    rH   i  rJ   z'ClusterSpec.as_dict.<locals>.<dictcomp>)r   r   r   maxrZ   )r*   retr   r   rn   r    ri   Q  s   

zClusterSpec.as_dictc                 C   r8   )zFReturns a `tf.train.ClusterDef` protocol buffer based on this cluster.)rV   r5   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.
    )rQ   rO   keysr5   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)rO   KeyErrorr   r   r*   r   rW   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.
    rr   )rO   rs   r   rQ   rj   rq   rt   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.
    rr   zNo task with index %r in job %r)rO   rs   r   )r*   r   r   rW   r   r   r    rm     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.
    rr   c                 S   s   g | ]}d qS r,   r   )rE   _r   r   r    rh         z)ClusterSpec.job_tasks.<locals>.<listcomp>r
   )rO   rs   r   rangero   rq   rP   )r*   r   rW   rp   rF   rG   r   r   r    rZ     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   rU   rV   rj   rO   rP   r   as_bytesr   rW   addrY   rX   )r*   r   rX   r[   rF   rm   r   r   r    rT     s(   
zClusterSpec._make_cluster_defN)r=   r>   r?   r@   r+   r]   __nonzero__rb   rc   rl   ri   r   rA   r   ru   r   rm   rZ   rT   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_filtersr5   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rE   dfr   r   r    	<genexpr>  s    z:ClusterDeviceFilters.set_device_filters.<locals>.<genexpr>c                 S   s   g | ]}|qS r   r   r   r   r   r    rh     rw   z;ClusterDeviceFilters.set_device_filters.<locals>.<listcomp>N)allr~   
setdefaultr   )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.)r   _make_cluster_device_filtersr5   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.
    ry   z)Device filter %r must be bytes or unicodeN)r   r}   r   rj   r~   rP   r   rz   r   r   r{   rY   rX   r   append)r*   r   rX   jdfrF   task_device_filterstdfr   r   r    r   %  s(   
z1ClusterDeviceFilters._make_cluster_device_filtersN)r=   r>   r?   r@   r+   r   r   r   r   r   r   r    r}     s    	r}   N)r@   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}   r   r   r   r    <module>   s&   C  }