Neural Network Modules¶
Critic Network¶
CriticNetwork
¶
CriticNetwork(
encoder: Module,
value_head: Module | None = None,
embed_dim: int = 128,
hidden_dim: int = 512,
customized: bool = False,
)
Bases: Module
Create a critic network given an encoder (e.g. as the one in the policy network) with a value head to transform the embeddings to a scalar value.
Parameters:
-
encoder(Module) –Encoder module to encode the input
-
value_head(Module | None, default:None) –Value head to transform the embeddings to a scalar value
-
embed_dim(int, default:128) –Dimension of the embeddings of the value head
-
hidden_dim(int, default:512) –Dimension of the hidden layer of the value head
Methods:
-
forward–Forward pass of the critic network: encode the imput in embedding space and return the value
Source code in rl4co/models/rl/common/critic.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | |
forward
¶
forward(x: Tensor | TensorDict, hidden=None) -> Tensor
Forward pass of the critic network: encode the imput in embedding space and return the value
Parameters:
-
x(Tensor | TensorDict) –Input containing the environment state. Can be a Tensor or a TensorDict
Returns:
-
Tensor–Value of the input state
Source code in rl4co/models/rl/common/critic.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
Graph Neural Networks¶
MultiHeadAttentionLayer
¶
MultiHeadAttentionLayer(
embed_dim: int,
num_heads: int = 8,
feedforward_hidden: int = 512,
normalization: str | None = "batch",
bias: bool = True,
sdpa_fn: Callable | None = None,
moe_kwargs: dict | None = None,
)
Bases: Sequential
Multi-Head Attention Layer with normalization and feed-forward layer
Parameters:
-
embed_dim(int) –dimension of the embeddings
-
num_heads(int, default:8) –number of heads in the MHA
-
feedforward_hidden(int, default:512) –dimension of the hidden layer in the feed-forward layer
-
normalization(str | None, default:'batch') –type of normalization to use (batch, layer, none)
-
sdpa_fn(Callable | None, default:None) –scaled dot product attention function (SDPA)
-
moe_kwargs(dict | None, default:None) –Keyword arguments for MoE
Source code in rl4co/models/nn/graph/attnnet.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
GraphAttentionNetwork
¶
GraphAttentionNetwork(
num_heads: int,
embed_dim: int,
num_layers: int,
normalization: str = "batch",
feedforward_hidden: int = 512,
sdpa_fn: Callable | None = None,
moe_kwargs: dict | None = None,
)
Bases: Module
Graph Attention Network to encode embeddings with a series of MHA layers consisting of a MHA layer, normalization, feed-forward layer, and normalization. Similar to Transformer encoder, as used in Kool et al. (2019).
Parameters:
-
num_heads(int) –number of heads in the MHA
-
embed_dim(int) –dimension of the embeddings
-
num_layers(int) –number of MHA layers
-
normalization(str, default:'batch') –type of normalization to use (batch, layer, none)
-
feedforward_hidden(int, default:512) –dimension of the hidden layer in the feed-forward layer
-
sdpa_fn(Callable | None, default:None) –scaled dot product attention function (SDPA)
-
moe_kwargs(dict | None, default:None) –Keyword arguments for MoE
Methods:
-
forward–Forward pass of the encoder
Source code in rl4co/models/nn/graph/attnnet.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
forward
¶
forward(x: Tensor, mask: Tensor | None = None) -> Tensor
Forward pass of the encoder
Parameters:
-
x(Tensor) –[batch_size, graph_size, embed_dim] initial embeddings to process
-
mask(Tensor | None, default:None) –[batch_size, graph_size, graph_size] mask for the input embeddings. Unused for now.
Source code in rl4co/models/nn/graph/attnnet.py
97 98 99 100 101 102 103 104 105 106 | |
GCNEncoder
¶
GCNEncoder(
env_name: str,
embed_dim: int,
num_layers: int,
init_embedding: Module = None,
residual: bool = True,
edge_idx_fn: EdgeIndexFnSignature = None,
dropout: float = 0.5,
bias: bool = True,
)
Bases: Module
Graph Convolutional Network to encode embeddings with a series of GCN layers from the pytorch geometric package
Parameters:
-
embed_dim(int) –dimension of the embeddings
-
num_nodes–number of nodes in the graph
-
num_gcn_layer–number of GCN layers
-
self_loop–whether to add self loop in the graph
-
residual(bool, default:True) –whether to use residual connection
Methods:
-
forward–Forward pass of the encoder.
Source code in rl4co/models/nn/graph/gcn.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
forward
¶
forward(
td: TensorDict, mask: Tensor | None = None
) -> tuple[Tensor, Tensor]
Forward pass of the encoder. Transform the input TensorDict into a latent representation.
Parameters:
-
td(TensorDict) –Input TensorDict containing the environment state
-
mask(Tensor | None, default:None) –Mask to apply to the attention
Returns:
-
h(Tensor) –Latent representation of the input
-
init_h(Tensor) –Initial embedding of the input
Source code in rl4co/models/nn/graph/gcn.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
MessagePassingEncoder
¶
MessagePassingEncoder(
env_name: str,
embed_dim: int,
num_nodes: int,
num_layers: int,
init_embedding: Module = None,
aggregation: str = "add",
self_loop: bool = False,
residual: bool = True,
)
Bases: Module
Source code in rl4co/models/nn/graph/mpnn.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
Attention Mechanisms¶
Classes:
-
MultiHeadAttention–PyTorch native implementation of Flash Multi-Head Attention with automatic mixed precision support.
-
MultiHeadCrossAttention–PyTorch native implementation of Flash Multi-Head Cross Attention with automatic mixed precision support.
-
PointerAttention–Calculate logits given query, key and value and logit key.
-
PointerAttnMoE–Calculate logits given query, key and value and logit key.
-
MultiHeadCompat– -
PolyNetAttention–Calculate logits given query, key and value and logit key.
Functions:
-
scaled_dot_product_attention_simple–Simple (exact) Scaled Dot-Product Attention in RL4CO without customized kernels (i.e. no Flash Attention).
MultiHeadAttention
¶
MultiHeadAttention(
embed_dim: int,
num_heads: int,
bias: bool = True,
attention_dropout: float = 0.0,
causal: bool = False,
device: str = None,
dtype: dtype = None,
sdpa_fn: Callable | None = None,
)
Bases: Module
PyTorch native implementation of Flash Multi-Head Attention with automatic mixed precision support.
Uses PyTorch's native scaled_dot_product_attention implementation, available from 2.0
Note
If scaled_dot_product_attention is not available, use custom implementation of scaled_dot_product_attention without Flash Attention.
Parameters:
-
embed_dim(int) –total dimension of the model
-
num_heads(int) –number of heads
-
bias(bool, default:True) –whether to use bias
-
attention_dropout(float, default:0.0) –dropout rate for attention weights
-
causal(bool, default:False) –whether to apply causal mask to attention scores
-
device(str, default:None) –torch device
-
dtype(dtype, default:None) –torch dtype
-
sdpa_fn(Callable | None, default:None) –scaled dot product attention function (SDPA) implementation
Methods:
-
forward–x: (batch, seqlen, hidden_dim) (where hidden_dim = num heads * head dim)
Source code in rl4co/models/nn/attention.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
forward
¶
forward(x, attn_mask=None)
x: (batch, seqlen, hidden_dim) (where hidden_dim = num heads * head dim) attn_mask: bool tensor of shape (batch, seqlen)
Source code in rl4co/models/nn/attention.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
MultiHeadCrossAttention
¶
MultiHeadCrossAttention(
embed_dim: int,
num_heads: int,
bias: bool = False,
attention_dropout: float = 0.0,
device: str = None,
dtype: dtype = None,
sdpa_fn: Callable | Module | None = None,
)
Bases: Module
PyTorch native implementation of Flash Multi-Head Cross Attention with automatic mixed precision support.
Uses PyTorch's native scaled_dot_product_attention implementation, available from 2.0
Note
If scaled_dot_product_attention is not available, use custom implementation of scaled_dot_product_attention without Flash Attention.
Parameters:
-
embed_dim(int) –total dimension of the model
-
num_heads(int) –number of heads
-
bias(bool, default:False) –whether to use bias
-
attention_dropout(float, default:0.0) –dropout rate for attention weights
-
device(str, default:None) –torch device
-
dtype(dtype, default:None) –torch dtype
-
sdpa_fn(Callable | Module | None, default:None) –scaled dot product attention function (SDPA)
Source code in rl4co/models/nn/attention.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |
PointerAttention
¶
PointerAttention(
embed_dim: int,
num_heads: int,
mask_inner: bool = True,
out_bias: bool = False,
check_nan: bool = True,
sdpa_fn: Callable | str = "default",
**kwargs
)
Bases: Module
Calculate logits given query, key and value and logit key. This follows the pointer mechanism of Vinyals et al. (2015) (https://arxiv.org/abs/1506.03134).
Note
With Flash Attention, masking is not supported
Performs the following
- Apply cross attention to get the heads
- Project heads to get glimpse
- Compute attention score between glimpse and logit key
Parameters:
-
embed_dim(int) –total dimension of the model
-
num_heads(int) –number of heads
-
mask_inner(bool, default:True) –whether to mask inner attention
-
linear_bias–whether to use bias in linear projection
-
check_nan(bool, default:True) –whether to check for NaNs in logits
-
sdpa_fn(Callable | str, default:'default') –scaled dot product attention function (SDPA) implementation
Methods:
-
forward–Compute attention logits given query, key, value, logit key and attention mask.
Source code in rl4co/models/nn/attention.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
forward
¶
forward(query, key, value, logit_key, attn_mask=None)
Compute attention logits given query, key, value, logit key and attention mask.
Parameters:
-
query–query tensor of shape [B, ..., L, E]
-
key–key tensor of shape [B, ..., S, E]
-
value–value tensor of shape [B, ..., S, E]
-
logit_key–logit key tensor of shape [B, ..., S, E]
-
attn_mask–attention mask tensor of shape [B, ..., S]. Note that
Truemeans that the value should take part in attention as described in the PyTorch Documentation
Source code in rl4co/models/nn/attention.py
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | |
PointerAttnMoE
¶
PointerAttnMoE(
embed_dim: int,
num_heads: int,
mask_inner: bool = True,
out_bias: bool = False,
check_nan: bool = True,
sdpa_fn: Callable | None = None,
moe_kwargs: dict | None = None,
)
Bases: PointerAttention
Calculate logits given query, key and value and logit key. This follows the pointer mechanism of Vinyals et al. (2015) https://arxiv.org/abs/1506.03134, and the MoE gating mechanism of Zhou et al. (2024) https://arxiv.org/abs/2405.01029.
Note
With Flash Attention, masking is not supported
Performs the following
- Apply cross attention to get the heads
- Project heads to get glimpse
- Compute attention score between glimpse and logit key
Parameters:
-
embed_dim(int) –total dimension of the model
-
num_heads(int) –number of heads
-
mask_inner(bool, default:True) –whether to mask inner attention
-
linear_bias–whether to use bias in linear projection
-
check_nan(bool, default:True) –whether to check for NaNs in logits
-
sdpa_fn(Callable | None, default:None) –scaled dot product attention function (SDPA) implementation
-
moe_kwargs(dict | None, default:None) –Keyword arguments for MoE
Source code in rl4co/models/nn/attention.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | |
MultiHeadCompat
¶
MultiHeadCompat(
n_heads,
input_dim,
embed_dim=None,
val_dim=None,
key_dim=None,
)
Bases: Module
Methods:
-
forward–:param q: queries (batch_size, n_query, input_dim)
Source code in rl4co/models/nn/attention.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | |
forward
¶
forward(q, h=None, mask=None)
:param q: queries (batch_size, n_query, input_dim) :param h: data (batch_size, graph_size, input_dim) :param mask: mask (batch_size, n_query, graph_size) or viewable as that (i.e. can be 2 dim if n_query == 1) Mask should contain 1 if attention is not possible (i.e. mask is negative adjacency) :return:
Source code in rl4co/models/nn/attention.py
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
PolyNetAttention
¶
PolyNetAttention(
k: int,
embed_dim: int,
poly_layer_dim: int,
num_heads: int,
**kwargs
)
Bases: PointerAttention
Calculate logits given query, key and value and logit key. This implements a modified version the pointer mechanism of Vinyals et al. (2015) (https://arxiv.org/abs/1506.03134) as described in Hottung et al. (2024) (https://arxiv.org/abs/2402.14048) PolyNetAttention conditions the attention logits on a set of k different binary vectors allowing to learn k different solution strategies.
Note
With Flash Attention, masking is not supported
Performs the following
- Apply cross attention to get the heads
- Project heads to get glimpse
- Apply PolyNet layers
- Compute attention score between glimpse and logit key
Parameters:
-
k(int) –Number unique bit vectors used to compute attention score
-
embed_dim(int) –total dimension of the model
-
poly_layer_dim(int) –Dimension of the PolyNet layers
-
num_heads(int) –number of heads
-
mask_inner–whether to mask inner attention
-
linear_bias–whether to use bias in linear projection
-
check_nan–whether to check for NaNs in logits
-
sdpa_fn–scaled dot product attention function (SDPA) implementation
Methods:
-
forward–Compute attention logits given query, key, value, logit key and attention mask.
Source code in rl4co/models/nn/attention.py
486 487 488 489 490 491 492 493 494 495 496 497 | |
forward
¶
forward(query, key, value, logit_key, attn_mask=None)
Compute attention logits given query, key, value, logit key and attention mask.
Parameters:
-
query–query tensor of shape [B, ..., L, E]
-
key–key tensor of shape [B, ..., S, E]
-
value–value tensor of shape [B, ..., S, E]
-
logit_key–logit key tensor of shape [B, ..., S, E]
-
attn_mask–attention mask tensor of shape [B, ..., S]. Note that
Truemeans that the value should take part in attention as described in the PyTorch Documentation
Source code in rl4co/models/nn/attention.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 | |
scaled_dot_product_attention_simple
¶
scaled_dot_product_attention_simple(
q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False
)
Simple (exact) Scaled Dot-Product Attention in RL4CO without customized kernels (i.e. no Flash Attention).
Source code in rl4co/models/nn/attention.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
Multi-Layer Perceptron¶
MLP
¶
MLP(
input_dim: int,
output_dim: int,
num_neurons: list[int] = [64, 32],
dropout_probs: None | list[float] = None,
hidden_act: str = "ReLU",
out_act: str = "Identity",
input_norm: str = "None",
output_norm: str = "None",
)
Bases: Module
Source code in rl4co/models/nn/mlp.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
Operations¶
PositionalEncoding
¶
PositionalEncoding(
embed_dim: int,
dropout: float = 0.1,
max_len: int = 1000,
)
Bases: Module
Methods:
-
forward–Arguments:
Source code in rl4co/models/nn/ops.py
58 59 60 61 62 63 64 65 66 67 68 69 | |
forward
¶
forward(hidden: Tensor, seq_pos) -> Tensor
Parameters:
-
x–Tensor, shape
[batch_size, seq_len, embedding_dim] -
seq_pos–Tensor, shape
[batch_size, seq_len]
Source code in rl4co/models/nn/ops.py
71 72 73 74 75 76 77 78 79 80 81 | |
RandomEncoding
¶
RandomEncoding(embed_dim: int, max_classes: int = 100)
Bases: Module
This is like torch.nn.Embedding but with rows of embeddings are randomly permuted in each forward pass before lookup operation. This might be useful in cases where classes have no fixed meaning but rather indicate a connection between different elements in a sequence. Reference is the MatNet model.
Source code in rl4co/models/nn/ops.py
114 115 116 117 118 119 | |
Positional Encodings¶
Routing positional encodings. IPE/XPE/Hierarchical: https://arxiv.org/abs/2605.11910
Classes:
-
AbsolutePE–Absolute PE (APE): a learnable lookup table indexed by within-route position.
-
SinusoidalPE–Sinusoidal PE (SIN): fixed sin/cos of the integer index (Vaswani et al., 2017).
-
RotaryPE–Rotary PE (RoPE): query/key rotation rather than an additive embedding.
-
RelativePE–Relative PE (RPE): a learnable bias indexed by signed index offset (Shaw et al., 2018).
-
ALiBiBias–ALiBi: a fixed linear penalty subtracted from attention logits (Press et al., 2021).
-
DACTCyclicPE–DACT cyclic PE: a Gray-code lookup over the cyclic index, projected to
D. -
CycleFormerPE–CycleFormer circular PE: a sinusoidal map of the index wrapped around the tour length.
-
LaplacianPE–Laplacian PE (Lap. PE): the
Ksmallest non-trivial Laplacian eigenvectors. -
RandomWalkSE–Random-Walk Structural Encoding (RWSE): diagonals of random-walk matrix powers.
-
ShortestPathBias–Shortest-path-distance attention bias (SPD): a learnable scalar per integer distance.
-
InRoutePE–In-route PE (IPE): distance-indexed multi-frequency sinusoid (paper §4.1).
-
CrossRoutePE–Cross-route PE (XPE): depot-anchored polar-angle sinusoid (paper §4.2).
-
HierarchicalPE–Hierarchical PE: per-node concatenation
[IPE(v) ‖ XPE(v)](paper §4.3, pre-projection).
Functions:
-
build_route_graph–Build a symmetric adjacency matrix from padded route permutations.
-
get_positional_encoding–Instantiate a positional-encoding module by name.
AbsolutePE
¶
AbsolutePE(embed_dim: int, max_len: int = 1000)
Bases: Module
Absolute PE (APE): a learnable lookup table indexed by within-route position.
Implements PE^APE(v_i) = E_i with E ∈ R^{(max_len + 1) × D} trainable
(index 0 reserved for the depot).
Parameters:
-
embed_dim(int) –Embedding dimension
D. -
max_len(int, default:1000) –Maximum within-route position the table can index (
L_max).
Methods:
-
forward–Look up the per-position embeddings.
Source code in rl4co/utils/pe.py
93 94 95 96 97 | |
forward
¶
forward(positions: Tensor) -> Tensor
Look up the per-position embeddings.
Parameters:
-
positions(Tensor) –Long tensor of shape
[..., L]with within-route indices.
Returns:
-
Tensor–Tensor of shape
[..., L, D].
Source code in rl4co/utils/pe.py
99 100 101 102 103 104 105 106 107 108 | |
SinusoidalPE
¶
SinusoidalPE(embed_dim: int, base: float = 10000.0)
Bases: Module
Sinusoidal PE (SIN): fixed sin/cos of the integer index (Vaswani et al., 2017).
PE^SIN_{2k}(v_i) = sin(i / λ^{2k/D}) and PE^SIN_{2k+1}(v_i) = cos(i / λ^{2k/D})
with λ = 10000 and k = 0 .. D/2 - 1.
Parameters:
-
embed_dim(int) –Embedding dimension
D(assumed even; an oddDdrops the last channel of the cosine half). -
base(float, default:10000.0) –Wavelength base
λ(default10000).
Methods:
-
forward–Compute the sinusoidal encoding for the given positions.
Source code in rl4co/utils/pe.py
123 124 125 126 | |
forward
¶
forward(positions: Tensor) -> Tensor
Compute the sinusoidal encoding for the given positions.
Parameters:
-
positions(Tensor) –Tensor of shape
[..., L](int or float) with within-route indices.
Returns:
-
Tensor–Tensor of shape
[..., L, D].
Source code in rl4co/utils/pe.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
RotaryPE
¶
RotaryPE(embed_dim: int, base: float = 10000.0)
Bases: Module
Rotary PE (RoPE): query/key rotation rather than an additive embedding.
For each channel pair (2k, 2k+1) the query/key is rotated by θ_i = i · λ^{-2k/D}
(Su et al., 2024). The resulting attention logit q_i^T k_j depends only on the
index difference i - j.
Parameters:
-
embed_dim(int) –Per-head dimension
D(assumed even). -
base(float, default:10000.0) –Wavelength base
λ(default10000).
Methods:
-
rotate–Apply the rotary transform to a single tensor.
-
rotate_queries_keys–Rotate both queries and keys by their positions.
-
forward–Alias for :meth:
rotate_queries_keys.
Source code in rl4co/utils/pe.py
158 159 160 161 162 | |
rotate
¶
rotate(x: Tensor, positions: Tensor) -> Tensor
Apply the rotary transform to a single tensor.
Parameters:
-
x(Tensor) –Tensor of shape
[..., L, D]. -
positions(Tensor) –Tensor of shape
[..., L]with the index of each element.
Returns:
-
Tensor–Rotated tensor of the same shape as
x.
Source code in rl4co/utils/pe.py
178 179 180 181 182 183 184 185 186 187 188 189 | |
rotate_queries_keys
¶
rotate_queries_keys(
q: Tensor, k: Tensor, positions: Tensor
) -> tuple[Tensor, Tensor]
Rotate both queries and keys by their positions.
Parameters:
-
q(Tensor) –Query tensor
[..., L, D]. -
k(Tensor) –Key tensor
[..., L, D]. -
positions(Tensor) –Index tensor
[..., L]shared byqandk.
Returns:
-
tuple[Tensor, Tensor]–Tuple
(q_rot, k_rot)with the same shapes as the inputs.
Source code in rl4co/utils/pe.py
191 192 193 194 195 196 197 198 199 200 201 202 | |
forward
¶
forward(
q: Tensor, k: Tensor, positions: Tensor
) -> tuple[Tensor, Tensor]
Alias for :meth:rotate_queries_keys.
Source code in rl4co/utils/pe.py
204 205 206 | |
RelativePE
¶
RelativePE(window: int = 16)
Bases: Module
Relative PE (RPE): a learnable bias indexed by signed index offset (Shaw et al., 2018).
logit(i, j) += b_{clip(i - j, -W, W)} with {b_Δ}_{Δ=-W}^{W} shared across heads.
Parameters:
-
window(int, default:16) –Clipping window
W; offsets are clipped to[-W, W].
Methods:
-
forward–Build the
[L, L]bias matrix added to attention logits.
Source code in rl4co/utils/pe.py
218 219 220 221 | |
forward
¶
forward(
seq_len: int, device: device | None = None
) -> Tensor
Build the [L, L] bias matrix added to attention logits.
Parameters:
-
seq_len(int) –Sequence length
L. -
device(device | None, default:None) –Optional device for the output.
Returns:
-
Tensor–Tensor of shape
[L, L]where entry(i, j)isb_{clip(i-j, -W, W)}.
Source code in rl4co/utils/pe.py
223 224 225 226 227 228 229 230 231 232 233 234 235 | |
ALiBiBias
¶
ALiBiBias(num_heads: int)
Bases: Module
ALiBi: a fixed linear penalty subtracted from attention logits (Press et al., 2021).
logit(i, j) -= m_h · |i - j| with head-specific slopes m_h following the
geometric schedule of the original paper. The returned tensor is shaped
[num_heads, L, L] (broadcasts over the batch dimension).
Parameters:
-
num_heads(int) –Number of attention heads
n_h.
Methods:
-
forward–Build the
[num_heads, L, L]ALiBi bias.
Source code in rl4co/utils/pe.py
249 250 251 252 | |
forward
¶
forward(
seq_len: int, device: device | None = None
) -> Tensor
Build the [num_heads, L, L] ALiBi bias.
Parameters:
-
seq_len(int) –Sequence length
L. -
device(device | None, default:None) –Optional device for the output.
Returns:
-
Tensor–Tensor of shape
[num_heads, L, L]equal to-m_h · |i - j|.
Source code in rl4co/utils/pe.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
DACTCyclicPE
¶
DACTCyclicPE(embed_dim: int, max_len: int = 1000)
Bases: Module
DACT cyclic PE: a Gray-code lookup over the cyclic index, projected to D.
PE^DACT(v_i) = Linear(Gray(i mod L)) (Ma et al., 2021). The Gray code uses
ceil(log2(L)) bits so consecutive cyclic positions differ by exactly one bit; this is
not bit-wise circular when L is not a power of two (documented limitation).
Parameters:
-
embed_dim(int) –Output embedding dimension
D. -
max_len(int, default:1000) –Maximum route length
Lsupported (sets the number of Gray-code bits).
Methods:
-
forward–Encode the within-route positions.
Source code in rl4co/utils/pe.py
301 302 303 304 305 306 307 308 309 310 | |
forward
¶
forward(
positions: Tensor, seq_len: int | None = None
) -> Tensor
Encode the within-route positions.
Parameters:
-
positions(Tensor) –Long tensor
[..., L]of within-route indices. -
seq_len(int | None, default:None) –Route length
Lused for the cyclici mod Lreduction. Defaults topositions.shape[-1].
Returns:
-
Tensor–Tensor of shape
[..., L, D].
Source code in rl4co/utils/pe.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | |
CycleFormerPE
¶
CycleFormerPE(embed_dim: int, base: float = 10000.0)
Bases: Module
CycleFormer circular PE: a sinusoidal map of the index wrapped around the tour length.
PE^Cyc_{2k}(v_i) = sin(2π (i mod L) / L · ω_k) and the cosine counterpart, with the
same geometric frequency schedule as :class:SinusoidalPE (Yook et al., 2024).
Reducing the index modulo L makes the encoding identical for i and i + L
regardless of the frequency schedule.
Parameters:
-
embed_dim(int) –Embedding dimension
D(assumed even). -
base(float, default:10000.0) –Wavelength base
λfor the geometric schedule (default10000).
Methods:
-
forward–Compute the circular sinusoidal encoding.
Source code in rl4co/utils/pe.py
343 344 345 346 | |
forward
¶
forward(
positions: Tensor, seq_len: int | None = None
) -> Tensor
Compute the circular sinusoidal encoding.
Parameters:
-
positions(Tensor) –Tensor
[..., L]of within-route indices. -
seq_len(int | None, default:None) –Tour length
Lfor the2π i / Lwrap. Defaults topositions.shape[-1].
Returns:
-
Tensor–Tensor of shape
[..., L, D].
Source code in rl4co/utils/pe.py
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
LaplacianPE
¶
LaplacianPE(embed_dim: int, k: int = 8)
Bases: Module
Laplacian PE (Lap. PE): the K smallest non-trivial Laplacian eigenvectors.
For each instance the route graph is built (depot plus route arcs), the unnormalized
Laplacian L = diag(deg) - A is formed, and the eigenvectors of the K smallest
non-trivial eigenvalues are taken (Dwivedi & Bresson, 2020). Sign ambiguity is
resolved by random flips during training (deterministic, no flips, in eval). The result
is zero-padded to D columns.
Note: only K_eff = min(K, N - 1) columns can be genuinely non-trivial for a graph on
N nodes; the remaining D - K_eff columns are zeros. Only eigenvector 0 is dropped
(as in PyG), so on a disconnected graph (e.g. unvisited nodes) the leading columns can be
component indicators.
Parameters:
-
embed_dim(int) –Output embedding dimension
D. -
k(int, default:8) –Number of non-trivial eigenvectors to use (default
8).
Methods:
-
forward–Compute the Laplacian eigenvector PE.
Source code in rl4co/utils/pe.py
474 475 476 477 | |
forward
¶
forward(
routes: Tensor | None = None,
adj: Tensor | None = None,
num_nodes: int | None = None,
pad_value: int | None = None,
) -> Tensor
Compute the Laplacian eigenvector PE.
Parameters:
-
routes(Tensor | None, default:None) –Padded route permutations
[..., R, Lr]or[..., Lr]. -
adj(Tensor | None, default:None) –Alternatively, a pre-built symmetric adjacency
[..., N, N]. -
num_nodes(int | None, default:None) –Number of nodes (passed to :func:
build_route_graph). -
pad_value(int | None, default:None) –Padding value to ignore (passed to :func:
build_route_graph).
Returns:
-
Tensor–Tensor of shape
[..., N, D].
Source code in rl4co/utils/pe.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 | |
RandomWalkSE
¶
RandomWalkSE(embed_dim: int, k: int = 8)
Bases: Module
Random-Walk Structural Encoding (RWSE): diagonals of random-walk matrix powers.
PE^RWSE(v) = [(R^k)_{vv}]_{k=1}^{K} with R = D^{-1} A on the route graph
(Dwivedi et al., 2021), zero-padded to D. Isolated nodes (degree 0) get a
zero row of R so their landing probabilities are 0.
Parameters:
-
embed_dim(int) –Output embedding dimension
D. -
k(int, default:8) –Number of random-walk steps
K(default8).
Methods:
-
forward–Compute the random-walk structural encoding.
Source code in rl4co/utils/pe.py
531 532 533 534 | |
forward
¶
forward(
routes: Tensor | None = None,
adj: Tensor | None = None,
num_nodes: int | None = None,
pad_value: int | None = None,
) -> Tensor
Compute the random-walk structural encoding.
Parameters:
-
routes(Tensor | None, default:None) –Padded route permutations
[..., R, Lr]or[..., Lr]. -
adj(Tensor | None, default:None) –Alternatively, a pre-built symmetric adjacency
[..., N, N]. -
num_nodes(int | None, default:None) –Number of nodes (passed to :func:
build_route_graph). -
pad_value(int | None, default:None) –Padding value to ignore (passed to :func:
build_route_graph).
Returns:
-
Tensor–Tensor of shape
[..., N, D]with entries in[0, 1].
Source code in rl4co/utils/pe.py
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | |
ShortestPathBias
¶
ShortestPathBias(max_spd: int = 16)
Bases: Module
Shortest-path-distance attention bias (SPD): a learnable scalar per integer distance.
logit(i, j) += b_{spd(v_i, v_j)} with a learnable scalar bias per integer
shortest-path distance on the route graph (Ying et al., 2021), capped at max_spd
(unreachable pairs are clamped to max_spd).
Parameters:
-
max_spd(int, default:16) –Maximum shortest-path distance the bias table indexes (default
16).
Methods:
-
forward–Compute the
[..., N, N]SPD bias added to attention logits.
Source code in rl4co/utils/pe.py
580 581 582 583 | |
forward
¶
forward(
routes: Tensor | None = None,
adj: Tensor | None = None,
num_nodes: int | None = None,
pad_value: int | None = None,
) -> Tensor
Compute the [..., N, N] SPD bias added to attention logits.
Parameters:
-
routes(Tensor | None, default:None) –Padded route permutations
[..., R, Lr]or[..., Lr]. -
adj(Tensor | None, default:None) –Alternatively, a pre-built symmetric adjacency
[..., N, N]. -
num_nodes(int | None, default:None) –Number of nodes (passed to :func:
build_route_graph). -
pad_value(int | None, default:None) –Padding value to ignore (passed to :func:
build_route_graph).
Returns:
-
Tensor–Tensor of shape
[..., N, N]. It is symmetric and thespd = 0(diagonal) -
Tensor–entries all share the single learnable bias
b_0.
Source code in rl4co/utils/pe.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 | |
InRoutePE
¶
InRoutePE(
embed_dim: int,
direction_aware: bool = False,
eps: float = 1e-09,
)
Bases: Module
In-route PE (IPE): distance-indexed multi-frequency sinusoid (paper §4.1).
For a closed route r = (v_1, ..., v_L) with v_1 = v_L = depot, define the
cumulative travel distance d_i = Σ_{j=2}^{i} ||x_{v_j} - x_{v_{j-1}}|| and rescale it
to one period d̂_i = 2π d_i / d_L ∈ [0, 2π]. Then
direction_aware=True→[sin(ω_k d̂_i), cos(ω_k d̂_i)]_{k=0}^{D/2-1}(distinguishes a route from its reversal: reversal mapsd_i → d_L - d_i, flipping the sine half).direction_aware=False→[cos(ω_k d̂_i)]_{k=0}^{D-1}(invariant to route reversal by construction, sincecos(2π - x) = cos(x)with integer frequencies).
Implementation note: the paper writes ω_k = λ^{-2k/D} (geometric), but the stated
properties IPE(v_1) = IPE(v_L) and the reversal (in)variance only hold for integer
frequencies. This module therefore uses integer harmonics ω_k = k + 1.
Parameters:
-
embed_dim(int) –Output embedding dimension
D. -
direction_aware(bool, default:False) –Whether to use the sin/cos variant (
True) or the cosine-only reversal-invariant variant (False). -
eps(float, default:1e-09) –Small constant guarding the
d_Ldivision for degenerate (zero-length) routes.
Methods:
-
forward–Compute the in-route PE for route-ordered coordinates.
Source code in rl4co/utils/pe.py
648 649 650 651 652 653 654 655 656 657 | |
forward
¶
forward(coords: Tensor) -> Tensor
Compute the in-route PE for route-ordered coordinates.
Parameters:
-
coords(Tensor) –Route-ordered coordinates of shape
[..., L, 2]. The route is assumed closed (coords[..., 0, :] == coords[..., -1, :] == depot).
Returns:
-
Tensor–Tensor of shape
[..., L, D].
Source code in rl4co/utils/pe.py
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
CrossRoutePE
¶
CrossRoutePE(embed_dim: int, k: int = 4)
Bases: Module
Cross-route PE (XPE): depot-anchored polar-angle sinusoid (paper §4.2).
For node v with coordinate x_v and depot x_0, define
θ_v = atan2(y_v - y_0, x_v - x_0) ∈ [-π, π) and encode
XPE(v) = [sin(ω'_k θ_v), cos(ω'_k θ_v)]_{k=0}^{K-1}, ω'_k = 2^k,
zero-padded from 2K to D columns (requires 2K ≤ D). A customer coincident
with the depot yields atan2(0, 0) = 0 (acceptable).
Parameters:
-
embed_dim(int) –Output embedding dimension
D. -
k(int, default:4) –Number of frequency bands
K(default4; must satisfy2K ≤ D).
Methods:
-
forward–Compute the cross-route PE.
Source code in rl4co/utils/pe.py
702 703 704 705 706 707 708 709 710 | |
forward
¶
forward(coords: Tensor, depot: Tensor) -> Tensor
Compute the cross-route PE.
Parameters:
-
coords(Tensor) –Node coordinates of shape
[..., 2]or[..., L, 2]. -
depot(Tensor) –Depot coordinate of shape
[..., 2](broadcast againstcoords).
Returns:
-
Tensor–Tensor of shape
coords.shape[:-1] + (D,).
Source code in rl4co/utils/pe.py
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 | |
HierarchicalPE
¶
HierarchicalPE(
embed_dim: int,
direction_aware: bool = False,
xpe_k: int = 4,
)
Bases: Module
Hierarchical PE: per-node concatenation [IPE(v) ‖ XPE(v)] (paper §4.3, pre-projection).
This produces the positional part of the §4.3 fusion FF([x_v ‖ IPE(v) ‖ XPE(v)]);
the raw-coordinate concatenation and the shared feed-forward projection itself are out of
scope for this module. The output width is 2 * embed_dim (IPE width embed_dim
plus XPE width embed_dim).
Parameters:
-
embed_dim(int) –Per-component embedding dimension
D; the output width is2D. -
direction_aware(bool, default:False) –Forwarded to :class:
InRoutePE. -
xpe_k(int, default:4) –Forwarded to :class:
CrossRoutePEask(default4).
Methods:
-
forward–Compute the concatenated hierarchical PE for a route.
Source code in rl4co/utils/pe.py
748 749 750 751 752 753 | |
forward
¶
forward(
coords: Tensor, depot: Tensor | None = None
) -> Tensor
Compute the concatenated hierarchical PE for a route.
Parameters:
-
coords(Tensor) –Route-ordered coordinates
[..., L, 2](closed route; index0is the depot). -
depot(Tensor | None, default:None) –Optional depot coordinate
[..., 2]. Defaults tocoords[..., 0, :].
Returns:
-
Tensor–Tensor of shape
[..., L, 2D].
Source code in rl4co/utils/pe.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 | |
build_route_graph
¶
build_route_graph(
routes: Tensor,
num_nodes: int | None = None,
pad_value: int | None = None,
) -> Tensor
Build a symmetric adjacency matrix from padded route permutations.
Edges connect consecutive nodes on each route; the depot (index 0) connects to the
route endpoints through the usual closed representation [0, c_1, ..., c_k, 0, ...].
Self-loops (e.g. from zero-padding [..., c_k, 0, 0, 0]) are dropped, and any arc
touching pad_value (when given) is ignored.
Parameters:
-
routes(Tensor) –Long tensor of shape
[..., R, Lr](multiple routes per instance) or[..., Lr](a single route per instance). -
num_nodes(int | None, default:None) –Number of nodes
N(including the depot). Defaults toroutes.max() + 1. -
pad_value(int | None, default:None) –Optional padding value to ignore (e.g.
-1). IfNone, only self-loops are removed.
Returns:
-
Tensor–Symmetric adjacency tensor of shape
[..., N, N]with{0, 1}entries and a -
Tensor–zero diagonal.
Source code in rl4co/utils/pe.py
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | |
get_positional_encoding
¶
get_positional_encoding(name: str, **kwargs) -> Module
Instantiate a positional-encoding module by name.
Parameters:
-
name(str) –One of
"APE" | "SIN" | "RoPE" | "RPE" | "ALiBi" | "LapPE" | "RWSE" | "SPD" | "DACT" | "CycleFormer" | "IPE" | "XPE" | "Hierarchical". -
**kwargs–Forwarded to the selected class constructor.
Returns:
-
Module–The instantiated :class:
torch.nn.Module.
Raises:
-
ValueError–If
nameis not a registered positional encoding.
Source code in rl4co/utils/pe.py
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 | |