gigl.transforms.graph_transformer#
Transform HeteroData to Graph Transformer sequence input.
This module provides functionality to convert PyG HeteroData objects (typically batched 2-hop subgraphs) into sequence format suitable for Graph Transformers.
For each anchor node in the batch, the transform extracts its k-hop neighborhood and creates a fixed-length sequence of node features with padding.
- Example Usage:
>>> from torch_geometric.data import HeteroData >>> from gigl.transforms.graph_transformer import heterodata_to_graph_transformer_input >>> >>> # Create batched HeteroData (e.g., from NeighborLoader) >>> # First batch_size nodes in each node type are anchor nodes >>> data = HeteroData() >>> data['user'].x = torch.randn(100, 64) # 100 users, first N are anchors >>> data['item'].x = torch.randn(50, 32) >>> data['user', 'buys', 'item'].edge_index = ... >>> >>> # Transform to Graph Transformer input >>> sequences, valid_mask, attention_bias_data = heterodata_to_graph_transformer_input( ... data=data, ... batch_size=32, ... max_seq_len=128, ... anchor_node_type='user', ... ) >>> # sequences: (batch_size, max_seq_len, feature_dim) >>> # valid_mask: (batch_size, max_seq_len)
tensors_to_graph_transformer_inputtakes the same arguments with the batch’sx_dict/edge_index_dict(and optionaledge_attr_dict,graph_attr_dict) instead of aHeteroData.With Relative Encodings: Relative encodings stored as sparse graph-level attributes can be returned as raw attention-bias features:
>>> from torch_geometric.transforms import Compose >>> from gigl.transforms.add_positional_encodings import ( ... AddHeteroRandomWalkEncodings, ... AddHeteroHopDistanceEncoding, ... ) >>> >>> # First apply PE transforms to the data >>> pe_transform = Compose([ ... AddHeteroRandomWalkEncodings(walk_length=8), ... AddHeteroHopDistanceEncoding(h_max=5), ... ]) >>> data = pe_transform(data) >>> >>> # Transform to sequences with relative bias features >>> sequences, valid_mask, attention_bias_data = heterodata_to_graph_transformer_input( ... data=data, ... batch_size=32, ... max_seq_len=128, ... anchor_node_type='user', ... anchor_based_attention_bias_attr_names=['hop_distance'], ... ) >>> # sequences: (batch_size, max_seq_len, feature_dim) >>> # attention_bias_data['anchor_bias']: (batch_size, max_seq_len, 1)
Attributes#
Classes#
dict() -> new empty dictionary |
Functions#
|
|
|
Returns the row offset of each node type in the concatenated node features. |
|
Collects the sparse feature matrices for the requested attribute names. |
|
Transform a HeteroData object to Graph Transformer sequence input. |
|
Look up values in a CSR sparse matrix for given (row, col) pairs. |
|
Looks up |
|
Build sparse relation coordinates for valid token pairs. |
Look up pairwise sparse values for each valid token pair in the sequence. |
|
|
Transform a batch's tensors to Graph Transformer sequence input. |
|
Concatenates edge indices the way |
Validate placement of the reserved PPR anchor-relative features. |
Module Contents#
- class gigl.transforms.graph_transformer.SequenceAuxiliaryData[source]#
Bases:
TypedDictdict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
Initialize self. See help(type(self)) for accurate signature.
- gigl.transforms.graph_transformer.concat_tensors(parts, dim)[source]#
torch.catthat returns a single part as is, without a copy.- Parameters:
parts (list[torch.Tensor])
dim (int)
- Return type:
torch.Tensor
- gigl.transforms.graph_transformer.get_node_type_offsets(x_dict)[source]#
Returns the row offset of each node type in the concatenated node features.
- Parameters:
x_dict (dict[torch_geometric.typing.NodeType, torch.Tensor]) – Node features by node type, in concatenation order.
- Returns:
The offset of each node type’s first row.
- Return type:
dict[torch_geometric.typing.NodeType, int]
- gigl.transforms.graph_transformer.get_sparse_feature_matrices(graph_attr_dict, attr_names, missing_attr_error_prefix)[source]#
Collects the sparse feature matrices for the requested attribute names.
- Parameters:
graph_attr_dict (dict[str, torch.Tensor]) – Sparse matrices keyed by attribute name.
attr_names (Optional[list[str]]) – Names to collect, in order;
Nonecollects nothing.missing_attr_error_prefix (str) – Prefix of the error raised for a missing name.
- Returns:
The matrices in the order of
attr_names.- Raises:
ValueError – If a requested name is not in
graph_attr_dict.- Return type:
list[torch.Tensor]
- gigl.transforms.graph_transformer.heterodata_to_graph_transformer_input(data, batch_size, max_seq_len, anchor_node_type, anchor_node_ids=None, hop_distance=2, sequence_construction_method='khop', include_anchor_first=True, padding_value=0.0, anchor_based_attention_bias_attr_names=None, anchor_based_input_attr_names=None, pairwise_attention_bias_attr_names=None, relation_edge_types=None, sampling_direction='out', prioritize_hop_order=False)[source]#
Transform a HeteroData object to Graph Transformer sequence input.
Given a batched HeteroData object where the first batch_size nodes of anchor_node_type are anchor nodes, this function extracts the k-hop neighborhood for each anchor and creates padded sequences.
Uses sparse matrix operations for efficient batched k-hop neighbor extraction.
- Parameters:
data (torch_geometric.data.HeteroData) – HeteroData object containing node features and edge indices. Expected to have node features as data[node_type].x. All node types must have the same feature dimension.
batch_size (int) – Number of anchor nodes (first batch_size nodes of anchor_node_type). Ignored if anchor_node_ids is provided.
max_seq_len (int) – Maximum sequence length (neighbors beyond this are truncated).
anchor_node_type (torch_geometric.typing.NodeType) – The node type of anchor nodes.
anchor_node_ids (Optional[jaxtyping.Int64[torch.Tensor, anchors]]) – Optional tensor of local node indices within anchor_node_type to use as anchors. If None, uses first batch_size nodes. (default: None)
hop_distance (int) – Number of hops to consider for neighborhood when
sequence_construction_method="khop". (default: 2)sequence_construction_method (Literal['khop', 'ppr']) – Strategy used to build per-anchor sequences.
"khop"performs the existing k-hop expansion over the sampled graph."ppr"uses outgoing(anchor_type, "ppr", neighbor_type)edges, sorted by descending PPR weight fromedge_attr. (default:"khop")include_anchor_first (bool) – If True, anchor node is always first in sequence.
padding_value (float) – Value to use for padding (default: 0.0).
anchor_based_attention_bias_attr_names (Optional[list[str]]) – List of anchor-relative feature names used as attention bias. Sparse graph-level attributes are looked up from
dataand the reserved name"ppr_weight"resolves to PPR edge weights in PPR sequence mode. Example: [‘hop_distance’, ‘ppr_weight’].anchor_based_input_attr_names (Optional[list[str]]) – List of anchor-relative attribute names returned as token-aligned model-input features. Sparse graph-level attributes are looked up from
dataand"ppr_weight"resolves to PPR edge weights in PPR sequence mode. Example: [‘hop_distance’, ‘ppr_weight’].pairwise_attention_bias_attr_names (Optional[list[str]]) – List of pairwise feature names used as attention bias. These must correspond to sparse graph-level attributes on
data. Example: [‘pairwise_distance’].relation_edge_types (Optional[list[gigl.src.common.types.graph_data.EdgeType]]) – Optional ordered edge types used to materialize sparse relation coordinates. Each output relation index corresponds to one edge type in this list. Directed edges are stored as
(batch_idx, query_pos=dst_token, key_pos=src_token, relation_idx).sampling_direction (Literal['in', 'out']) – Direction used for token construction.
"out"preserves the existing k-hop reachability expansion."in"expands over reversed edges and is supported only withsequence_construction_method="khop". Directed relative encodings such as"hop_distance"should be computed with the same direction.prioritize_hop_order (bool) – If True, k-hop sequence construction fills tokens by hop depth before truncating to
max_seq_len. The default False preserves existing homogeneous-node-id ordering.
- Returns:
- sequences: (batch_size, max_seq_len, feature_dim) padded node features
taken directly from
data[node_type].xin homogeneous order.- valid_mask: (batch_size, max_seq_len) bool tensor indicating which
sequence positions correspond to real nodes.
- sequence_auxiliary_data: dictionary of raw token-aligned and
attention-bias features with:
"anchor_bias"shaped(batch, seq, num_anchor_attrs)or None"pairwise_bias"shaped(batch, seq, seq, num_pairwise_attrs)or None"pairwise_relation_indices"shaped(num_relation_edges, 4)or None, storing(batch_idx, query_pos, key_pos, relation_idx)coordinates"pairwise_nonmissing_indices"shaped(num_pairs, 3)or None, storing(batch_idx, row_pos, col_pos)coordinates for nonmissing pairwise entries"token_input"as a dict mapping attribute name to a(batch, seq, 1)tensor, or None
- Return type:
(sequences, valid_mask, attention_bias_data), where
- Raises:
ValueError – If node types have different feature dimensions.
ValueError – If no node features exist in the data.
- gigl.transforms.graph_transformer.lookup_csr_values(csr_matrix, row_indices, col_indices, default_value=0.0)[source]#
Look up values in a CSR sparse matrix for given (row, col) pairs.
Vectorized CSR lookup: for each query, slice the row and search for the column. Time complexity: O(n * avg_nnz_per_row), typically O(n) for sparse matrices.
- Parameters:
csr_matrix (torch.Tensor) – (num_rows, num_cols) sparse CSR tensor
row_indices (jaxtyping.Int[torch.Tensor, num_lookups]) – (n,) row indices to look up
col_indices (jaxtyping.Int[torch.Tensor, num_lookups]) – (n,) column indices to look up
default_value (float) – Value for missing entries (default: 0.0)
- Returns:
(n,) values from csr_matrix[row, col], or default_value if not present
- Return type:
jaxtyping.Float32[torch.Tensor, num_lookups]
- gigl.transforms.graph_transformer.lookup_csr_values_without_host_sync(csr_matrix, row_indices, col_indices)[source]#
Looks up
csr_matrix[row, col]for each (row, col) pair, with no host read.Gives the same values as
lookup_csr_values, which reads the longest queried row’s length back from the device. This version sorts the matrix’srow * num_cols + colkeys and binary-searches them instead, so it costs no host read and its output shape does not depend on the data.Example
>>> matrix = torch.tensor([[0.0, 2.0], [3.0, 0.0]]).to_sparse_csr() >>> lookup_csr_values_without_host_sync( ... matrix, torch.tensor([0, 1, 1]), torch.tensor([1, 0, 1]) ... ).tolist() [2.0, 3.0, 0.0]
- Parameters:
csr_matrix (torch.Tensor) –
[num_rows, num_cols]sparse CSR tensor.row_indices (torch.Tensor) –
[n]row of each query.col_indices (torch.Tensor) –
[n]column of each query.
- Returns:
[n]float values, 0 where the matrix has no entry.- Return type:
torch.Tensor
- gigl.transforms.graph_transformer.lookup_pairwise_relation_indices(edge_index_dict, node_index_sequences, valid_mask, relation_edge_types, node_type_offsets, num_nodes, device, expanded_token_mask=None, relation_channel_masks=None, frontier_batch_node_keys=None, sampling_direction='out')[source]#
Build sparse relation coordinates for valid token pairs.
For a directed edge
source -> target, attention usesquery=targetandkey=sourceso relation-aware attention follows message-passing orientation.If
frontier_batch_node_keysis given (sortedbatch_idx * num_nodes + node_idxkeys), an edge is kept only when its expanded endpoint is in that anchor’s frontier. K-hop sequences pass this so relation edges match the anchor’s own sample; PPR sequences passNone.If
expanded_token_maskis given (a per-token bitmask of the PPR channels that pushed each token’s node), an edge is kept only when the anchor expanded its owner – the query/target position, since GLT reverses sampled edges in collation. For typed PPR,relation_channel_masksmaps an edge type to the channels allowed to fetch it, so the edge is kept only when the owner was pushed in one of those channels. PPR sequences pass these; k-hop passesNone.- Parameters:
edge_index_dict (dict[torch_geometric.typing.EdgeType, torch.Tensor]) – Edge index tensors keyed by edge type tuple.
node_index_sequences (jaxtyping.Int[torch.Tensor, batch seq]) – Node ids of each sequence token.
valid_mask (jaxtyping.Bool[torch.Tensor, batch seq]) – True for real (non-padding) tokens.
relation_edge_types (Optional[list[gigl.src.common.types.graph_data.EdgeType]]) – Edge types that define the relation ids, in order.
node_type_offsets (dict[torch_geometric.typing.NodeType, int]) – Offset of each node type in the homogeneous node id space.
num_nodes (int) – Total number of nodes in the homogeneous node id space.
device (torch.device) – Device for the returned tensor.
expanded_token_mask (Optional[jaxtyping.Int[torch.Tensor, batch seq]]) – Optional per-token bitmask of the PPR channels that pushed each token’s node.
relation_channel_masks (Optional[dict[torch_geometric.typing.EdgeType, int]]) – Optional map from edge type to the allowed PPR channel bitmask.
frontier_batch_node_keys (Optional[jaxtyping.Int[torch.Tensor, num_frontier_keys]]) – Optional sorted
batch_idx * num_nodes + node_idxkeys of the anchor frontier.sampling_direction (Literal['in', 'out']) – Whether sampled edges point
"out"from or"in"to the expanded node.
- Returns:
[N, 4]unique(batch, query, key, relation)rows sorted by relation, then(batch, query, key);[0, 4]if there are none, andNonewithout relation edge types.- Return type:
Optional[jaxtyping.Int64[torch.Tensor, num_relation_edges 4]]
- gigl.transforms.graph_transformer.lookup_pairwise_relative_features(node_index_sequences, valid_mask, csr_matrices, attr_names, device)[source]#
Look up pairwise sparse values for each valid token pair in the sequence.
For each pair of nodes (i, j) in the sequence, this looks up the value PE[node_i, node_j] from each provided sparse CSR matrix. This captures pairwise relationships between all sequence tokens (e.g., random walk structural encoding between any two nodes).
The output is typically used as attention bias in Graph Transformers, added to attention scores before softmax.
- Parameters:
node_index_sequences (jaxtyping.Int[torch.Tensor, batch seq]) – (batch_size, max_seq_len) node indices for each sequence position
valid_mask (jaxtyping.Bool[torch.Tensor, batch seq]) – (batch_size, max_seq_len) bool tensor indicating valid positions
csr_matrices (Optional[list[torch.Tensor]]) – List of sparse CSR matrices, each (num_nodes, num_nodes)
attr_names (Optional[list[str]]) – Optional names for the pairwise attributes. Used only to produce clearer error messages when multiple attrs disagree on sparse support.
device (torch.device) – Device for output tensor
- Returns:
- (batch_size, max_seq_len, max_seq_len, num_attrs) tensor where
features[b, i, j, k] = csr_matrices[k][node_index_sequences[b, i], node_index_sequences[b, j]] for valid (i, j) pairs, 0.0 for padding positions.
- nonmissing_indices: (num_nonmissing_pairs, 3) long tensor containing
(batch_idx, row_pos, col_pos)coordinates for valid diagonal self pairs and valid sparse entries. Missing non-self pairs and padding are omitted.
Returns (None, None) if csr_matrices is empty.
- Return type:
features
Example
# batch_size=2, max_seq_len=3, num_attrs=1 (e.g., random_walk_se) # node_index_sequences = [[10, 5, 7], # anchor 0’s sequence # [20, 3, -1]] # anchor 1’s sequence (padded) # valid_mask = [[T, T, T], [T, T, F]] # # Output shape: (2, 3, 3, 1) # # For batch 0 (all valid), features[0, :, :, 0] is a 3x3 matrix: # node 10 node 5 node 7 # node 10 [PE[10,10], PE[10,5], PE[10,7]] # node 5 [PE[5,10], PE[5,5], PE[5,7]] # node 7 [PE[7,10], PE[7,5], PE[7,7]] # # For batch 1 (position 2 is padding), features[1, :, :, 0]: # node 20 node 3 (pad) # node 20 [PE[20,20], PE[20,3], 0.0] # node 3 [PE[3,20], PE[3,3], 0.0] # (pad) [0.0, 0.0, 0.0]
- gigl.transforms.graph_transformer.tensors_to_graph_transformer_input(x_dict, edge_index_dict, batch_size, max_seq_len, anchor_node_type, edge_attr_dict=None, graph_attr_dict=None, ppr_is_expanded_dict=None, ppr_relation_channel_masks=None, anchor_node_ids=None, hop_distance=2, sequence_construction_method='khop', include_anchor_first=True, padding_value=0.0, anchor_based_attention_bias_attr_names=None, anchor_based_input_attr_names=None, pairwise_attention_bias_attr_names=None, relation_edge_types=None, sampling_direction='out', prioritize_hop_order=False)[source]#
Transform a batch’s tensors to Graph Transformer sequence input.
Same as
heterodata_to_graph_transformer_input, but takes the tensors aHeteroDatabatch holds instead of the batch itself, sotorch.compilecan trace it without building PyG containers.Homogeneous node ids follow
x_dict’s key order and edges followedge_index_dict’s key order, matchingHeteroData.to_homogeneousfor a batch with the same node and edge type order.Example
>>> sequences, valid_mask, attention_bias_data = tensors_to_graph_transformer_input( ... x_dict={"user": user_x}, ... edge_index_dict={("user", "to", "user"): edge_index}, ... batch_size=32, ... max_seq_len=128, ... anchor_node_type="user", ... )
- Parameters:
x_dict (dict[torch_geometric.typing.NodeType, torch.Tensor]) – Node features per node type, in the batch’s node type order. All node types must have the same feature dimension.
edge_index_dict (dict[torch_geometric.typing.EdgeType, torch.Tensor]) – Edge indices per edge type, in the batch’s edge type order.
edge_attr_dict (Optional[dict[torch_geometric.typing.EdgeType, torch.Tensor]]) – Edge attributes per edge type. Only PPR sequences read them. (default: None)
graph_attr_dict (Optional[dict[str, torch.Tensor]]) – Graph-level sparse relative-encoding matrices, by attribute name (e.g.
"hop_distance"). (default: None)ppr_is_expanded_dict (Optional[dict[torch_geometric.typing.EdgeType, torch.Tensor]]) – Per-edge
ppr_is_expandedflags (or typed-PPR channel bitmasks) per"ppr"edge type. When every"ppr"edge type has one, PPR relation edges are kept only when the anchor expanded the edge’s owner. (default: None)ppr_relation_channel_masks (Optional[dict[torch_geometric.typing.EdgeType, int]]) – Typed-PPR channel bitmask per relation edge type; a relation edge is kept only when the anchor pushed its owner in one of those channels. (default: None)
batch_size (int) – Number of anchor nodes (first batch_size nodes of anchor_node_type). Ignored if anchor_node_ids is provided.
max_seq_len (int) – Maximum sequence length (neighbors beyond this are truncated).
anchor_node_type (torch_geometric.typing.NodeType) – The node type of anchor nodes.
anchor_node_ids (Optional[jaxtyping.Int64[torch.Tensor, anchors]]) – Optional tensor of local node indices within anchor_node_type to use as anchors. If None, uses first batch_size nodes. (default: None)
hop_distance (int) – Number of hops to consider for neighborhood when
sequence_construction_method="khop". (default: 2)sequence_construction_method (Literal['khop', 'ppr']) – Strategy used to build per-anchor sequences.
"khop"performs the existing k-hop expansion over the sampled graph."ppr"uses outgoing(anchor_type, "ppr", neighbor_type)edges, sorted by descending PPR weight fromedge_attr. (default:"khop")include_anchor_first (bool) – If True, anchor node is always first in sequence.
padding_value (float) – Value to use for padding (default: 0.0).
anchor_based_attention_bias_attr_names (Optional[list[str]]) – List of anchor-relative feature names used as attention bias. Sparse graph-level attributes are looked up from
graph_attr_dictand the reserved name"ppr_weight"resolves to PPR edge weights in PPR sequence mode. Example: [‘hop_distance’, ‘ppr_weight’].anchor_based_input_attr_names (Optional[list[str]]) – List of anchor-relative attribute names returned as token-aligned model-input features. Sparse graph-level attributes are looked up from
graph_attr_dictand"ppr_weight"resolves to PPR edge weights in PPR sequence mode. Example: [‘hop_distance’, ‘ppr_weight’].pairwise_attention_bias_attr_names (Optional[list[str]]) – List of pairwise feature names used as attention bias. These must correspond to sparse graph-level entries of
graph_attr_dict. Example: [‘pairwise_distance’].relation_edge_types (Optional[list[gigl.src.common.types.graph_data.EdgeType]]) – Optional ordered edge types used to materialize sparse relation coordinates. Each output relation index corresponds to one edge type in this list. Directed edges are stored as
(batch_idx, query_pos=dst_token, key_pos=src_token, relation_idx).sampling_direction (Literal['in', 'out']) – Direction used for token construction.
"out"preserves the existing k-hop reachability expansion."in"expands over reversed edges and is supported only withsequence_construction_method="khop". Directed relative encodings such as"hop_distance"should be computed with the same direction.prioritize_hop_order (bool) – If True, k-hop sequence construction fills tokens by hop depth before truncating to
max_seq_len. The default False preserves existing homogeneous-node-id ordering.
- Returns:
(sequences, valid_mask, attention_bias_data); see
heterodata_to_graph_transformer_input.- Raises:
ValueError – If node types have different feature dimensions.
- Return type:
tuple[jaxtyping.Float[torch.Tensor, anchors sequence feature_dim], jaxtyping.Bool[torch.Tensor, anchors sequence], SequenceAuxiliaryData]
- gigl.transforms.graph_transformer.to_homogeneous_edge_index(edge_index_dict, node_type_offsets, device)[source]#
Concatenates edge indices the way
HeteroData.to_homogeneousdoes.Each edge type’s ids are shifted by its node type offsets, and edge types keep
edge_index_dict’s order. The edge indices’ dtype is kept.- Parameters:
edge_index_dict (dict[torch_geometric.typing.EdgeType, torch.Tensor]) –
[2, num_edges]local edge index by edge type.node_type_offsets (dict[torch_geometric.typing.NodeType, int]) – Offsets from
get_node_type_offsets.device (torch.device) – Device of the result.
- Returns:
[2, num_edges]edge index ondevice; a long[2, 0]if there are no edges.- Return type:
torch.Tensor
- gigl.transforms.graph_transformer.validate_reserved_anchor_feature_usage(pairwise_bias_attr_names, anchor_bias_attr_names, anchor_input_attr_names, sequence_construction_method)[source]#
Validate placement of the reserved PPR anchor-relative features.
ppr_weightandppr_relation_featuresare produced per (anchor, neighbor) edge, so they may only be requested as anchor-relative token inputs (and, for the scalarppr_weight, as a scalar bias) undersequence_construction_method='ppr'. Shared byheterodata_to_graph_transformer_inputandGraphTransformerEncoderso the rules stay defined in one place.- Parameters:
pairwise_bias_attr_names (list[str]) – Names requested as pairwise attention biases.
anchor_bias_attr_names (list[str]) – Names requested as anchor-relative scalar biases.
anchor_input_attr_names (list[str]) – Names requested as anchor-relative token inputs.
sequence_construction_method (str) – Sequence construction method in use.
- Raises:
ValueError – If a reserved PPR feature is placed where it is not allowed.
- Return type:
None