@@ -71,12 +71,23 @@ def _get_local_rank(device_dptr, _semantic=None, ret_dtype=tl.int32):
7171 return tl .tensor (result , ret_dtype )
7272
7373
74- # The number of devices in the world
74+ # Get the current world rank
75+ @tl .builtin
76+ def _get_world_rank (device_dptr , _semantic = None , ret_dtype = tl .int32 ):
77+ builder = _semantic .builder
78+ ret_ir_ty = ret_dtype .to_ir (builder )
79+ ptr = _parse_src_arg (builder , device_dptr , 1 )
80+ result = builder .get_world_rank (ret_ir_ty , ptr )
81+ return tl .tensor (result , ret_dtype )
82+
83+
84+ # The number of devices on the current node
7585@tl .builtin
7686def n_pes (dev_mem_ptr , _semantic = None , ret_dtype = tl .int32 ):
7787 builder = _semantic .builder
7888 ret_ir_ty = ret_dtype .to_ir (builder )
79- result = builder .get_n_pes (ret_ir_ty , dev_mem_ptr .handle )
89+ ptr = _parse_src_arg (builder , dev_mem_ptr , 1 )
90+ result = builder .get_n_pes (ret_ir_ty , ptr )
8091 return tl .tensor (result , ret_dtype )
8192
8293
@@ -639,13 +650,21 @@ def shard_id(
639650 Return current shard coordinate on the given launch mesh axis.
640651
641652 `axis` can be axis name (`str`) or axis index (`int`, supports negative).
653+ `device` returns the intra-node rank; `node` returns the inter-node rank.
642654 The returned value is a scalar int32 tensor.
643655 """
644656 mesh = tl ._unwrap_if_constexpr (mesh )
645657 axis = tl ._unwrap_if_constexpr (axis )
646658
647- if axis in ("device" , "node" ):
659+ if axis in ("device" , "node" ) and device_dptr is None :
660+ raise ValueError (f"device_dptr is required for axis { axis !r} " )
661+
662+ if axis == "device" :
648663 return _get_local_rank (device_dptr , _semantic = _semantic , ret_dtype = tl .int32 )
664+ if axis == "node" :
665+ world_rank = _get_world_rank (device_dptr , _semantic = _semantic , ret_dtype = tl .int32 )
666+ local_world_size = n_pes (device_dptr , _semantic = _semantic , ret_dtype = tl .int32 )
667+ return _semantic .floordiv (world_rank , local_world_size )
649668
650669 if not isinstance (mesh , device_mesh ):
651670 raise TypeError (f"mesh must be device_mesh, got { type (mesh ).__name__ } " )
0 commit comments