|
| 1 | +# Copyright 2026 FlagOS Contributors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +import math |
| 17 | + |
| 18 | +import torch |
| 19 | +import triton |
| 20 | +import triton.language as tl |
| 21 | + |
| 22 | +from flag_gems.ops.bucketize import bucketize as default_bucketize |
| 23 | +from flag_gems.runtime import torch_device_fn |
| 24 | +from flag_gems.utils import libentry |
| 25 | +from flag_gems.utils import triton_lang_extension as tle |
| 26 | + |
| 27 | +logger = logging.getLogger( |
| 28 | + f'flag_gems.runtime.backend._mthreads.ops.{__name__.split(".")[-1]}' |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +@libentry() |
| 33 | +@triton.autotune( |
| 34 | + configs=[ |
| 35 | + triton.Config({"BLOCK_SIZE": 512}, num_warps=4, num_stages=1), |
| 36 | + triton.Config({"BLOCK_SIZE": 1024}, num_warps=4, num_stages=1), |
| 37 | + triton.Config({"BLOCK_SIZE": 1024}, num_warps=8, num_stages=2), |
| 38 | + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8, num_stages=1), |
| 39 | + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8, num_stages=2), |
| 40 | + triton.Config({"BLOCK_SIZE": 4096}, num_warps=16, num_stages=1), |
| 41 | + ], |
| 42 | + key=["n_elements", "n_boundaries"], |
| 43 | +) |
| 44 | +@triton.jit |
| 45 | +def bucketize_kernel( |
| 46 | + inp_ptr, |
| 47 | + boundaries_ptr, |
| 48 | + out_ptr, |
| 49 | + n_elements, |
| 50 | + n_boundaries, |
| 51 | + right: tl.constexpr, |
| 52 | + N_BOUNDARY_ITERS: tl.constexpr, |
| 53 | + BLOCK_SIZE: tl.constexpr, |
| 54 | +): |
| 55 | + pid = tle.program_id(0) |
| 56 | + block_start = pid * BLOCK_SIZE |
| 57 | + offsets = block_start + tl.arange(0, BLOCK_SIZE) |
| 58 | + mask = offsets < n_elements |
| 59 | + |
| 60 | + inp_val = tl.load(inp_ptr + offsets, mask=mask, other=0) |
| 61 | + |
| 62 | + # Vectorized binary search: each lane keeps its own [lo, hi) window and |
| 63 | + # narrows it over a fixed iteration count (ceil(log2(n_boundaries + 1))). |
| 64 | + lo = tl.zeros([BLOCK_SIZE], dtype=tl.int32) |
| 65 | + hi = tl.full([BLOCK_SIZE], n_boundaries, dtype=tl.int32) |
| 66 | + |
| 67 | + for _ in range(N_BOUNDARY_ITERS): |
| 68 | + mid = tl.minimum((lo + hi) // 2, n_boundaries - 1) |
| 69 | + mid_val = tl.load(boundaries_ptr + mid) |
| 70 | + # right=True -> upper_bound (first boundary strictly greater than val) |
| 71 | + # right=False -> lower_bound (first boundary >= val) |
| 72 | + if right: |
| 73 | + cond = mid_val <= inp_val |
| 74 | + else: |
| 75 | + cond = mid_val < inp_val |
| 76 | + lo = tl.where(cond, mid + 1, lo) |
| 77 | + hi = tl.where(cond, hi, mid) |
| 78 | + |
| 79 | + tl.store(out_ptr + offsets, lo, mask=mask) |
| 80 | + |
| 81 | + |
| 82 | +# Moore Threads hardware does not support fp64 compute. The specialized kernel |
| 83 | +# targets the real floating types; other dtypes / empty boundaries / dtype |
| 84 | +# mismatches defer to the generic implementation for correctness. |
| 85 | +_SUPPORTED_DTYPES = {torch.float16, torch.bfloat16, torch.float32} |
| 86 | + |
| 87 | + |
| 88 | +def _use_triton_kernel(inp, boundaries): |
| 89 | + if inp.device.type != "musa": |
| 90 | + return False |
| 91 | + if inp.dtype not in _SUPPORTED_DTYPES: |
| 92 | + return False |
| 93 | + if boundaries.numel() == 0: |
| 94 | + return False |
| 95 | + # Binary search compares input against boundaries; keep them the same |
| 96 | + # element type so the search is exact and no implicit promotion is needed. |
| 97 | + if boundaries.dtype != inp.dtype: |
| 98 | + return False |
| 99 | + return True |
| 100 | + |
| 101 | + |
| 102 | +def bucketize(input, boundaries, *, out_int32=False, right=False): |
| 103 | + logger.debug("GEMS_MTHREADS BUCKETIZE") |
| 104 | + |
| 105 | + if not _use_triton_kernel(input, boundaries): |
| 106 | + return default_bucketize(input, boundaries, out_int32=out_int32, right=right) |
| 107 | + |
| 108 | + output_dtype = torch.int32 if out_int32 else torch.int64 |
| 109 | + |
| 110 | + n_elements = input.numel() |
| 111 | + n_boundaries = boundaries.numel() |
| 112 | + search_iterations = math.ceil(math.log2(n_boundaries + 1)) |
| 113 | + |
| 114 | + # Allocate a contiguous flat output so kernel stores land in the returned |
| 115 | + # tensor regardless of the input's memory layout (empty_like would inherit a |
| 116 | + # non-contiguous layout and flatten() could then copy). |
| 117 | + input_flat = input.contiguous().flatten() |
| 118 | + output_flat = torch.empty(n_elements, dtype=output_dtype, device=input.device) |
| 119 | + boundaries = boundaries.contiguous() |
| 120 | + |
| 121 | + grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) # noqa: E731 |
| 122 | + |
| 123 | + with torch_device_fn.device(input.device): |
| 124 | + bucketize_kernel[grid]( |
| 125 | + input_flat, |
| 126 | + boundaries, |
| 127 | + output_flat, |
| 128 | + n_elements, |
| 129 | + n_boundaries, |
| 130 | + right, |
| 131 | + search_iterations, |
| 132 | + ) |
| 133 | + |
| 134 | + return output_flat.reshape(input.shape) |
0 commit comments