gigl.transforms.sequence_layout#
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.
Attributes#
Classes#
A run of packed sequences that share an upper bound on their length. |
|
Where each sequence lives in the packed token buffer, and what each token is. |
|
Relation edges between packed tokens, grouped by relation. |
|
A relation id with the |
|
The tokens |
Functions#
|
Computes what is needed to drop the padding from a padded grid of sequences. |
|
Picks each anchor's tokens from its candidates, with fixed shapes. |
Module Contents#
- class gigl.transforms.sequence_layout.PackedBucket[source]#
Bases:
NamedTupleA 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 mostbucket_lenlong. All fields are host ints.
- class gigl.transforms.sequence_layout.PackedLayout[source]#
Bases:
NamedTupleWhere each sequence lives in the packed token buffer, and what each token is.
- cu_seqlens[source]#
[num_sequences + 1]int32 cumulative sequence lengths, on the same device as the tokens. Sequenceioccupies[cu_seqlens[i], cu_seqlens[i + 1]). The attention kernel requires int32, so the total token count must fit in int32.
- max_seq_len[source]#
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[source]#
[num_tokens]long indices of the valid cells of the flattened[num_sequences, max_seq_len]grid, sequence by sequence.
- position[source]#
[num_tokens]long position of each token within its sequence,flat_index % max_seq_len. Position 0 is the anchor.
- sequence_order[source]#
[num_sequences]long row of the caller’s input (lengthsand the grids) of each packed sequence. None when the layout is not sorted.
- buckets[source]#
The
PackedBucketruns, longestbucket_lenfirst, covering all sequences and tokens, each holding at least two sequences. The lengths are a subset of the bucket lengths ofpack_sequences. None means one bucket ofmax_seq_lencovering everything, which is what an unsorted layout has.
Every per-sequence quantity (
cu_seqlens,sequence_id, the rows of the gridsflat_indexrefers to) is in packed order.flat_indexindexes the[num_sequences, max_seq_len]grid whose rows are already in packed order, sogrid[sequence_order].flatten(0, 1)[flat_index]gathers a grid in the caller’s order. Onlysequence_ordermaps back to the caller’s order.- buckets: tuple[PackedBucket, Ellipsis] | None = None[source]#
- relation_edges: PackedRelationEdges | None = None[source]#
- class gigl.transforms.sequence_layout.PackedRelationEdges[source]#
Bases:
NamedTupleRelation edges between packed tokens, grouped by relation.
- segments[source]#
(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[source]#
The edges into each sequence’s anchor token, with
targetthe sequence index, for a last layer that computes only the anchors. None when no such layer runs.
- anchor_edges: PackedRelationEdges | None = None[source]#
- segments: tuple[RelationSegment, Ellipsis][source]#
- class gigl.transforms.sequence_layout.RelationSegment[source]#
Bases:
NamedTupleA relation id with the
[start, end)range of its edges.
- class gigl.transforms.sequence_layout.SelectedSequences[source]#
Bases:
NamedTupleThe tokens
select_sequencespicked for each anchor.- nodes[source]#
[num_anchors, max_seq_len]long node ids, the anchor in column 0 ifinclude_anchor, -1 from the sequence length on.
- source[source]#
[num_anchors, max_seq_len]long column ofcandidateseach token came from, so a per-candidate payload follows withpayload.gather(1, source.clamp(min=0)). It is -1 at the anchor and at padding.
- gigl.transforms.sequence_layout.pack_sequences(lengths, max_seq_len, node_grid=None, attr_grids=None, sort_by_length=False)[source]#
Computes what is needed to drop the padding from a padded grid of sequences.
Sequence
iis valid in its firstlengths[i]positions. Any[num_sequences, max_seq_len]per-position tensor gathers into packed order withgrid.flatten()[flat_index], andcu_seqlensmarks 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_lenis clamped to it, because the grid has no positions beyond that. Checking for it would cost another host read.With
sort_by_lengththe sequences are packed longest first, ties in the caller’s order, andsequence_ordermaps 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 inPACKED_BUCKET_LENGTHScapped atmax_seq_len, plusmax_seq_len. The lengths depend onmax_seq_lenonly, 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 ofmax_seq_lenisbucketsNone, and so are fewer than two sequences. A single shorter bucket is kept, so the per-pair bias is sized by it rather than bymax_seq_len. Dropping and merging keeptorch.compilefrom 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_lenis 3, so there is only one bucket length andbucketsis 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
- Parameters:
lengths (jaxtyping.Int64[torch.Tensor, pack_sequences.num_sequences]) –
[num_sequences]number of valid positions of each sequence.max_seq_len (int) – Width of the padded grid.
node_grid (Optional[jaxtyping.Int64[torch.Tensor, num_sequences max_seq_len]]) –
[num_sequences, max_seq_len]node row of each cell. If None,node_indexis the flat index.attr_grids (Optional[dict[str, torch.Tensor]]) –
[num_sequences, max_seq_len, ...]grids to gather intotoken_attrs, by name.sort_by_length (bool) – Whether to pack the sequences longest first and plan buckets.
- Returns:
The packed layout, without relation edges.
- Return type:
- gigl.transforms.sequence_layout.select_sequences(anchor_indices, candidates, max_seq_len, priority=None, ties_by_column=False, include_anchor=True)[source]#
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 withties_by_column) and cut atmax_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 whatpriorityranks.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
priorityranks the candidates (smaller first); equal priorities go by node id, or by column withties_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_anchorthe 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]]
- Parameters:
anchor_indices (jaxtyping.Int[torch.Tensor, num_anchors]) –
[num_anchors]node ids of the anchors.candidates (jaxtyping.Int64[torch.Tensor, num_anchors num_candidates]) –
[num_anchors, num_candidates]long candidate node ids, -1 at padding. The anchor itself may appear. There can be at most2 ** 26columns.max_seq_len (int) – Tokens per sequence, anchor included.
priority (Optional[torch.Tensor]) –
[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 (bool) – Whether candidates with equal
prioritystay in column order instead of ascending node id. It has no effect withoutpriority.include_anchor (bool) – 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:
nodes,sourceandlengths.- Return type:
The
SelectedSequences