
    AVhG              
       
   d Z ddlZddlZddlmZmZmZ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a ej0                         Z edg       dedef   deej4                     defd       Z edg        ej8                  dd      ej:                  dej<                  fd                     Z edg       ej:                  dej<                  fd              Z  edg       deej<                     fd       Z! edg       de"fd       Z# edg       de$fd       Z% edg       	 d?d edej4                  d!eej4                     dejL                  fd"       Z' ed#g       d$ee   dej4                  defd%       Z( ed&g       d edee   fd'       Z) ed(g       d ejL                  dej4                  fd)       Z* ed*g       d ejL                  dej4                  ddfd+       Z+ ed,g       	 d?d ejL                  dej4                  d-ee"   dejL                  fd.       Z, ed/g       	 d?d ejL                  d0ejL                  d-ee"   dejL                  fd1       Z- ed2g       d3e$ddfd4       Z.de	j^                  fd5Z0d@d6Z1 ejd                  d7      d8        Z3 ejd                  d9      d:        Z4 ejd                  d;      d<        Z5 ejd                  d=      d>        Z6y)AzCore DTensor Python API.    N)AnyCallableOptionalSequence)dtensor_device)gen_dtensor_ops)layout)context)opstensor)deprecation)	tf_exportz%experimental.dtensor.call_with_layout)v1fn.r	   returnc                 :   |pt        j                         rJt        |j                        5  t	               j                  |      5   | |i |cddd       cddd       S t         | |i ||      S  | |i |S # 1 sw Y   nxY w	 ddd       # 1 sw Y   'xY w)aE  Calls a function in the DTensor device scope if `layout` is not None.

  If `layout` is not None, `fn` consumes DTensor(s) as input and produces a
  DTensor as output; a DTensor is a tf.Tensor with layout-related attributes.

  If `layout` is None, `fn` consumes and produces regular tf.Tensors.

  Args:
    fn: A supported TF API function such as tf.zeros.
    layout: Optional, the layout of the output DTensor.
    *args:  Arguments given to `fn`.
    **kwargs: Keyword arguments given to `fn`.

  Returns:
    The return value of `fn` transformed to a DTensor if requested.
  N)r
   executing_eagerlydefault_meshmesh_dtensor_device_default_layoutrelayout)r   r	   argskwargss       M/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/dtensor/python/api.pycall_with_layoutr   %   s    (   "$ %..v6 	%T$V$	% 	%% % b$)&)622	T	V			% 	% 	%% % %s#   BA;	B;B	 BBzexperimental.dtensor.run_onz)Use `dtensor.default_mesh` scope instead.r   c              #   T   K   t        |       5  d ddd       y# 1 sw Y   yxY ww)a,  Runs enclosed functions in the DTensor device scope.

  This function returns a scope. All the ops and tf.functions in this scope will
  run on the DTensor device using the mesh provided.
  This is useful for wrapping any tf.function that doesn't take a DTensor as
  input but would like to produce DTensor as result. The scope will also make
  sure all small constants be replicated as DTensor.

  Args:
    mesh: A Mesh instance to extract a default mesh from.

  Yields:
    A context in which all ops and tf.functions will run on the DTensor device.
  N)r   r   s    r   run_onr    C   s'     $ D 
	
 
 
s   (	(%(z!experimental.dtensor.default_meshc              #   6  K   t        | t        j                        st        dt	        |              t               j                  |       5  t        j                  t                     5  d ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY ww)aY  Sets the default DTensor device mesh to use for enclosed functions.

  This function returns a scope. All the ops and tf.functions in this scope will
  default to this DTensor mesh if a mesh cannot be inferred from any of the
  inputs
  This is useful for wrapping any tf.function that doesn't take a DTensor as
  input but would like to produce DTensor as result. The scope will also make
  sure all small constants are replicated as DTensors.

  Args:
    mesh: A Mesh instance to extract a default mesh from.

  Yields:
    A context in which all ops and tf.functions will run on the given mesh.
  z Expect `mesh` to be `Mesh`, got N)

isinstance
layout_libMesh
ValueErrortyper   _experimental_default_meshr   devicedevice_namer   s    r   r   r   Y   s}     $ 
D*//	*
7T
|D
EE33D9 	KM	"    s6   ABB+B0B8	BB
	BBBz%experimental.dtensor.get_default_meshc                  0    t         yt         j                  S )zReturn the default mesh under the current dtensor device context.

  In the case that dtensor device system is not initialized, this function
  will return None.

  Returns:
    The current default mesh for the dtensor device context.
  N)_dtensor_singleton_current_default_mesh     r   get_default_meshr/   s   s     333r.   z experimental.dtensor.device_namec                  *    t               j                  S )zReturns the singleton DTensor device's name.

  This function can be used in the following way:

  ```python
  import tensorflow as tf

  with tf.device(dtensor.device_name()):
    # ...
  ```
  )r   namer-   r.   r   r)   r)      s     
			r.   zexperimental.dtensor.is_dtensorc                 4    t               j                  |       S )a6  Check whether the input tensor is a DTensor.

  In Python, a DTensor has the same type as a `tf.Tensor`. This method will
  let you check and handle the tensor differently if a tf.Tensor is a DTensor.

  Args:
    tensor: an object to be checked.

  Returns:
    bool, True if the given tensor is a DTensor.
  )r   
is_dtensorr   s    r   r3   r3      s     
		%	%f	--r.   z!experimental.dtensor.copy_to_meshr   source_layoutc                     ~t        | |      S )a:  Copies a tf.Tensor onto the DTensor device with the given layout.

  Copies a regular tf.Tensor onto the DTensor device. Use the mesh attached to
  `layout` as target mesh. This method currently only supports replicated
  layouts, or one-to-one copies for sharded layouts.

  Args:
    tensor: A regular tf.Tensor to be copied as a DTensor.
    layout: Target layout (and mesh) for the result DTensor.
    source_layout: Source layout of the tensor before copy. This argument
      is deprecated.

  Returns:
    A DTensor on the DTensor device with the given layout.
  )r   )r   r	   r4   s      r   copy_to_meshr6      s    ( 	&&	!!r.   zexperimental.dtensor.packtensorsc                 6    t               j                  | |      S )a  Packs `tf.Tensor` components into a DTensor.

  Packing and unpacking are inverse operations:

  ```
  * unpack(pack(tensors)) == tensors
  * pack(unpack(dtensor)) == dtensor
  ```

  1. For any DTensor on the mesh, `unpack` returns the raw components placed on
     each underlying device.
  2. Packing these raw components in the same order using `pack` returns a
     DTensor which should be identical to the original DTensor--both the content
     value and the layout.

  **Shape, Rank, and Scalars**: The rank of the DTensor is the same as the
  rank of its raw components, i.e., rank is preserved.  This leads to a
  consistent interpretation for packing scalar values into a DTensor. The only
  valid layout for a scalar value is fully replicated, and the individual
  components must be identical scalars.

  Each input `tensors[i]` will be copied to `layout.mesh.local_device[i]`
  if not already on the local device. Non-local components should not be passed
  to `pack`; use `copy_to_mesh` and `relayout` to place tensors on all global
  devices on a mesh.

  It is the caller's responsibility to ensure that the underlying values
  for `pack` adhere to the specified layout, and that only as many values are
  specified as there are local devices. Pack does not move data between clients.
  See examples below for more detail about layouts.

  For example, assume we have a mesh `[X(2), Y(3)]`, which has in total 6
  underlying devices. Futuremore, assume that the device location mapping is
  the following:

  ```
  device_ID  |  location X, Y
          0     0, 0
          1     0, 1
          2     0, 2
          3     1, 0
          4     1, 1
          5     1, 2
  ```

  1. For 1-D vector DTensor with shape `[128]` with layout `[mesh.X]` and value
     as `range(128)`, the raw components will have shape `[64]` each, and the
     raw components will be:

     ```
     device_ID  |  raw component
             0     range(0, 64)
             1     range(0, 64)
             2     range(0, 64)
             3     range(64, 128)
             4     range(64, 128)
             5     range(64, 128)
     ```

     This also means for a 1-D DTensor with shape `[2]` and layout `[mesh.X]`,
     the raw components have shape `[1]` rather than the shape for scalar values
     `[]`.

  2. For 2-D vector DTensor with shape `[2, 3]` with layout `[mesh.X, mesh.Y]`
     and value as `range(6)`, this is basically a fully-sharded DTensor.

     From global view, the content looks like
     ```
     [
       [0.0, 1.0, 2.0],
       [3.0, 4.0, 5.0],
     ]
     ```

     The raw components will have shape `[1, 1]` each, and have the following
     content:

     ```
     device_ID  |  raw component
             0     [[0.0]]
             1     [[1.0]]
             2     [[2.0]]
             3     [[3.0]]
             4     [[4.0]]
             5     [[5.0]]
     ```

  3. For a scalar value `123.0` DTensor, it can only have one legitimate layout
     `[]` (no dimension, but fully replicated).

     The raw components will have shape `[]` each, and have the following
     content:

     ```
     device_ID  |  raw component
             0     123.0
             1     123.0
             2     123.0
             3     123.0
             4     123.0
             5     123.0
     ```

     Again, caller of `pack` is expected to provide 6 identical value raw
     components with scalar shapes.

  4. For 3-D vector DTensor with shape `[2, 2, 3]` with layout
     `[X, unsharded, unsharded]` and value as `range(12)`,

     From global view, the content looks like:
     ```
     [
       [
         [0.0, 1.0, 2.0],
         [3.0, 4.0, 5.0],
       ],
       [
         [6.0, 7.0, 8.0],
         [9.0, 10., 11.],
       ],
     ]
     ```

     The raw components will have shape `[1, 2, 3]` each, and have the following
     content:

     ```
     device_ID  |  raw component
             0     range(6).reshape([1, 2, 3])
             1     range(6).reshape([1, 2, 3])
             2     range(6).reshape([1, 2, 3])
             3     range(6, 12).reshape([1, 2, 3])
             4     range(6, 12).reshape([1, 2, 3])
             5     range(6, 12).reshape([1, 2, 3])
     ```

  Args:
    tensors: The list of local tensor components to pack into a DTensor.
    layout: The layout of the DTensor to be created.

  Returns:
    A DTensor created from the individual component tensors.

  Raises:
    RuntimeError: When `pack` is not called eagerly.
  )r   pack)r7   r	   s     r   r9   r9      s    h 
				00r.   zexperimental.dtensor.unpackc                 4    t               j                  |       S )aX  Unpacks a DTensor into `tf.Tensor` components.

  Packing and unpacking are inverse operations:

  ```
  * unpack(pack(tensors)) == tensors
  * pack(unpack(dtensor)) == dtensor
  ```

  1. For any DTensor on the mesh, `unpack` returns the raw components placed on
     each underlying device.
  2. Packing these raw components in the same order using `pack` returns a
     DTensor which should be identical to the original DTensor--both the content
     value and the layout.

  See the documentation for `pack` for more information about how packing and
  unpacking works.

  Args:
    tensor: The DTensor to unpack.

  Returns:
    The individual component tensors of the DTensor. This will include only the
    client-local components, i.e. the components placed on the local devices.

  Raises:
    RuntimeError: When `unpack` is not called eagerly.
  )r   unpackr   s    r   r;   r;   V  s    < 
		!	!&	))r.   z!experimental.dtensor.fetch_layoutc                 4    t               j                  |       S )zFetches the layout of a DTensor.

  Args:
    tensor: The DTensor whose layout is to be fetched.

  Returns:
    The `Layout` of this DTensor.

  Raises:
    RuntimeError: When not called eagerly.
  )r   fetch_layoutr   s    r   r=   r=   {  s     
		'	'	//r.   z!experimental.dtensor.check_layoutc                 ~    t        |       |k7  r/t        dt        t        |             z   dz   t        |      z         y)zAsserts that the layout of the DTensor is `layout`.

  Args:
    tensor: A DTensor whose layout is to be checked.
    layout: The `Layout` to compare against.

  Raises:
    ValueError: If the layout of `tensor` does not match the supplied `layout`.
  zLayout of tensor: z!, did not match expected layout: N)r=   r%   str)r   r	   s     r   check_layoutr@     sL     &V#
)CV0D,EE89;>v;G H H $r.   zexperimental.dtensor.relayoutr1   c                     |j                         }t        |j                        5  t        j                  | ||      cddd       S # 1 sw Y   yxY w)a.  Changes the layout of `tensor`.

  Changes the layout of `tensor` to `layout`. This is used to fine-tune the
  behavior of ops following/connected to `tensor`, such as choosing one SPMD
  expansion pattern over another. This works by forward propagating `layout`
  to connected TensorFlow computation graphs during layout propagation.

  Currently, only converting layouts from replicated to sharded or sharded to
  replicated per mesh dimension is supported. That is, "x, y" -> "unsharded, y"
  is supported, while "x, y" -> "z, y" is not supported.

  We also support a special "match" sharding spec, which instructs the relayout
  to act as an identity operation with respect to any sharding on these
  mesh dimensions.

  Relayout is internally lowered to a set of Split and/or AllToAll ops. When
  tensor layouts are converted from replicated to sharded, the cost is
  comparatively low because we only insert Split ops and no cross-device
  communication is needed. However, when tensor layouts are converted from
  sharded to replicated, cross-device communication may occur, causing potential
  performance impact.

  Args:
    tensor: A DTensor to specify a new layout for.
    layout: A Layout object specifying a new sharding spec.
    name: name of the Op.

  Returns:
    A DTensor output from the Relayout op.
  )r1   N)	to_stringr   r   r   r   )r   r	   r1   
layout_strs       r   r   r     sJ    H !*FKK  C##FJTBC C Cs   AAz"experimental.dtensor.relayout_likelayout_tensorc                 2    t        j                  | ||      S )au  Changes the layout of `tensor` to the same as `layout_tensor`.

  `relayout_like` is often used inside a `tf.function`, to ensure a tensor is
  placed to the same mesh and with the same layout as another tensor.

  The backward gradient of a `relayout` is a `relayout_like` operation, to
  ensure the backward tensor has the same layout as the forward input tensor:

  ```
  @ops.RegisterGradient("Relayout")
  def _relayout_gradient(op, grad):
    return relayout_like(grad, layout_input=op.inputs[0])
  ```

  Here is another illustrative example:

  ```
  @tf.function
  def func(x):
    z = tf.ones(x.shape)
    z = dtensor.relayout_like(z, x)
    return x + z

  with dtensor.default_mesh(cpu_mesh):
    x = tf.ones((4, 4))

  with dtensor.default_mesh(gpu_mesh):
    y = func(x)

  # y would be on the cpu mesh, following the mesh of x.
  ```

  Args:
    tensor: A DTensor to specify a new layout for.
    layout_tensor: A Tensor object whose layout will be used for the layout of
      result. The shape and type of layout_tensor are irrelevant.
    name: name of the Op.

  Returns:
    A DTensor output from the RelayoutLike op.
  )inputlayout_inputr1   )r   relayout_like)r   rD   r1   s      r   rH   rH     s    ` 
	&	&T
 r.   z*experimental.dtensor._reset_dtensor_deviceis_asyncc                 6    t        j                  g |       }|ay)zResets the Eager execution device for DTensor.

  This function is only intended for testing and diagnostics.

  Args:
    is_async: If True, the device uses async execution.
  )meshesrI   N)r   DTensorDevicer+   )rI   r(   s     r   reset_dtensor_devicerM     s     ''rHE&r.   c                  j    t         5  t        t        d       t        cd d d        S # 1 sw Y   y xY w)NT)rI   )_dtensor_singleton_lockr+   rM   r-   r.   r   r   r     s+     !D)  s   )2c                  r    t         5  t        t        j                          d ad d d        y # 1 sw Y   y xY wN)rO   r+   clear_tpu_core_idsr-   r.   r   _resetrS     s2     %++-  s   -6Relayoutc                 N    t        j                  || j                  d         }|S Nr   )rG   r   rH   inputsopgrads     r   _relayout_gradientr\     s!    		&	&t"))A,	G$	+r.   RelayoutLikec                 R    t        j                  || j                  d         }|d fS rV   rW   rY   s     r   _relayout_grad_gradientr_      s*     
	&	&t"))A,	G$ 
tr.   
CopyToMeshc                 N    t        j                  || j                  d         }|S Nr   )forward_inputr   copy_to_mesh_gradrX   rY   s     r   _copy_to_mesh_gradientrf   )  s'    		*	*
IIaL
$ 
+r.   CopyToMeshGradc                 R    t        j                  || j                  d         }|d fS rb   rd   rY   s     r   _copy_to_mesh_grad_gradientri   2  s,    		*	*
IIaL
$ 
tr.   rQ   )r   N)7__doc__
contextlib	threadingtypingr   r   r   r   tensorflow.dtensor.pythonr   r   r	   r#   tensorflow.python.eagerr
   tensorflow.python.frameworkr   r   
tensor_libtensorflow.python.utilr    tensorflow.python.util.tf_exportr   r+   LockrO   Layoutr   
deprecatedcontextmanagerr$   r    r   r/   r?   r)   boolr3   Tensorr6   r9   r;   r=   r@   r   rH   rM   rL   r   rS   RegisterGradientr\   r_   rf   ri   r-   r.   r   <module>r{      sO      4 4 4 5 : + + < . 6 ()..*  2r:#"%#& ' 089J9J0K), ;: (R0IJ
 
  K 1
& .26z   70 2r:4(:??3 4 ;4 -"5 S   6  ,4.$ . 5.& .26 26""" J--." ;E:K:K" 7". &2.S1(3- S1):): S1s S1 /S1l (R0*3 *8C= * 1*H .260** 0z/@/@ 0 70 .26H** HJ4E4E H$ H 7H *r2 %C%C%C 3-%C 	%C 3%CP /B7 11$$1 3-1 	1 81h 7B?
4 
D 
 @
55  j! "
 n% & l# $ &' (r.   