IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /get-started.md). For the complete documentation index, see llms.txt.
Skip to main content
For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /get-started.md).

Mojo struct

TopKHeap

struct TopKHeap[T: DType, largest: Bool, M: Int]

Fixed-capacity register heap for per-thread top-M tracking.

Stores up to M (value, index) pairs in registers. During the scan phase, a cached threshold provides O(1) rejection of non-competitive elements. All internal loops are compile-time unrolled to keep data in registers on GPU. Indices are stored as Int32 to reduce register pressure for large block sizes.

Fields​

  • ​vals (Array[Scalar[T], M]):
  • ​idxs (Array[Int32, M]):
  • ​threshold (Scalar[T]):

Implemented traits​

AnyType, Deinitable, Movable

Methods​

__init__​

def __init__(out self)

insert​

def insert(mut self, val: Scalar[T], idx: Int)

Insert an element, evicting the worst if full.

best​

def best(self) -> TopK_2[T, largest]

Return the best element, ties broken by smallest index.

Returns a dead TopK_2 (p=-1) when every slot has been retired.

Returns:

TopK_2[T, largest]

remove​

def remove(mut self, idx: Int)

Retires element idx, keeping the index behind as a record.

The slot's index is left in place so that retired can still name the elements this thread has already emitted -- the replacement for writing the dead value over them in the row.

retired​

def retired(self, idx: Int) -> Bool

Whether this thread has already emitted element idx from the heap.

A slot that was never filled holds index -1 and one that still holds a live element is not retired, so a retired slot is exactly one that has this index and the dead value.

Returns:

Bool

Was this page helpful?