MCPcopy Create free account
hub / github.com/tile-ai/tilelang / ref_program

Function ref_program

examples/flash_decoding/example_gqa_decode.py:260–288  ·  view source on GitHub ↗
(query, key, value, mask)

Source from the content-addressed store, hash-verified

258
259
260def ref_program(query, key, value, mask):
261 # """
262 # Inputs:
263 # - query (Tensor): [batch, heads, dim]
264 # - key (Tensor): [batch, seqlen_kv, groups, dim]
265 # - value (Tensor): [batch, seqlen_kv, groups, dim]
266 # - mask (Tensor): [batch, seqlen_kv, groups]
267 # Outputs:
268 # - output (Tensor): [batch, heads, dim]
269 # """
270 dim = query.shape[-1]
271 num_head_groups = query.shape[1] // key.shape[2]
272 scale = dim**0.5
273 key = rearrange(key, "b n h d -> b h n d") # [batch_size, groups, seqlen_kv, dim]
274 value = rearrange(value, "b n h d -> b h n d") # [batch_size, groups, seqlen_kv, dim]
275
276 query = rearrange(query, "b (h g) d -> b g h d", g=num_head_groups) # [batch_size, num_head_groups, groups, dim]
277
278 scores = einsum(query, key, "b g h d, b h s d -> b g h s") # [batch_size, num_head_groups, groups, seqlen_kv]
279 if mask is not None:
280 mask = rearrange(mask, "b s h -> b h s")
281 mask = mask.unsqueeze(1)
282 scores = scores.masked_fill(mask == 0, float("-inf"))
283
284 attention = F.softmax(scores / scale, dim=-1) # [batch_size, num_head_groups, groups, seqlen_kv]
285
286 out = einsum(attention, value, "b g h s, b h s d -> b g h d") # [batch_size, num_head_groups, groups, dim]
287 out = rearrange(out, "b g h d -> b (h g) d") # [batch_size, heads, dim]
288 return out
289
290
291def flash_split_ref(Q, K, V, mask):

Callers 1

mainFunction · 0.70

Calls 1

floatClass · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…