"""Shared pieces for building per-anchor token sequences.
``select_sequences`` picks each anchor's tokens from its candidates into a padded
``[num_sequences, max_seq_len]`` grid, whatever generated the candidates (k-hop
expansion, PPR edges). ``pack_sequences`` turns that grid into a ``PackedLayout``:
the offsets and per-token indices that ``gigl.nn.packed_attention`` needs to run
on real tokens only. ``PackedRelationEdges`` holds the relation edges between
packed tokens.
"""
from typing import Final, NamedTuple, Optional
import torch
import torch.nn.functional as F
from jaxtyping import Int, Int32, Int64
from torch import Tensor
# Sequence lengths that ``pack_sequences`` sorts into buckets, each capped at
# ``max_seq_len``. ``max_seq_len`` is always a bucket length too.
[docs]
PACKED_BUCKET_LENGTHS: Final[tuple[int, ...]] = (32, 64, 128, 256)
[docs]
class RelationSegment(NamedTuple):
"""A relation id with the ``[start, end)`` range of its edges."""
[docs]
class PackedRelationEdges(NamedTuple):
"""Relation edges between packed tokens, grouped by relation.
Attributes:
target: ``[num_edges]`` long row of each edge's target in the layer's
queries and outputs.
source: ``[num_edges]`` long packed token row of each edge's source.
relation: ``[num_edges]`` long relation of each edge.
segments: ``(relation, start, end)`` edge range of every relation, in
order, covering ``[0, num_edges)``; empty if there are no edges. They
are host values, so the per-relation transforms never read the device.
anchor_edges: The edges into each sequence's anchor token, with ``target``
the sequence index, for a last layer that computes only the anchors.
None when no such layer runs.
"""
[docs]
segments: tuple[RelationSegment, ...]
[docs]
anchor_edges: Optional["PackedRelationEdges"] = None
[docs]
class PackedBucket(NamedTuple):
"""A run of packed sequences that share an upper bound on their length.
Packed sequences ``[first_sequence, end_sequence)`` are packed tokens
``[first_token, end_token)``, and each is at most ``bucket_len`` long. All
fields are host ints.
"""
[docs]
class PackedLayout(NamedTuple):
"""Where each sequence lives in the packed token buffer, and what each token is.
Attributes:
cu_seqlens: ``[num_sequences + 1]`` int32 cumulative sequence lengths,
on the same device as the tokens. Sequence ``i`` occupies
``[cu_seqlens[i], cu_seqlens[i + 1])``. The attention kernel
requires int32, so the total token count must fit in int32.
max_seq_len: Python int upper bound on any sequence length. It must be at
least the longest sequence, or the attention kernel skips rows. The
attention clamps it to the token count.
flat_index: ``[num_tokens]`` long indices of the valid cells of the
flattened ``[num_sequences, max_seq_len]`` grid, sequence by sequence.
sequence_id: ``[num_tokens]`` long sequence of each token,
``flat_index // max_seq_len``.
position: ``[num_tokens]`` long position of each token within its
sequence, ``flat_index % max_seq_len``. Position 0 is the anchor.
node_index: ``[num_tokens]`` long row of each token in the concatenated
node features.
token_attrs: Per-token values the builder knows, each
``[num_tokens, ...]``.
relation_edges: Relation edges in token coordinates, when the builder
makes them.
sequence_order: ``[num_sequences]`` long row of the caller's input
(``lengths`` and the grids) of each packed sequence. None when the
layout is not sorted.
buckets: The ``PackedBucket`` runs, longest ``bucket_len`` first,
covering all sequences and tokens, each holding at least two
sequences. The lengths are a subset of the bucket lengths of
``pack_sequences``. None means one bucket of ``max_seq_len``
covering everything, which is what an unsorted layout has.
Every per-sequence quantity (``cu_seqlens``, ``sequence_id``, the rows of the
grids ``flat_index`` refers to) is in packed order. ``flat_index`` indexes the
``[num_sequences, max_seq_len]`` grid whose rows are already in packed order,
so ``grid[sequence_order].flatten(0, 1)[flat_index]`` gathers a grid in the
caller's order. Only ``sequence_order`` maps back to the caller's order.
"""
[docs]
cu_seqlens: Int32[Tensor, "num_sequences_plus_one"]
[docs]
flat_index: Int64[Tensor, "num_tokens"]
[docs]
sequence_id: Int64[Tensor, "num_tokens"]
[docs]
position: Int64[Tensor, "num_tokens"]
[docs]
node_index: Int64[Tensor, "num_tokens"]
[docs]
token_attrs: dict[str, Tensor]
[docs]
relation_edges: Optional[PackedRelationEdges] = None
[docs]
sequence_order: Optional[Int64[Tensor, "num_sequences"]] = None
[docs]
buckets: Optional[tuple[PackedBucket, ...]] = None
[docs]
class SelectedSequences(NamedTuple):
"""The tokens ``select_sequences`` picked for each anchor.
Attributes:
nodes: ``[num_anchors, max_seq_len]`` long node ids, the anchor in
column 0 if ``include_anchor``, -1 from the sequence length on.
source: ``[num_anchors, max_seq_len]`` long column of ``candidates``
each token came from, so a per-candidate payload follows with
``payload.gather(1, source.clamp(min=0))``. It is -1 at the anchor
and at padding.
lengths: ``[num_anchors]`` long count of valid tokens, anchor included.
It is at most ``max_seq_len``, except that it counts the anchor even
when ``max_seq_len`` is 0.
"""
[docs]
nodes: Int64[Tensor, "num_anchors max_seq_len"]
[docs]
source: Int64[Tensor, "num_anchors max_seq_len"]
[docs]
lengths: Int64[Tensor, "num_anchors"]
[docs]
def pack_sequences(
lengths: Int64[Tensor, "num_sequences"],
max_seq_len: int,
node_grid: Optional[Int64[Tensor, "num_sequences max_seq_len"]] = None,
attr_grids: Optional[dict[str, Tensor]] = None,
sort_by_length: bool = False,
) -> PackedLayout:
"""Computes what is needed to drop the padding from a padded grid of sequences.
Sequence ``i`` is valid in its first ``lengths[i]`` positions. Any
``[num_sequences, max_seq_len]`` per-position tensor gathers into packed
order with ``grid.flatten()[flat_index]``, and ``cu_seqlens`` marks where
each packed sequence starts. This costs exactly one host read, which returns
the total token count and, when sorted, the bucket bounds; it is why the
packed buffer holds exactly the real tokens.
A length above ``max_seq_len`` is clamped to it, because the grid has no
positions beyond that. Checking for it would cost another host read.
With ``sort_by_length`` the sequences are packed longest first, ties in the
caller's order, and ``sequence_order`` maps each packed sequence back to its
row of the input. The grids are permuted the same way before packing. The
sorted sequences are also split into buckets by length: the lengths in
``PACKED_BUCKET_LENGTHS`` capped at ``max_seq_len``, plus ``max_seq_len``.
The lengths depend on ``max_seq_len`` only, never on the data. A sequence
goes to the smallest bucket length that holds it. Empty buckets are dropped.
A bucket with one sequence is merged into the next longer non-empty bucket
(or, if it is the longest, absorbs the next shorter one) and keeps the longer
length, until every bucket holds at least two sequences or one bucket is
left. A single bucket of ``max_seq_len`` is ``buckets`` None, and so are fewer
than two sequences. A single shorter bucket is kept, so the per-pair bias is
sized by it rather than by ``max_seq_len``. Dropping and merging keep
``torch.compile`` from specializing on bucket sizes 0 and 1, and the possible
structures are bounded by the subsets of the bucket lengths.
Example:
>>> packed = pack_sequences(torch.tensor([2, 1, 3]), max_seq_len=3)
>>> packed.flat_index.tolist()
[0, 1, 3, 6, 7, 8]
>>> packed.cu_seqlens.tolist()
[0, 2, 3, 6]
Sorted, the longest sequence comes first. Here ``max_seq_len`` is 3, so
there is only one bucket length and ``buckets`` is None::
>>> packed = pack_sequences(
... torch.tensor([1, 3, 2]), 3, sort_by_length=True
... )
>>> packed.sequence_order.tolist()
[1, 2, 0]
>>> packed.cu_seqlens.tolist()
[0, 3, 5, 6]
>>> packed.buckets is None
True
Args:
lengths: ``[num_sequences]`` number of valid positions of each sequence.
max_seq_len: Width of the padded grid.
node_grid: ``[num_sequences, max_seq_len]`` node row of each cell. If
None, ``node_index`` is the flat index.
attr_grids: ``[num_sequences, max_seq_len, ...]`` grids to gather into
``token_attrs``, by name.
sort_by_length: Whether to pack the sequences longest first and plan
buckets.
Returns:
The packed layout, without relation edges.
"""
lengths = lengths.clamp(max=max_seq_len)
sequence_order: Optional[Tensor] = None
if sort_by_length:
sequence_order = torch.sort(lengths, descending=True, stable=True).indices
lengths = lengths[sequence_order]
if node_grid is not None:
node_grid = node_grid[sequence_order]
if attr_grids is not None:
attr_grids = {
name: grid[sequence_order] for name, grid in attr_grids.items()
}
device = lengths.device
num_sequences = lengths.numel()
cu_seqlens = torch.cat([lengths.new_zeros(1), torch.cumsum(lengths, 0)])
bucket_lens = sorted(
{min(bound, max_seq_len) for bound in PACKED_BUCKET_LENGTHS} | {max_seq_len},
reverse=True,
)
num_boundaries = len(bucket_lens) - 1
if sort_by_length and num_boundaries > 0:
# Sequences longer than the next smaller bucket length are in the buckets
# above it, so these are the sequence bounds between buckets.
# The bounds are compared as Python ints, so no host-to-device copy (which
# synchronizes) is needed.
boundaries = torch.stack([(lengths > bound).sum() for bound in bucket_lens[1:]])
host_values = torch.cat(
[boundaries, cu_seqlens[boundaries], cu_seqlens[-1:]]
).tolist()
else:
host_values = [int(cu_seqlens[-1])]
num_tokens = host_values[-1]
sequence_id = torch.repeat_interleave(
torch.arange(num_sequences, device=device), lengths, output_size=num_tokens
)
position = torch.arange(num_tokens, device=device) - cu_seqlens[:-1][sequence_id]
flat_index = sequence_id * max_seq_len + position
buckets: Optional[tuple[PackedBucket, ...]] = None
if sort_by_length and num_boundaries > 0 and num_sequences >= 2:
sequence_bounds = [0] + host_values[:num_boundaries] + [num_sequences]
token_bounds = (
[0] + host_values[num_boundaries : 2 * num_boundaries] + [num_tokens]
)
# Each run is [first_sequence, end_sequence, first_token, end_token,
# bucket_len]. Empty buckets are dropped.
runs: list[list[int]] = []
for i in range(len(bucket_lens)):
if sequence_bounds[i + 1] > sequence_bounds[i]:
runs.append(
[
sequence_bounds[i],
sequence_bounds[i + 1],
token_bounds[i],
token_bounds[i + 1],
bucket_lens[i],
]
)
# A one-sequence bucket joins its next longer neighbor, or absorbs the
# next shorter one if it is the longest. The merged run keeps the longer
# bucket length, which holds every sequence in it.
while len(runs) > 1:
small = next((i for i, run in enumerate(runs) if run[1] - run[0] < 2), None)
if small is None:
break
if small > 0:
runs[small - 1][1] = runs[small][1]
runs[small - 1][3] = runs[small][3]
else:
runs[0][1] = runs[1][1]
runs[0][3] = runs[1][3]
del runs[small if small > 0 else 1]
if len(runs) > 1 or runs[0][4] < max_seq_len:
buckets = tuple(PackedBucket(*run) for run in runs)
if node_grid is None:
node_index = flat_index
else:
node_index = node_grid.flatten()[flat_index]
token_attrs: dict[str, Tensor] = {}
if attr_grids is not None:
for name, grid in attr_grids.items():
token_attrs[name] = grid.flatten(0, 1)[flat_index]
return PackedLayout(
cu_seqlens=cu_seqlens.to(torch.int32),
max_seq_len=max_seq_len,
flat_index=flat_index,
sequence_id=sequence_id,
position=position,
node_index=node_index,
token_attrs=token_attrs,
sequence_order=sequence_order,
buckets=buckets,
)
# Bits of a sort key that hold the candidate's column; a node id takes the bits
# above. A fixed width keeps shapes, not the column count, out of the arithmetic, so
# ``torch.compile`` does not recompile when the candidate count changes.
_COLUMN_BITS = 26
_COLUMN_MASK = (1 << _COLUMN_BITS) - 1
[docs]
def select_sequences(
anchor_indices: Int[Tensor, "num_anchors"],
candidates: Int64[Tensor, "num_anchors num_candidates"],
max_seq_len: int,
priority: Optional[Tensor] = None,
ties_by_column: bool = False,
include_anchor: bool = True,
) -> SelectedSequences:
"""Picks each anchor's tokens from its candidates, with fixed shapes.
Every anchor's sequence is the anchor, then its distinct candidate nodes other
than the anchor, ordered by ``priority`` (ties by ascending node id, or by
column with ``ties_by_column``) and cut at ``max_seq_len``. A node that
appears in several columns keeps the lowest column, so put the preferred copy
of a node first. This is the selection step shared by the k-hop and PPR
sequence builders: they differ in how they generate the candidates and in
what ``priority`` ranks.
Example:
Two anchors, 0 and 1. Node 3 is a duplicate candidate of anchor 0, anchor 0
is among its own candidates, and -1 is padding::
>>> anchors = torch.tensor([0, 1])
>>> candidates = torch.tensor([[5, 3, 0, 3, -1], [4, 1, 6, 4, 2]])
>>> nodes, source, lengths = select_sequences(anchors, candidates, 4)
>>> nodes.tolist()
[[0, 3, 5, -1], [1, 2, 4, 6]]
>>> lengths.tolist()
[3, 4]
Gather a per-candidate payload with ``source``, zeroing the anchor and
padding tokens::
>>> payload = torch.arange(10, 20).reshape(2, 5)
>>> (payload.gather(1, source.clamp(min=0)) * (source >= 0)).tolist()
[[0, 11, 10, 0], [0, 19, 15, 17]]
A ``priority`` ranks the candidates (smaller first); equal priorities go by
node id, or by column with ``ties_by_column``::
>>> priority = torch.tensor([[0, 1, 0, 1, 0], [2, 9, 0, 5, 0]])
>>> select_sequences(anchors, candidates, 4, priority).nodes.tolist()
[[0, 5, 3, -1], [1, 2, 6, 4]]
>>> select_sequences(
... anchors, candidates, 4, priority, ties_by_column=True
... ).nodes.tolist()
[[0, 5, 3, -1], [1, 6, 2, 4]]
Without ``include_anchor`` the candidates are the whole sequence, so anchor
0 stays in its sequence as the candidate it is::
>>> select_sequences(anchors, candidates, 4, include_anchor=False).source.tolist()
[[2, 1, 0, -1], [1, 4, 0, 2]]
Args:
anchor_indices: ``[num_anchors]`` node ids of the anchors.
candidates: ``[num_anchors, num_candidates]`` long candidate node ids,
-1 at padding. The anchor itself may appear. There can be at most
``2 ** 26`` columns.
max_seq_len: Tokens per sequence, anchor included.
priority: ``[num_anchors, num_candidates]`` integer or float rank of each
candidate; smaller comes first. If None, candidates are ordered by
ascending node id, which costs one sort instead of two. Pass the
column index to keep the candidates' own order.
ties_by_column: Whether candidates with equal ``priority`` stay in column
order instead of ascending node id. It has no effect without
``priority``.
include_anchor: Whether column 0 holds the anchor, which is then dropped
from the candidates. If False, the sequence is only candidates, and
the anchor stays in it if it is one of them.
Returns:
The ``SelectedSequences``: ``nodes``, ``source`` and ``lengths``.
"""
anchor_indices = anchor_indices.long()
num_candidates = candidates.size(1)
padding_key = torch.iinfo(torch.long).max
# Sort ``(node << _COLUMN_BITS) | column``: each node's copies are adjacent
# with the lowest column first, and padding sorts last.
columns = torch.arange(num_candidates, device=candidates.device)
keys = torch.where(
candidates >= 0, (candidates << _COLUMN_BITS) | columns, padding_key
)
keys = torch.sort(keys, dim=1).values
nodes = keys >> _COLUMN_BITS
keep = (keys != padding_key) & F.pad(nodes.diff(dim=1) != 0, (1, 0), value=True)
if include_anchor:
keep = keep & (nodes != anchor_indices.unsqueeze(1))
if priority is not None:
if ties_by_column:
# Put the kept candidates back in column order, so the stable sort
# below leaves priority ties there.
by_column = torch.sort(
torch.where(keep, keys & _COLUMN_MASK, num_candidates), dim=1
).indices
keys = keys.gather(1, by_column)
keep = keep.gather(1, by_column)
# Dropped candidates rank last, so the kept ones come first, in
# ``priority`` order and then ascending node id. Padding decodes to an
# out-of-range column; its priority is never used.
columns = (keys & _COLUMN_MASK).clamp(max=num_candidates - 1)
if priority.is_floating_point():
worst = torch.inf
else:
worst = torch.iinfo(priority.dtype).max
order = torch.sort(
torch.where(keep, priority.gather(1, columns), worst),
dim=1,
stable=True,
).indices
keys = keys.gather(1, order)
keep = keep.gather(1, order)
# With the anchor, it takes column 0 and the kept candidates are numbered from
# 1. The kept candidates are cut at ``max_seq_len``.
first_position = int(include_anchor)
positions = torch.cumsum(keep, dim=1) - 1 + first_position
keep = keep & (positions < max_seq_len)
# Dropped candidates scatter into an extra last column, which is sliced off.
packed = torch.full(
(anchor_indices.numel(), max_seq_len + 1),
-1,
dtype=torch.long,
device=keys.device,
)
packed.scatter_(1, torch.where(keep, positions, max_seq_len), keys)
packed = packed[:, :max_seq_len]
if include_anchor and max_seq_len > 0:
packed[:, 0] = anchor_indices << _COLUMN_BITS
source = torch.where(packed >= 0, packed & _COLUMN_MASK, -1)
if include_anchor and max_seq_len > 0:
source[:, 0] = -1
return SelectedSequences(
packed >> _COLUMN_BITS, source, first_position + keep.sum(dim=1)
)