Coverage for src/flag_gems/runtime/backend/_kunlunxin/ops/arange.py: 0%

40 statements  

« prev     ^ index     » next       coverage.py v7.6.9, created at 2026-03-22 16:54 +0800

1import logging 

2import math 

3 

4import torch 

5import triton 

6import triton.language as tl 

7 

8from flag_gems import runtime 

9from flag_gems.utils import libentry 

10from flag_gems.utils import triton_lang_extension as tle 

11 

12logger = logging.getLogger("flag_gems").getChild(__name__.lstrip(".")) 

13 

14 

15@libentry() 

16@triton.jit 

17def arange_func( 

18 y_ptr, 

19 start, 

20 end, 

21 step, 

22 size, 

23 BLOCK_SIZE: tl.constexpr, 

24 buffer_size_limit: tl.constexpr, 

25): 

26 pid = tle.program_id(0) 

27 y_ptr += pid * BLOCK_SIZE 

28 step_offset = pid * BLOCK_SIZE * step 

29 

30 cols = tl.arange(0, BLOCK_SIZE) 

31 arange_val = cols * step + step_offset + start 

32 mask = cols + pid * BLOCK_SIZE 

33 tl.store(y_ptr + cols, arange_val, mask=mask < size) 

34 

35 

36def arange_start( 

37 start, end, step=1, *, dtype=None, layout=None, device=None, pin_memory=None 

38): 

39 logger.debug("GEMS ARANGE") 

40 if dtype is torch.int64: 

41 sgn = (step > 0) - (step < 0) 

42 size = (end - start + step - sgn) // step 

43 else: 

44 size = math.ceil((end - start) / step) 

45 

46 cluster_num = 12 

47 tmp = torch.tensor([], dtype=dtype) 

48 BLOCK_SIZE = min( 

49 triton.next_power_of_2(triton.cdiv(size, cluster_num)), 

50 int(2048 * 64 / tmp.element_size()), 

51 ) 

52 grid = triton.cdiv(size, BLOCK_SIZE) 

53 

54 if dtype is None: 

55 dtype = torch.int64 

56 

57 if pin_memory is None: 

58 pin_memory = False 

59 

60 if device is None: 

61 device = ( 

62 runtime.device.name 

63 ) # Note(Zhengzekang): Torch default value is CPU, but triton is target to GPU. 

64 

65 result = torch.empty((size,), device=device, dtype=dtype, pin_memory=pin_memory) 

66 arange_func[grid,]( 

67 result, start, end, step, size, BLOCK_SIZE, buffer_size_limit=2048 

68 ) 

69 return result 

70 

71 

72def arange(end, *, dtype=None, layout=None, device=None, pin_memory=None): 

73 return arange_start( 

74 0, end, 1, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory 

75 )