Skip to content

Commit 0409f9a

Browse files
split out varlen batch search into utils (Dao-AILab#2556)
* split out varlen batch search into utils * more descriptive name
1 parent 9cee95f commit 0409f9a

2 files changed

Lines changed: 24 additions & 11 deletions

File tree

flash_attn/cute/compute_block_sparsity.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,12 @@
1818
get_aux_tensor_metadata,
1919
to_cute_aux_tensor,
2020
)
21-
from flash_attn.cute.utils import hash_callable, scalar_to_ssa, ssa_to_scalar
21+
from flash_attn.cute.utils import (
22+
hash_callable,
23+
scalar_to_ssa,
24+
ssa_to_scalar,
25+
get_batch_from_cu_tensor,
26+
)
2227
from flash_attn.cute.seqlen_info import SeqlenInfoQK
2328

2429

@@ -161,16 +166,7 @@ class SharedStorage:
161166
m_block, head_idx, batch_idx = cute.arch.block_idx()
162167
else:
163168
global_m_block, head_idx, _ = cute.arch.block_idx()
164-
# Binary search over cu_total_m_blocks to find batch_idx
165-
lo = Int32(0)
166-
hi = batch_size
167-
while lo < hi:
168-
mid = (lo + hi) // 2
169-
if mCuTotalMBlocks[mid + 1] <= global_m_block:
170-
lo = mid + 1
171-
else:
172-
hi = mid
173-
batch_idx = lo
169+
batch_idx = get_batch_from_cu_tensor(global_m_block, mCuTotalMBlocks)
174170
m_block = global_m_block - mCuTotalMBlocks[batch_idx]
175171

176172
seqlen = SeqlenInfoCls(batch_idx)

flash_attn/cute/utils.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -949,3 +949,20 @@ def scalar_to_ssa(a: cute.Numeric, dtype) -> cute.TensorSSA:
949949
def ssa_to_scalar(val):
950950
"""Could inline but nice for reflecting the above api"""
951951
return val[0]
952+
953+
954+
@cute.jit
955+
def get_batch_from_cu_tensor(idx: Int32, cu_tensor: cute.Tensor) -> Int32:
956+
"""Binary search to determine batch from packed index in a cumulative tensor"""
957+
batch_size = cute.size(cu_tensor) - 1
958+
lo = Int32(0)
959+
hi = batch_size
960+
961+
while lo < hi:
962+
mid = (lo + hi) // 2
963+
if cu_tensor[mid + 1] <= idx:
964+
lo = mid + 1
965+
else:
966+
hi = mid
967+
968+
return lo

0 commit comments

Comments
 (0)