
    Vh;?                         U d dl Z d dlZd dlmZmZ d dlZd dlmZ d dlm	Z	 d dl
mZmZ d dlmZ d dlmZ g dZdaed   ed	<   d
edefdZded
eddfdZ G d d      Z G d de      Zd
edej4                  fdZy)    N)OptionalUnion)Tensor)_get_device_handle
DeviceMesh)DTensorSpec)Shard)is_rng_supported_meshmanual_seedOffsetBasedRNGTracker_RNGStateTracker_rng_trackerdevice_meshreturnc                     t        | j                        }|rt        |d      ryt        j                  d| j                   d       y)aF  Checks if the current device of ``device_mesh`` supports DTensor's random APIs.
    Currently DTensor Random APIs only supports cuda/cuda-like devices. We suggest
    users call this API to test the availability before using our random APIs.

    Args:
        device_mesh (:class:`DeviceMesh`): The device mesh on which we check if the
            random ops APIs are supported.

    Returns:
        A bool value. True if ``device_mesh`` supports DTensor Random APIs; False otherwise.

    .. warning::
        Currently we only support correct RNG on cuda/cuda-like devices.
    set_rng_stateTz:DTensor random operators may not have complete support on  device meshF)r   device_typehasattrwarningswarn)r   device_handles     P/home/dcms/DCMS/lib/python3.12/site-packages/torch/distributed/tensor/_random.pyr
   r
      sJ     '{'>'>?M@ 	HI`I`Haamn	
     seedc                     t        |      s$t        j                  d|j                   d       yt        st        |d      a|j                         t        j                  |        yt        d      )ay  Sets the seed for generating random numbers for the calling rank.

    Args:
        seed (int): The desired seed.
        device_mesh (:class:`DeviceMesh`): The device mesh to set the seed. It is
            required that the ``device_mesh`` include the calling rank. This is
            to ensure that the SPMD region maintains a synchronous RNG state, which
            means no ranks should be initialized with values other than ``seed``.

    Returns:
        None

    .. warning::
        :func:`manual_seed` does not check the ``seed`` value correctness. Users must
        ensure on their own that the value passed in is the desired ``seed`` for ranks
        within ``device_mesh``.
        If ``device_mesh`` is a sub-mesh and the calling rank is not a part of it,
        ``manual_seed`` will throw an error.
        Current implementation only supports a GPU device mesh.
    z7DTensor manual_seed() may not have complete support on r   NF)run_state_synczmanual_seed requires the current rank to be a part of the device mesh otherwise DTensor RNG state on the rank will not be initialized and the behavior of DTensor random ops is undefined.)	r
   r   r   r   r   r   get_coordinate_manual_seedRuntimeError)r   r   s     r   r   r   2   sw    * !-))*,8	
 	
 ,[O !!#/!!$'?
 	
r   c                       e Zd ZdZdej
                  fdZedee	e
f   fd       Zedefd       Zej                  dd       Zdefd	Zd
e	defdZd
e	deddfdZdefdZdeddfdZy)r   a  
    _RNGStateTracker stores Random Number Generator (RNG) state (a ByteTensor object)
    in a dict, mapping from a corresponding tag to each state tensor. It also provides
    a set of convenient utility methods to help access/modify the state tensors. The most
    important interface is _distribute_region which will be used when DTensor executes
    a random op (an operator that calls RNG).
    devicec                     || _         t        | j                   j                        | _        | j                  r| j                  j	                         s/t        | j                  j                   d|j                   d      i | _        d| _	        y )Nz( instantiation requires the presence of z device but couldn't find.T)
_devicer   type_device_handleis_availabler    	__class____name___states_use_distribute_region)selfr"   s     r   __init__z_RNGStateTracker.__init__h   s|    01B1BC##(;(;(H(H(J>>**++S;;-9; 
 +-&*#r   r   c                     | j                   S N)r*   r,   s    r   
rng_statesz_RNGStateTracker.rng_statest   s    ||r   c                     | j                   S r/   r+   r0   s    r   distribute_region_enabledz*_RNGStateTracker.distribute_region_enabledx   s    ***r   Nc                     || _         y r/   r3   )r,   values     r   r4   z*_RNGStateTracker.distribute_region_enabled|   s
    &+#r   c                     || j                   v S r/   )r1   )r,   names     r   rng_state_is_syncz"_RNGStateTracker.rng_state_is_sync   s    t&&r   r8   c                     || j                   vr$t        | j                  j                   d|       | j                   |   dd j	                  t
        j                        }t        |j                               S )N  does not have random state for r      dtype	r1   r    r(   r)   viewtorchint64intitem)r,   r8   seed_tensors      r   get_seedz_RNGStateTracker.get_seed   sr    t&>>**++KD6R  t,a277ekk7J;##%&&r   r   c                 \   t        j                  |gt         j                  d      j                  t         j                        }t        j                  dgt         j                  d      j                  t         j                        }t        j
                  ||g      | j                  |<   y )Ncpur>   r"   r   )rA   tensoruint64r@   uint8catr1   )r,   r8   r   rE   offset_tensors        r   set_seedz_RNGStateTracker.set_seed   sv    llD6eLQQKK
 aSUKPPKK
 !&		;*F Gr   specc                      y r/    )r,   rP   s     r   _distribute_regionz#_RNGStateTracker._distribute_region       r   parallel_seedc                      y r/   rR   r,   rU   s     r   r   z_RNGStateTracker._manual_seed   rT   r   )r   N)r)   
__module____qualname____doc__rA   r"   r-   propertydictstrr   r1   boolr4   setterr9   rC   rF   rO   r   rS   r   rR   r   r   r   r   _   s    
+u|| 
+ Df-   +4 + + %%, &,' ''S 'S 'HS H H H{ # $ r   c                        e Zd ZdZ	 ddedef fdZdeddfdZe	j                  d	efd
       ZdedefdZdededdfdZd	eddfdZd	ededdfdZdee   dee   defdZ xZS )r   a  
    This subclass of ``_RNGStateTracker`` defines the default policy of how RNG states
    should be shared and synchronized among all ranks to respect the semantics of DTensor
    random operators.

    note: _RNGStateTracker only supports cuda/cuda-like device.
    r   r   c                    t         |   t        |             | j                  J | j                  j
                  dk(  r9t        | j                  j                   d| j                  j
                   d      | j                  j                         j                  | j                        }|rt        j                  |d       |j                  d      | j                  d<   y )N)r   rH   zG instantiation requires the presence of CUDA/CUDA-like/XPU device. Got z	 instead.r   parallel-rng)superr-   _resolve_devicer&   r$   r%   r    r(   r)   get_rng_statetodist	broadcastr1   )r,   r   r   	rng_stater(   s       r   r-   zOffsetBasedRNGTracker.__init__   s    
 	[AB""...<<%>>**+ ,226,,2C2C1DIO 
 ''557::4<<H	NN9a(*3,,u*='r   rU   r   Nc                 (    | j                  d|       y )Nrb   )rO   rW   s     r   r   z"OffsetBasedRNGTracker._manual_seed   s    nm4r   rP   c              #     K   | j                  d      st        d      | j                  r| j                  d      }| j	                  |       t
        j                  j                  | j                  g| j                  j                        5  | j                  J | j                  j                  | j                  d          	 d  | j                  ||       	 d d d        y d  y # | j                  ||       w xY w# 1 sw Y   y xY ww)Nrb   zlOffsetBasedRNGTracker requires the random state to be synchronized before entering into a distribute region!)devicesr   )r9   r    r4   
get_offset_set_pre_op_offsetrA   randomfork_rngr$   r%   r&   r   r1   _set_post_op_offset)r,   rP   
old_offsets      r   rS   z(OffsetBasedRNGTracker._distribute_region   s      %%n5< 
 ))8J##D)&&DLL4E4E '  	? **666##11$//.2QR? ,,T:>	? 	?  ,,T:>	? 	?s6   BD7DC*	DD*C>>DD
Dr8   c                     || j                   vr$t        | j                  j                   d|       | j                   |   dd  j	                  t
        j                        }t        |j                               S )Nr;   r<   r=   r?   )r,   r8   rN   s      r   rm   z OffsetBasedRNGTracker.get_offset   sr    t&>>**++KD6R  .388u{{8K=%%'((r   offsetc                 \   || j                   vr$t        | j                  j                   d|       | j                   |   dd }t	        j
                  |gt        j                  d      j                  t        j                        }t	        j                  ||g      | j                   |<   y )Nr;   r   r<   rH   rI   )
r1   r    r(   r)   rA   rJ   rK   r@   rL   rM   )r,   r8   rt   rE   rN   s        r   
set_offsetz OffsetBasedRNGTracker.set_offset   s    t&>>**++KD6R  t,a2fXU\\%PUUKK
 !&		;*F Gr   c                 &   |j                   }|j                  }dg|j                  z  }t        |j                        D ]Y  \  }}t        |t              s|j                  }||   dk(  r|g||<   2||   }t        |t              sJ |j                  |       [ |j                         }	|	J |j                   }
g }g }|D ]}  }d}d}t        |t              rE|D cg c]  }|	|   	 }}|D cg c]  }|
|   	 }}t        ||      D ]  \  }}||z  |z   }||z  } |j                  |       |j                  |        | j                  ||      }t        |      }t        |j                        D ]Q  \  }}t        |t              s|j                  |      }|j                  }|j                  ||   |dd      d   ||<   S ddlm}  ||      }| j#                  d      }||z  d	z   d
z  d
z  }| j%                  d||z          yc c}w c c}w )a
  Set the starting RNG offset for current device's local shard before actual
        op execution. The pre_op_offset value should start from the current RNG offset
        and increment by the size of local shard until it reaches the size of the whole
        DTensor. For different ranks that hold the same DTensor shard, their pre_op_offset
        will be the same.

        Args:
            spec (:class:`DTensorSpec`): the spec of the DTensor object on which
                we prepare the offset for running random ops.

        Returns:
            None

        .. warning::
            Note that, current implementation does not consider DTensor's continguity.

        Example:
            take a DTensor of shape [8, 16] as an example. Assume that the DTensor
            is placed on a device mesh with placements ([Shard(1), Replicate(), Shard(0)]),
            and the mesh is:
                [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
            ``spec.mesh.get_coordinate()`` provides the coordinate of the current rank
            in the mesh. For example, the coordinate of rank 5 is (1, 0, 1).

            Another concept to introduce besides rank coordinate is shard coordinate.
            Each rank holds a local shard of the DTensor. In the example, the DTensor
            is partitioned into 4 [4, 8] shards. The first shard has 2 replicas and
            rank 0 (coord (0, 0, 0)) and rank 2 (coord (0, 1, 0)) have 1 replica each.
            That being said, the local shard on rank 0 and rank 2 correspond to the same
            shard of the DTensor. To denote each DTensor shard, we use a shard coordinate
            (in the example, it will be a tuple (i, j) where shard (i, j) has the slice
            DTensor[4 * i : 4 * (i + 1), 8 * j : 8 * (j + 1)], 0 <= i < 2, 0 <= j < 2).

            Once we have rank coordinate and shard coordinate, we can calculate on each rank
            what shard of the DTensor the rank holds, with the help of dim_map. The dim_map
            of the above DTensor is [2, 0] so the shard coordinate of a rank with rank coord
            (x, y, z) is simply (z, x) by taking(rank_coord[dim_map[0]],rank_coord[dim_map[1]]).
            Following this calculation,
            rank 0 and rank 2 holds the shard of coord (0, 0);
            rank 1 and rank 3 holds the shard of coord (0, 1);
            rank 4 and rank 6 holds the shard of coord (1, 0);
            rank 5 and rank 7 holds the shard of coord (1, 1);

            The last value to calculate before obtaining the starting offset is the shard linear index.
            The starting offset for each rank will be its shard_linear_index * local_tensor_numel.
        Nr      F)return_offsetprodrb         )shapemeshndim	enumerate
placements
isinstancer	   dimlistappendr   zip_calc_shard_linear_idxsize_local_shard_size_on_dim#torch.distributed.tensor._ops.utilsr|   rm   rv   )r,   rP   dtensor_shaper   dim_mapi	placement	shard_dimmesh_dim_listmesh_coordinate	mesh_sizeshard_idx_by_dimtotal_num_shards_by_dimmesh_dim	shard_idxtotal_num_shardsd
rank_coord
num_shardsidxr   shard_linear_idxlocal_size_on_rank_0mesh_dim_sizer|   
local_sizecurrent_offsetoffset_incrs                               r   rn   z(OffsetBasedRNGTracker._set_pre_op_offset   sa   ^ 

yy 13tdii/?%doo6 	,LAy)U+%MM	9%+*+GI&$+I$6M%mT:::!((+	, --/***JJ	"$ 	=HI (D):BCQoa0C
C4<=qil=
=!$Z!< -IC )D 03 6I$,$- ##I.#**+;<	=   665

  $M2'8 		NC)U+ $		#%MM	2;2T2T!),!"'	 3U 3
 3$Y/			 	=./
 8 (*4q8Q>B(DEM D=s   H	-Hrr   c                 x    |j                   }ddlm}  ||      }|dz   dz  dz  }| j                  d||z          y)a  Sets the RNG to a synchronized state after running the local random op. Every
        rank should set its RNG offset to `old_offset + DTensor.numel()` where old_offset is
        the offset before calling `set_pre_op_offset` i.e. the offset before running DTensor
        random ops.

        Args:
            spec (:class:`DTensorSpec`): the spec of the DTensor object on which
                we post-process the offset for running random ops.

        Returns:
            None
        r   r{   r}   r~   rb   N)r   r   r|   rv   )r,   rP   rr   r   r|   numels         r   rq   z)OffsetBasedRNGTracker._set_post_op_offset_  sB     

<]# q 1$
U(:;r   shard_coord
shard_sizec                 t    d}d}t        t        |      t        |            D ]  \  }}|||z  z  }||z  } |S )Nr   ry   )r   reversed)r,   r   r   r   shard_coord_strider   r   s          r   r   z,OffsetBasedRNGTracker._calc_shard_linear_idxv  sX     Xk2HZ4HI 	'IC&8 88$&	'  r   )T)r)   rX   rY   rZ   r   r^   r-   rC   r   
contextlibcontextmanagerr   rS   r]   rm   rv   rn   rq   r   r   __classcell__)r(   s   @r   r   r      s      $>> >*5# 5$ 5 {  0)s )s )
Hs 
HC 
HD 
HrF{ rFt rFh< < < <.
 9
 26s)
 	
 r   r   c                     | j                   }t        |      }|J | j                         |j                         z  }t	        j
                  | d|d      S )N:r   )r   r   get_rankdevice_countrA   r"   )r   r   r   
device_idxs       r   rd   rd     s[    ))K&{3M$$$%%'-*D*D*FFJ<<;-qA788r   )r   r   typingr   r   rA   torch.distributeddistributedrg   r   torch.distributed.device_meshr   r   &torch.distributed.tensor._dtensor_specr   (torch.distributed.tensor.placement_typesr	   __all__r   __annotations__r^   r
   rC   r   r   r   r"   rd   rR   r   r   <module>r      s      "     H > : .2h)* 1z d 4*
c *

 *
t *
Z: :zd , d N9 9 9r   